Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/kernel/src/wasm/posix/stdlib.c
1070 views
1
#define _BSD_SOURCE
2
#include <stdlib.h>
3
#include <string.h>
4
#include <fcntl.h>
5
#include <unistd.h>
6
#include <errno.h>
7
8
// Copied from upstream musl, starting at
9
// zig/lib/libc/wasi/libc-top-half/musl/src/temp/mkstemp.c Probably a better
10
// approach would be to CHANGE ZIG so it builds more of libc!? Why the heck
11
// doesn't it already build mkstemp? Maybe it is because they just want to
12
// support the zig language, not a C build toolchain like emscripten is...? Or
13
// it could be the __randname isn't allowed in pure WASM.
14
15
#include <time.h>
16
extern int __clock_gettime(clockid_t, struct timespec *);
17
char *__randname(char *template) {
18
int i;
19
struct timespec ts;
20
unsigned long r;
21
22
__clock_gettime(CLOCK_REALTIME, &ts);
23
// original code was this, but it crashes in webassembly:
24
// r = ts.tv_nsec * 65537 ^ (uintptr_t)&ts / 16 + (uintptr_t) template;
25
// So instead we use this. It is just a source of non-cryptographic
26
// randomness, so it's fine:
27
r = ts.tv_nsec;
28
for (i = 0; i < 6; i++, r >>= 5) {
29
template[i] = 'A' + (r & 15) + (r & 16) * 2;
30
}
31
32
return template;
33
}
34
35
int __mkostemps(char *template, int len, int flags) {
36
size_t l = strlen(template);
37
if (l < 6 || len > l - 6 || memcmp(template + l - len - 6, "XXXXXX", 6)) {
38
errno = EINVAL;
39
return -1;
40
}
41
42
flags -= flags & O_ACCMODE;
43
int fd, retries = 100;
44
do {
45
__randname(template + l - len - 6);
46
if ((fd = open(template, flags | O_RDWR | O_CREAT | O_EXCL, 0600)) >= 0) {
47
return fd;
48
}
49
} while (--retries && errno == EEXIST);
50
51
memcpy(template + l - len - 6, "XXXXXX", 6);
52
return -1;
53
}
54
55
int mkstemp(char *template) { return __mkostemps(template, 0, 0); }
56
57