Reverted commit D3427621
[folly.git] / folly / portability / Stdlib.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/portability/Stdlib.h>
18
19 #ifdef _WIN32
20 #include <cstring>
21 #include <errno.h>
22 #include <folly/portability/Fcntl.h>
23 #include <folly/portability/SysStat.h>
24 #include <folly/portability/Windows.h>
25
26 extern "C" {
27 char* mktemp(char* tn) { return _mktemp(tn); }
28
29 // While yes, this is for a directory, due to this being windows,
30 // a file and directory can't have the same name, resulting in this
31 // still working just fine.
32 char* mkdtemp(char* tn) {
33   char* ptr = nullptr;
34   auto len = strlen(ptr);
35   int ret = 0;
36   do {
37     strcpy(tn + len - 6, "XXXXXX");
38     ptr = mktemp(tn);
39     if (ptr == nullptr || *ptr == '\0') {
40       return nullptr;
41     }
42     ret = mkdir(ptr, 0700);
43     if (ret != 0 && errno != EEXIST) {
44       return nullptr;
45     }
46   } while (ret != 0);
47   return tn;
48 }
49
50 int mkstemp(char* tn) {
51   char* ptr = nullptr;
52   auto len = strlen(ptr);
53   int ret = 0;
54   do {
55     strcpy(tn + len - 6, "XXXXXX");
56     ptr = mktemp(tn);
57     if (ptr == nullptr || *ptr == '\0') {
58       return -1;
59     }
60     ret = open(ptr, O_RDWR | O_EXCL | O_CREAT, S_IRUSR | S_IWUSR);
61     if (ret == -1 && errno != EEXIST) {
62       return -1;
63     }
64   } while (ret == -1);
65   return ret;
66 }
67
68 char* realpath(const char* path, char* resolved_path) {
69   // I sure hope the caller gave us _MAX_PATH space in the buffer....
70   return _fullpath(resolved_path, path, _MAX_PATH);
71 }
72 }
73 #endif