| /* A part of the Windows CE C Extra Library (celibc) |
| Copyright 2007-2015 PC GO Ld. |
| |
| This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. |
| */ |
| |
| #include <unistd.h> |
| #include <string.h> |
| #include <errno.h> |
| #include <sys/time.h> |
| #include <sys/stat.h> |
| |
| static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| |
| char *mktemp(char *template) { |
| static uint64_t value; |
| |
| size_t len = strlen(template); |
| char *p = template + len - 6; |
| if(len < 6 || strcmp(p, "XXXXXX")) { |
| errno = EINVAL; |
| goto failed; |
| } |
| |
| struct timeval tv; |
| gettimeofday(&tv, NULL); |
| uint64_t random_time_bits = ((uint64_t) tv.tv_usec << 16) ^ tv.tv_sec; |
| value += random_time_bits ^ getpid(); |
| unsigned int i; |
| for(i=0; i<62*62*62; value+=7777, i++) { |
| uint64_t v = value; |
| /* Fill in the random bits. */ |
| p[0] = letters[v % 62]; |
| v /= 62; |
| p[1] = letters[v % 62]; |
| v /= 62; |
| p[2] = letters[v % 62]; |
| v /= 62; |
| p[3] = letters[v % 62]; |
| v /= 62; |
| p[4] = letters[v % 62]; |
| v /= 62; |
| p[5] = letters[v % 62]; |
| |
| struct stat st; |
| if(stat(template, &st) < 0) { |
| if(errno == ENOENT) return template; |
| goto failed; |
| } |
| } |
| |
| errno = EEXIST; |
| failed: |
| *template = 0; |
| return template; |
| } |