1 //===- unittest/Support/ProgramTest.cpp -----------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/Program.h"
10 #include "llvm/Config/llvm-config.h"
11 #include "llvm/Support/CommandLine.h"
12 #include "llvm/Support/ConvertUTF.h"
13 #include "llvm/Support/FileSystem.h"
14 #include "llvm/Support/Path.h"
15 #include "gtest/gtest.h"
18 #if defined(__APPLE__)
19 # include <crt_externs.h>
20 #elif !defined(_MSC_VER)
21 // Forward declare environ in case it's not provided by stdlib.h.
22 extern char **environ
;
25 #if defined(LLVM_ON_UNIX)
27 void sleep_for(unsigned int seconds
) {
32 void sleep_for(unsigned int seconds
) {
33 Sleep(seconds
* 1000);
36 #error sleep_for is not implemented on your platform.
39 #define ASSERT_NO_ERROR(x) \
40 if (std::error_code ASSERT_NO_ERROR_ec = x) { \
41 SmallString<128> MessageStorage; \
42 raw_svector_ostream Message(MessageStorage); \
43 Message << #x ": did not return errc::success.\n" \
44 << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \
45 << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \
46 GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \
50 extern const char *TestMainArgv0
;
57 static cl::opt
<std::string
>
58 ProgramTestStringArg1("program-test-string-arg1");
59 static cl::opt
<std::string
>
60 ProgramTestStringArg2("program-test-string-arg2");
62 class ProgramEnvTest
: public testing::Test
{
63 std::vector
<StringRef
> EnvTable
;
64 std::vector
<std::string
> EnvStorage
;
67 void SetUp() override
{
70 _wgetenv(L
"TMP"); // Populate _wenviron, initially is null
72 #elif defined(__APPLE__)
73 return *_NSGetEnviron();
80 auto prepareEnvVar
= [this](decltype(*EnvP
) Var
) -> StringRef
{
82 // On Windows convert UTF16 encoded variable to UTF8
83 auto Len
= wcslen(Var
);
84 ArrayRef
<char> Ref
{reinterpret_cast<char const *>(Var
),
86 EnvStorage
.emplace_back();
87 auto convStatus
= convertUTF16ToUTF8String(Ref
, EnvStorage
.back());
88 EXPECT_TRUE(convStatus
);
89 return EnvStorage
.back();
92 return StringRef(Var
);
96 while (*EnvP
!= nullptr) {
97 EnvTable
.emplace_back(prepareEnvVar(*EnvP
));
102 void TearDown() override
{
107 void addEnvVar(StringRef Var
) { EnvTable
.emplace_back(Var
); }
109 ArrayRef
<StringRef
> getEnviron() const { return EnvTable
; }
113 void checkSeparators(StringRef Path
) {
114 char UndesiredSeparator
= sys::path::get_separator()[0] == '/' ? '\\' : '/';
115 ASSERT_EQ(Path
.find(UndesiredSeparator
), StringRef::npos
);
118 TEST_F(ProgramEnvTest
, CreateProcessLongPath
) {
119 if (getenv("LLVM_PROGRAM_TEST_LONG_PATH"))
122 // getMainExecutable returns an absolute path; prepend the long-path prefix.
123 SmallString
<128> MyAbsExe(
124 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
));
125 checkSeparators(MyAbsExe
);
126 // Force a path with backslashes, when we are going to prepend the \\?\
128 sys::path::native(MyAbsExe
, sys::path::Style::windows_backslash
);
130 if (!StringRef(MyAbsExe
).startswith("\\\\?\\"))
131 MyExe
.append("\\\\?\\");
132 MyExe
.append(std::string(MyAbsExe
.begin(), MyAbsExe
.end()));
134 StringRef ArgV
[] = {MyExe
,
135 "--gtest_filter=ProgramEnvTest.CreateProcessLongPath"};
137 // Add LLVM_PROGRAM_TEST_LONG_PATH to the environment of the child.
138 addEnvVar("LLVM_PROGRAM_TEST_LONG_PATH=1");
140 // Redirect stdout to a long path.
141 SmallString
<128> TestDirectory
;
143 fs::createUniqueDirectory("program-redirect-test", TestDirectory
));
144 SmallString
<256> LongPath(TestDirectory
);
145 LongPath
.push_back('\\');
147 LongPath
.append(260 - TestDirectory
.size(), 'a');
150 bool ExecutionFailed
;
151 Optional
<StringRef
> Redirects
[] = {None
, LongPath
.str(), None
};
152 int RC
= ExecuteAndWait(MyExe
, ArgV
, getEnviron(), Redirects
,
153 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &Error
,
155 EXPECT_FALSE(ExecutionFailed
) << Error
;
158 // Remove the long stdout.
159 ASSERT_NO_ERROR(fs::remove(Twine(LongPath
)));
160 ASSERT_NO_ERROR(fs::remove(Twine(TestDirectory
)));
164 TEST_F(ProgramEnvTest
, CreateProcessTrailingSlash
) {
165 if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
166 if (ProgramTestStringArg1
== "has\\\\ trailing\\" &&
167 ProgramTestStringArg2
== "has\\\\ trailing\\") {
168 exit(0); // Success! The arguments were passed and parsed.
174 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
);
177 "--gtest_filter=ProgramEnvTest.CreateProcessTrailingSlash",
178 "-program-test-string-arg1",
179 "has\\\\ trailing\\",
180 "-program-test-string-arg2",
181 "has\\\\ trailing\\"};
183 // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
184 addEnvVar("LLVM_PROGRAM_TEST_CHILD=1");
187 bool ExecutionFailed
;
188 // Redirect stdout and stdin to NUL, but let stderr through.
190 StringRef
nul("NUL");
192 StringRef
nul("/dev/null");
194 Optional
<StringRef
> redirects
[] = { nul
, nul
, None
};
195 int rc
= ExecuteAndWait(my_exe
, argv
, getEnviron(), redirects
,
196 /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error
,
198 EXPECT_FALSE(ExecutionFailed
) << error
;
202 TEST_F(ProgramEnvTest
, TestExecuteNoWait
) {
203 using namespace llvm::sys
;
205 if (getenv("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT")) {
206 sleep_for(/*seconds*/ 1);
210 std::string Executable
=
211 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
);
212 StringRef argv
[] = {Executable
,
213 "--gtest_filter=ProgramEnvTest.TestExecuteNoWait"};
215 // Add LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT to the environment of the child.
216 addEnvVar("LLVM_PROGRAM_TEST_EXECUTE_NO_WAIT=1");
219 bool ExecutionFailed
;
220 ProcessInfo PI1
= ExecuteNoWait(Executable
, argv
, getEnviron(), {}, 0, &Error
,
222 ASSERT_FALSE(ExecutionFailed
) << Error
;
223 ASSERT_NE(PI1
.Pid
, ProcessInfo::InvalidPid
) << "Invalid process id";
225 unsigned LoopCount
= 0;
227 // Test that Wait() with WaitUntilTerminates=true works. In this case,
228 // LoopCount should only be incremented once.
231 ProcessInfo WaitResult
= llvm::sys::Wait(PI1
, 0, true, &Error
);
232 ASSERT_TRUE(Error
.empty());
233 if (WaitResult
.Pid
== PI1
.Pid
)
237 EXPECT_EQ(LoopCount
, 1u) << "LoopCount should be 1";
239 ProcessInfo PI2
= ExecuteNoWait(Executable
, argv
, getEnviron(), {}, 0, &Error
,
241 ASSERT_FALSE(ExecutionFailed
) << Error
;
242 ASSERT_NE(PI2
.Pid
, ProcessInfo::InvalidPid
) << "Invalid process id";
244 // Test that Wait() with SecondsToWait=0 performs a non-blocking wait. In this
245 // cse, LoopCount should be greater than 1 (more than one increment occurs).
248 ProcessInfo WaitResult
= llvm::sys::Wait(PI2
, 0, false, &Error
);
249 ASSERT_TRUE(Error
.empty());
250 if (WaitResult
.Pid
== PI2
.Pid
)
254 ASSERT_GT(LoopCount
, 1u) << "LoopCount should be >1";
257 TEST_F(ProgramEnvTest
, TestExecuteAndWaitTimeout
) {
258 using namespace llvm::sys
;
260 if (getenv("LLVM_PROGRAM_TEST_TIMEOUT")) {
261 sleep_for(/*seconds*/ 10);
265 std::string Executable
=
266 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
);
268 Executable
, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitTimeout"};
270 // Add LLVM_PROGRAM_TEST_TIMEOUT to the environment of the child.
271 addEnvVar("LLVM_PROGRAM_TEST_TIMEOUT=1");
274 bool ExecutionFailed
;
276 ExecuteAndWait(Executable
, argv
, getEnviron(), {}, /*secondsToWait=*/1, 0,
277 &Error
, &ExecutionFailed
);
278 ASSERT_EQ(-2, RetCode
);
281 TEST(ProgramTest
, TestExecuteNegative
) {
282 std::string Executable
= "i_dont_exist";
283 StringRef argv
[] = {Executable
};
287 bool ExecutionFailed
;
288 int RetCode
= ExecuteAndWait(Executable
, argv
, llvm::None
, {}, 0, 0, &Error
,
290 ASSERT_TRUE(RetCode
< 0) << "On error ExecuteAndWait should return 0 or "
291 "positive value indicating the result code";
292 ASSERT_TRUE(ExecutionFailed
);
293 ASSERT_FALSE(Error
.empty());
298 bool ExecutionFailed
;
299 ProcessInfo PI
= ExecuteNoWait(Executable
, argv
, llvm::None
, {}, 0, &Error
,
301 ASSERT_EQ(PI
.Pid
, ProcessInfo::InvalidPid
)
302 << "On error ExecuteNoWait should return an invalid ProcessInfo";
303 ASSERT_TRUE(ExecutionFailed
);
304 ASSERT_FALSE(Error
.empty());
310 const char utf16le_text
[] =
311 "\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61\x00";
312 const char utf16be_text
[] =
313 "\x00\x6c\x00\x69\x00\x6e\x00\x67\x00\xfc\x00\x69\x00\xe7\x00\x61";
315 const char utf8_text
[] = "\x6c\x69\x6e\x67\xc3\xbc\x69\xc3\xa7\x61";
317 TEST(ProgramTest
, TestWriteWithSystemEncoding
) {
318 SmallString
<128> TestDirectory
;
319 ASSERT_NO_ERROR(fs::createUniqueDirectory("program-test", TestDirectory
));
320 errs() << "Test Directory: " << TestDirectory
<< '\n';
322 SmallString
<128> file_pathname(TestDirectory
);
323 path::append(file_pathname
, "international-file.txt");
324 // Only on Windows we should encode in UTF16. For other systems, use UTF8
325 ASSERT_NO_ERROR(sys::writeFileWithEncoding(file_pathname
.c_str(), utf8_text
,
328 ASSERT_NO_ERROR(fs::openFileForRead(file_pathname
.c_str(), fd
));
331 ASSERT_EQ(::read(fd
, buf
, 18), 18);
332 const char *utf16_text
;
333 if (strncmp(buf
, "\xfe\xff", 2) == 0) { // UTF16-BE
334 utf16_text
= utf16be_text
;
335 } else if (strncmp(buf
, "\xff\xfe", 2) == 0) { // UTF16-LE
336 utf16_text
= utf16le_text
;
338 FAIL() << "Invalid BOM in UTF-16 file";
340 ASSERT_EQ(strncmp(&buf
[2], utf16_text
, 16), 0);
343 ASSERT_EQ(::read(fd
, buf
, 10), 10);
344 ASSERT_EQ(strncmp(buf
, utf8_text
, 10), 0);
347 ASSERT_NO_ERROR(fs::remove(file_pathname
.str()));
348 ASSERT_NO_ERROR(fs::remove(TestDirectory
.str()));
351 TEST_F(ProgramEnvTest
, TestExecuteAndWaitStatistics
) {
352 using namespace llvm::sys
;
354 if (getenv("LLVM_PROGRAM_TEST_STATISTICS"))
357 std::string Executable
=
358 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
);
360 Executable
, "--gtest_filter=ProgramEnvTest.TestExecuteAndWaitStatistics"};
362 // Add LLVM_PROGRAM_TEST_STATISTICS to the environment of the child.
363 addEnvVar("LLVM_PROGRAM_TEST_STATISTICS=1");
366 bool ExecutionFailed
;
367 Optional
<ProcessStatistics
> ProcStat
;
368 int RetCode
= ExecuteAndWait(Executable
, argv
, getEnviron(), {}, 0, 0, &Error
,
369 &ExecutionFailed
, &ProcStat
);
370 ASSERT_EQ(0, RetCode
);
371 ASSERT_TRUE(ProcStat
);
372 ASSERT_GE(ProcStat
->UserTime
, std::chrono::microseconds(0));
373 ASSERT_GE(ProcStat
->TotalTime
, ProcStat
->UserTime
);
376 TEST_F(ProgramEnvTest
, TestLockFile
) {
377 using namespace llvm::sys
;
379 if (const char *LockedFile
= getenv("LLVM_PROGRAM_TEST_LOCKED_FILE")) {
382 ASSERT_NO_ERROR(fs::openFileForReadWrite(LockedFile
, FD2
,
383 fs::CD_OpenExisting
, fs::OF_None
));
385 std::error_code ErrC
= fs::tryLockFile(FD2
, std::chrono::seconds(5));
386 ASSERT_NO_ERROR(ErrC
);
387 ASSERT_NO_ERROR(fs::unlockFile(FD2
));
392 // Create file that will be locked.
393 SmallString
<64> LockedFile
;
396 fs::createTemporaryFile("TestLockFile", "temp", FD1
, LockedFile
));
398 std::string Executable
=
399 sys::fs::getMainExecutable(TestMainArgv0
, &ProgramTestStringArg1
);
400 StringRef argv
[] = {Executable
, "--gtest_filter=ProgramEnvTest.TestLockFile"};
402 // Add LLVM_PROGRAM_TEST_LOCKED_FILE to the environment of the child.
403 std::string EnvVar
= "LLVM_PROGRAM_TEST_LOCKED_FILE=";
404 EnvVar
+= LockedFile
.str();
408 ASSERT_NO_ERROR(fs::tryLockFile(FD1
));
411 bool ExecutionFailed
;
412 ProcessInfo PI2
= ExecuteNoWait(Executable
, argv
, getEnviron(), {}, 0, &Error
,
414 ASSERT_FALSE(ExecutionFailed
) << Error
;
415 ASSERT_TRUE(Error
.empty());
416 ASSERT_NE(PI2
.Pid
, ProcessInfo::InvalidPid
) << "Invalid process id";
418 // Wait some time to give the child process a chance to start.
419 std::this_thread::sleep_for(std::chrono::milliseconds(100));
421 ASSERT_NO_ERROR(fs::unlockFile(FD1
));
422 ProcessInfo WaitResult
= llvm::sys::Wait(PI2
, 5 /* seconds */, true, &Error
);
423 ASSERT_TRUE(Error
.empty());
424 ASSERT_EQ(0, WaitResult
.ReturnCode
);
425 ASSERT_EQ(WaitResult
.Pid
, PI2
.Pid
);
426 sys::fs::remove(LockedFile
);
429 } // end anonymous namespace