Skip to content

Commit eae155d

Browse files
authored
fix CWD sync (#45)
2 parents b15ed3d + c4dc0bc commit eae155d

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

libc-bottom-half/sources/chdir.c

+28-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ void __wasilibc_cwd_unlock(void);
1717
#endif
1818
extern char *__wasilibc_cwd;
1919
static int __wasilibc_cwd_mallocd = 0;
20+
static int __wasilibc_cwd_is_synced = 0;
2021

2122
int chdir_legacy(const char *path)
2223
{
@@ -62,15 +63,41 @@ int chdir_legacy(const char *path)
6263
__wasilibc_cwd_lock();
6364
char *prev_cwd = __wasilibc_cwd;
6465
__wasilibc_cwd = new_cwd;
65-
__wasilibc_cwd_unlock();
6666

6767
if (__wasilibc_cwd_mallocd)
6868
free(prev_cwd);
69+
6970
__wasilibc_cwd_mallocd = 1;
71+
__wasilibc_cwd_unlock();
7072
return 0;
7173
}
7274

7375
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+
74101
static char *make_absolute_buf = NULL;
75102
static size_t make_absolute_len = 0;
76103

@@ -97,7 +124,6 @@ static const char *make_absolute(const char *path) {
97124
__wasilibc_cwd_lock();
98125
size_t cwd_len = strlen(__wasilibc_cwd);
99126
size_t path_len = path ? strlen(path) : 0;
100-
__wasilibc_cwd_unlock();
101127
int need_slash = __wasilibc_cwd[cwd_len - 1] == '/' ? 0 : 1;
102128
size_t alloc_len = cwd_len + path_len + 1 + need_slash;
103129
if (alloc_len > make_absolute_len) {

0 commit comments

Comments
 (0)