@@ -17,6 +17,7 @@ void __wasilibc_cwd_unlock(void);
17
17
#endif
18
18
extern char * __wasilibc_cwd ;
19
19
static int __wasilibc_cwd_mallocd = 0 ;
20
+ static int __wasilibc_cwd_is_synced = 0 ;
20
21
21
22
int chdir_legacy (const char * path )
22
23
{
@@ -62,15 +63,41 @@ int chdir_legacy(const char *path)
62
63
__wasilibc_cwd_lock ();
63
64
char * prev_cwd = __wasilibc_cwd ;
64
65
__wasilibc_cwd = new_cwd ;
65
- __wasilibc_cwd_unlock ();
66
66
67
67
if (__wasilibc_cwd_mallocd )
68
68
free (prev_cwd );
69
+
69
70
__wasilibc_cwd_mallocd = 1 ;
71
+ __wasilibc_cwd_unlock ();
70
72
return 0 ;
71
73
}
72
74
73
75
static const char * make_absolute (const char * path ) {
76
+ // if the libc has not synced with the runtime yet, call into the runtime to get the cwd
77
+ if (!__wasilibc_cwd_is_synced ) {
78
+ char cwd [256 ];
79
+ if (getcwd (cwd , sizeof (cwd )) != NULL ) {
80
+ char * new_cwd = malloc (strlen (cwd ) + 1 );
81
+ if (new_cwd != NULL ) {
82
+ strcpy (new_cwd , cwd );
83
+ }
84
+
85
+ __wasilibc_cwd_lock ();
86
+ char * prev_cwd = __wasilibc_cwd ;
87
+ __wasilibc_cwd = new_cwd ;
88
+
89
+ if (__wasilibc_cwd_mallocd )
90
+ free (prev_cwd );
91
+
92
+ __wasilibc_cwd_is_synced = 1 ; // we synced the cwd
93
+ __wasilibc_cwd_mallocd = 1 ; // we allocated so next time, prev_cwd must be freed.
94
+ __wasilibc_cwd_unlock ();
95
+ } else {
96
+ return NULL ;
97
+ }
98
+ }
99
+
100
+
74
101
static char * make_absolute_buf = NULL ;
75
102
static size_t make_absolute_len = 0 ;
76
103
@@ -97,7 +124,6 @@ static const char *make_absolute(const char *path) {
97
124
__wasilibc_cwd_lock ();
98
125
size_t cwd_len = strlen (__wasilibc_cwd );
99
126
size_t path_len = path ? strlen (path ) : 0 ;
100
- __wasilibc_cwd_unlock ();
101
127
int need_slash = __wasilibc_cwd [cwd_len - 1 ] == '/' ? 0 : 1 ;
102
128
size_t alloc_len = cwd_len + path_len + 1 + need_slash ;
103
129
if (alloc_len > make_absolute_len ) {
0 commit comments