summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMauri de Souza Nunes <mauri870@gmail.com>2019-09-12 08:43:52 -0300
committerAndreas Kling <awesomekling@gmail.com>2019-09-14 12:05:50 +0200
commit2d24b12a348928b9ad8200f430d81735adfb8753 (patch)
tree87839498c90583aaa34dfcd13159c48aa5ca8348
parent161cb89e87bf0890849e205e98bff56bb0c99898 (diff)
downloadserenity-2d24b12a348928b9ad8200f430d81735adfb8753.zip
LibC: Implement mkdtemp library function
-rw-r--r--Libraries/LibC/stdlib.cpp33
-rw-r--r--Libraries/LibC/stdlib.h1
2 files changed, 32 insertions, 2 deletions
diff --git a/Libraries/LibC/stdlib.cpp b/Libraries/LibC/stdlib.cpp
index 56ec4e91a5..89cafd8e8c 100644
--- a/Libraries/LibC/stdlib.cpp
+++ b/Libraries/LibC/stdlib.cpp
@@ -13,6 +13,7 @@
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
+#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
@@ -278,8 +279,7 @@ char* mktemp(char* pattern)
{
int length = strlen(pattern);
- // FIXME: Check for an invalid template pattern and return EINVAL.
- if (length < 6) {
+ if (length < 6 || !String(pattern).ends_with("XXXXXX")) {
pattern[0] = '\0';
errno = EINVAL;
return pattern;
@@ -302,6 +302,35 @@ char* mktemp(char* pattern)
return pattern;
}
+char* mkdtemp(char* pattern)
+{
+ int length = strlen(pattern);
+
+ if (length < 6 || !String(pattern).ends_with("XXXXXX")) {
+ errno = EINVAL;
+ return nullptr;
+ }
+
+ int start = length - 6;
+
+ static constexpr char random_characters[] = "abcdefghijklmnopqrstuvwxyz0123456789";
+
+ for (int attempt = 0; attempt < 100; ++attempt) {
+ for (int i = 0; i < 6; ++i)
+ pattern[start + i] = random_characters[(rand() % sizeof(random_characters))];
+ struct stat st;
+ int rc = lstat(pattern, &st);
+ if (rc < 0 && errno == ENOENT) {
+ if (mkdir(pattern, 0700) < 0)
+ return nullptr;
+ return pattern;
+ }
+ }
+
+ errno = EEXIST;
+ return nullptr;
+}
+
void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*))
{
dbgprintf("FIXME(LibC): bsearch(%p, %p, %u, %u, %p)\n", key, base, nmemb, size, compar);
diff --git a/Libraries/LibC/stdlib.h b/Libraries/LibC/stdlib.h
index a310ee5e11..08fd255c0a 100644
--- a/Libraries/LibC/stdlib.h
+++ b/Libraries/LibC/stdlib.h
@@ -38,6 +38,7 @@ long labs(long);
double atof(const char*);
int system(const char* command);
char* mktemp(char*);
+char* mkdtemp(char*);
void* bsearch(const void* key, const void* base, size_t nmemb, size_t size, int (*compar)(const void*, const void*));
#define RAND_MAX 32767