DataFlowSanitizer: Factor the wrapper builder out to buildWrapperFunction.
[oota-llvm.git] / unittests / Support / ProgramTest.cpp
1 //===- unittest/Support/ProgramTest.cpp -----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Support/CommandLine.h"
11 #include "llvm/Support/FileSystem.h"
12 #include "llvm/Support/Path.h"
13 #include "llvm/Support/Program.h"
14 #include "gtest/gtest.h"
15
16 #include <stdlib.h>
17 #if defined(__APPLE__)
18 # include <crt_externs.h>
19 #elif !defined(_MSC_VER)
20 // Forward declare environ in case it's not provided by stdlib.h.
21 extern char **environ;
22 #endif
23
24 // From TestMain.cpp.
25 extern const char *TestMainArgv0;
26
27 namespace {
28
29 using namespace llvm;
30 using namespace sys;
31
32 static cl::opt<std::string>
33 ProgramTestStringArg1("program-test-string-arg1");
34 static cl::opt<std::string>
35 ProgramTestStringArg2("program-test-string-arg2");
36
37 static void CopyEnvironment(std::vector<const char *> &out) {
38 #ifdef __APPLE__
39   char **envp = *_NSGetEnviron();
40 #else
41   // environ seems to work for Windows and most other Unices.
42   char **envp = environ;
43 #endif
44   while (*envp != 0) {
45     out.push_back(*envp);
46     ++envp;
47   }
48 }
49
50 TEST(ProgramTest, CreateProcessTrailingSlash) {
51   if (getenv("LLVM_PROGRAM_TEST_CHILD")) {
52     if (ProgramTestStringArg1 == "has\\\\ trailing\\" &&
53         ProgramTestStringArg2 == "has\\\\ trailing\\") {
54       exit(0);  // Success!  The arguments were passed and parsed.
55     }
56     exit(1);
57   }
58
59   std::string my_exe =
60       sys::fs::getMainExecutable(TestMainArgv0, &ProgramTestStringArg1);
61   const char *argv[] = {
62     my_exe.c_str(),
63     "--gtest_filter=ProgramTest.CreateProcessTrailingSlashChild",
64     "-program-test-string-arg1", "has\\\\ trailing\\",
65     "-program-test-string-arg2", "has\\\\ trailing\\",
66     0
67   };
68
69   // Add LLVM_PROGRAM_TEST_CHILD to the environment of the child.
70   std::vector<const char *> envp;
71   CopyEnvironment(envp);
72   envp.push_back("LLVM_PROGRAM_TEST_CHILD=1");
73   envp.push_back(0);
74
75   std::string error;
76   bool ExecutionFailed;
77   // Redirect stdout and stdin to NUL, but let stderr through.
78 #ifdef LLVM_ON_WIN32
79   StringRef nul("NUL");
80 #else
81   StringRef nul("/dev/null");
82 #endif
83   const StringRef *redirects[] = { &nul, &nul, 0 };
84   int rc = ExecuteAndWait(my_exe, argv, &envp[0], redirects,
85                           /*secondsToWait=*/ 10, /*memoryLimit=*/ 0, &error,
86                           &ExecutionFailed);
87   EXPECT_FALSE(ExecutionFailed) << error;
88   EXPECT_EQ(0, rc);
89 }
90
91 } // end anonymous namespace