Path: blob/main/core/kernel/src/wasm/posix/stdlib.c
1070 views
#define _BSD_SOURCE1#include <stdlib.h>2#include <string.h>3#include <fcntl.h>4#include <unistd.h>5#include <errno.h>67// Copied from upstream musl, starting at8// zig/lib/libc/wasi/libc-top-half/musl/src/temp/mkstemp.c Probably a better9// approach would be to CHANGE ZIG so it builds more of libc!? Why the heck10// doesn't it already build mkstemp? Maybe it is because they just want to11// support the zig language, not a C build toolchain like emscripten is...? Or12// it could be the __randname isn't allowed in pure WASM.1314#include <time.h>15extern int __clock_gettime(clockid_t, struct timespec *);16char *__randname(char *template) {17int i;18struct timespec ts;19unsigned long r;2021__clock_gettime(CLOCK_REALTIME, &ts);22// original code was this, but it crashes in webassembly:23// r = ts.tv_nsec * 65537 ^ (uintptr_t)&ts / 16 + (uintptr_t) template;24// So instead we use this. It is just a source of non-cryptographic25// randomness, so it's fine:26r = ts.tv_nsec;27for (i = 0; i < 6; i++, r >>= 5) {28template[i] = 'A' + (r & 15) + (r & 16) * 2;29}3031return template;32}3334int __mkostemps(char *template, int len, int flags) {35size_t l = strlen(template);36if (l < 6 || len > l - 6 || memcmp(template + l - len - 6, "XXXXXX", 6)) {37errno = EINVAL;38return -1;39}4041flags -= flags & O_ACCMODE;42int fd, retries = 100;43do {44__randname(template + l - len - 6);45if ((fd = open(template, flags | O_RDWR | O_CREAT | O_EXCL, 0600)) >= 0) {46return fd;47}48} while (--retries && errno == EEXIST);4950memcpy(template + l - len - 6, "XXXXXX", 6);51return -1;52}5354int mkstemp(char *template) { return __mkostemps(template, 0, 0); }555657