Skip to content

Commit 5216983

Browse files
authored
Avoid a strdup call in __wasilibc_populate_libpreopen. (#128)
* Avoid a `strdup` call in `__wasilibc_populate_libpreopen`. Optimize `__wasilibc_populate_libpreopen` to avoid calling `strdup` in the common case where it's called from `__wasilibc_populate_libpreopen`. * Convert an if into a ?:.
1 parent 70099d4 commit 5216983

1 file changed

Lines changed: 16 additions & 10 deletions

File tree

libc-bottom-half/libpreopen/libpreopen.c

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -452,13 +452,15 @@ po_map_assertvalid(void)
452452
#endif
453453

454454
/// Register the given pre-opened file descriptor under the given path.
455-
int
456-
__wasilibc_register_preopened_fd(int fd, const char *path)
455+
///
456+
/// This function takes ownership of `name`.
457+
static int
458+
internal_register_preopened_fd(int fd, const char *name)
457459
{
458460
po_map_assertvalid();
459461

460462
assert(fd >= 0);
461-
assert(path != NULL);
463+
assert(name != NULL);
462464

463465
if (global_map.length == global_map.capacity) {
464466
int n = po_map_enlarge();
@@ -477,11 +479,6 @@ __wasilibc_register_preopened_fd(int fd, const char *path)
477479
return -1; // TODO: Add an infallible way to get the rights?
478480
}
479481

480-
const char *name = strdup(path);
481-
if (name == NULL) {
482-
return -1;
483-
}
484-
485482
struct po_map_entry *entry = &global_map.entries[global_map.length++];
486483

487484
entry->name = name;
@@ -494,6 +491,16 @@ __wasilibc_register_preopened_fd(int fd, const char *path)
494491
return 0;
495492
}
496493

494+
/// Register the given pre-opened file descriptor under the given path.
495+
///
496+
/// This function does not take ownership of `path`.
497+
int
498+
__wasilibc_register_preopened_fd(int fd, const char *path)
499+
{
500+
const char *name = strdup(path);
501+
return name == NULL ? -1 : __wasilibc_register_preopened_fd(fd, name);
502+
}
503+
497504
int
498505
__wasilibc_find_relpath(
499506
const char *path,
@@ -583,12 +590,11 @@ __wasilibc_populate_libpreopen(void)
583590
}
584591
path[prestat.u.dir.pr_name_len] = '\0';
585592

586-
if (__wasilibc_register_preopened_fd(fd, path) != 0) {
593+
if (internal_register_preopened_fd(fd, path) != 0) {
587594
free(path);
588595
return __WASI_ENOMEM;
589596
}
590597

591-
free(path);
592598
break;
593599
}
594600
default:

0 commit comments

Comments
 (0)