Skip to content

Commit d9c5a90

Browse files
committed
[libcxx] Add fallback to standard C when unistd is unavailable
Summary: This utility function gets a temp file to use for tests. It either uses WIN32 or POSIX to create it. Some targets only follow the C standard, and this test case will fail. This patch simply adds a fallback that uses the `tmpnam` function from standard C. This function isn't ideal, but it is good enough for our use-case.
1 parent 9fea731 commit d9c5a90

File tree

1 file changed

+34
-23
lines changed

1 file changed

+34
-23
lines changed

libcxx/test/support/platform_support.h

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,10 @@
4040
# include <io.h> // _mktemp_s
4141
# include <fcntl.h> // _O_EXCL, ...
4242
# include <sys/stat.h> // _S_IREAD, ...
43+
#elif __has_include(<unistd.h>)
44+
# include <unistd.h> // close
4345
#else
44-
# include <unistd.h> // close
46+
# define TEST_TEMP_FALLBACK
4547
#endif
4648

4749
#if defined(_CS_GNU_LIBC_VERSION)
@@ -55,31 +57,40 @@ extern "C" {
5557
}
5658
#endif
5759

58-
inline
59-
std::string get_temp_file_name()
60-
{
60+
inline std::string get_temp_file_name() {
6161
#if defined(_WIN32)
62-
while (true) {
63-
char Name[] = "libcxx.XXXXXX";
64-
if (_mktemp_s(Name, sizeof(Name)) != 0) abort();
65-
int fd = _open(Name, _O_RDWR | _O_CREAT | _O_EXCL, _S_IREAD | _S_IWRITE);
66-
if (fd != -1) {
67-
_close(fd);
68-
return Name;
69-
}
70-
if (errno == EEXIST)
71-
continue;
72-
abort();
62+
while (true) {
63+
char Name[] = "libcxx.XXXXXX";
64+
if (_mktemp_s(Name, sizeof(Name)) != 0)
65+
abort();
66+
int fd = _open(Name, _O_RDWR | _O_CREAT | _O_EXCL, _S_IREAD | _S_IWRITE);
67+
if (fd != -1) {
68+
_close(fd);
69+
return Name;
7370
}
71+
if (errno == EEXIST)
72+
continue;
73+
abort();
74+
}
75+
#elif defined(TEST_TEMP_FALLBACK)
76+
char* filename = tmpnam(nullptr);
77+
if (!filename)
78+
abort();
79+
FILE* file = fopen(filename, "w");
80+
if (!file)
81+
abort();
82+
if (fclose(file) == EOF)
83+
abort();
84+
return std::string(filename);
7485
#else
75-
std::string Name = "libcxx.XXXXXX";
76-
int FD = mkstemp(&Name[0]);
77-
if (FD == -1) {
78-
perror("mkstemp");
79-
abort();
80-
}
81-
close(FD);
82-
return Name;
86+
std::string Name = "libcxx.XXXXXX";
87+
int FD = mkstemp(&Name[0]);
88+
if (FD == -1) {
89+
perror("mkstemp");
90+
abort();
91+
}
92+
close(FD);
93+
return Name;
8394
#endif
8495
}
8596

0 commit comments

Comments
 (0)