On some systems /tmp may be inaccessible and instead $TMPDIR is supposed to be used. Prefer that and fall back to /tmp if undefined or empty. Also check return values of mkstemp and ftruncate.
Unified · Split
| @@ -120,11 +120,22 @@ static int rt_mem(TCCState *s1, int size) · 119 unmodified lines | ||
| 120 | 120 | #ifdef CONFIG_SELINUX |
| 121 | 121 | /* Using mmap instead of malloc */ |
| 122 | 122 | void *prw; |
| 123 | − char tmpfname[] = "/tmp/.tccrunXXXXXX"; | |
| 124 | − int fd = mkstemp(tmpfname); | |
| 123 | + static const char *tmpdir; | |
| 124 | + char tmpfname[256]; | |
| 125 | + int fd; | |
| 126 | + | |
| 127 | + if (tmpdir == NULL) { | |
| 128 | + tmpdir = getenv("TMPDIR"); | |
| 129 | + if (tmpdir == NULL || *tmpdir == 0) | |
| 130 | + tmpdir = "/tmp"; | |
| 131 | + } | |
| 132 | + snprintf(tmpfname, sizeof(tmpfname), "%s/.tccrunXXXXXX", tmpdir); | |
| 133 | + fd = mkstemp(tmpfname); | |
| 134 | + if (fd < 0) | |
| 135 | + return tcc_error_noabort("tccrun: could not create temp file"); | |
| 125 | 136 | unlink(tmpfname); |
| 126 | − ftruncate(fd, size); | |
| 127 | − | |
| 137 | + if (ftruncate(fd, size) < 0) | |
| 138 | + return tcc_error_noabort("tccrun: could not resize temp file"); | |
| 128 | 139 | ptr = mmap(NULL, size * 2, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0); |
| 129 | 140 | /* mmap RW memory at fixed distance */ |
| 130 | 141 | prw = mmap((char*)ptr + size, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_FIXED, fd, 0); |