xref: /llvm-project/llvm/lib/Support/SystemUtils.cpp (revision b6d6b931cc289cae50bfb22eff13b245bb99335e)
1 //===- SystemUtils.h - Utilities to do low-level system stuff --*- C++ -*--===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains functions used to do a variety of low-level, often
11 // system-specific, tasks.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define _POSIX_MAPPED_FILES
16 #include "Support/SystemUtils.h"
17 #include "Config/sys/types.h"
18 #include "Config/sys/stat.h"
19 #include "Config/fcntl.h"
20 #include "Config/sys/wait.h"
21 #include "Config/sys/mman.h"
22 #include "Config/unistd.h"
23 #include <algorithm>
24 #include <fstream>
25 #include <iostream>
26 #include <cstdlib>
27 #include <cerrno>
28 #include "Config/windows.h"
29 using namespace llvm;
30 
31 /// isExecutableFile - This function returns true if the filename specified
32 /// exists and is executable.
33 ///
34 bool llvm::isExecutableFile(const std::string &ExeFileName) {
35   struct stat Buf;
36   if (stat(ExeFileName.c_str(), &Buf))
37     return false;  // Must not be executable!
38 
39   if (!(Buf.st_mode & S_IFREG))
40     return false;                    // Not a regular file?
41 
42   if (Buf.st_uid == getuid())        // Owner of file?
43     return Buf.st_mode & S_IXUSR;
44   else if (Buf.st_gid == getgid())   // In group of file?
45     return Buf.st_mode & S_IXGRP;
46   else                               // Unrelated to file?
47     return Buf.st_mode & S_IXOTH;
48 }
49 
50 /// isStandardOutAConsole - Return true if we can tell that the standard output
51 /// stream goes to a terminal window or console.
52 bool llvm::isStandardOutAConsole() {
53 #if HAVE_ISATTY
54   return isatty(1);
55 #endif
56   // If we don't have isatty, just return false.
57   return false;
58 }
59 
60 
61 /// FindExecutable - Find a named executable, giving the argv[0] of program
62 /// being executed. This allows us to find another LLVM tool if it is built
63 /// into the same directory, but that directory is neither the current
64 /// directory, nor in the PATH.  If the executable cannot be found, return an
65 /// empty string.
66 ///
67 #undef FindExecutable   // needed on windows :(
68 std::string llvm::FindExecutable(const std::string &ExeName,
69                                  const std::string &ProgramPath) {
70   // First check the directory that bugpoint is in.  We can do this if
71   // BugPointPath contains at least one / character, indicating that it is a
72   // relative path to bugpoint itself.
73   //
74   std::string Result = ProgramPath;
75   while (!Result.empty() && Result[Result.size()-1] != '/')
76     Result.erase(Result.size()-1, 1);
77 
78   if (!Result.empty()) {
79     Result += ExeName;
80     if (isExecutableFile(Result)) return Result; // Found it?
81   }
82 
83   // Okay, if the path to the program didn't tell us anything, try using the
84   // PATH environment variable.
85   const char *PathStr = getenv("PATH");
86   if (PathStr == 0) return "";
87 
88   // Now we have a colon separated list of directories to search... try them...
89   unsigned PathLen = strlen(PathStr);
90   while (PathLen) {
91     // Find the first colon...
92     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
93 
94     // Check to see if this first directory contains the executable...
95     std::string FilePath = std::string(PathStr, Colon) + '/' + ExeName;
96     if (isExecutableFile(FilePath))
97       return FilePath;                    // Found the executable!
98 
99     // Nope it wasn't in this directory, check the next range!
100     PathLen -= Colon-PathStr;
101     PathStr = Colon;
102     while (*PathStr == ':') {   // Advance past colons
103       PathStr++;
104       PathLen--;
105     }
106   }
107 
108   // If we fell out, we ran out of directories in PATH to search, return failure
109   return "";
110 }
111 
112 static void RedirectFD(const std::string &File, int FD) {
113   if (File.empty()) return;  // Noop
114 
115   // Open the file
116   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
117   if (InFD == -1) {
118     std::cerr << "Error opening file '" << File << "' for "
119               << (FD == 0 ? "input" : "output") << "!\n";
120     exit(1);
121   }
122 
123   dup2(InFD, FD);   // Install it as the requested FD
124   close(InFD);      // Close the original FD
125 }
126 
127 /// RunProgramWithTimeout - This function executes the specified program, with
128 /// the specified null-terminated argument array, with the stdin/out/err fd's
129 /// redirected, with a timeout specified on the command line.  This terminates
130 /// the calling program if there is an error executing the specified program.
131 /// It returns the return value of the program, or -1 if a timeout is detected.
132 ///
133 int llvm::RunProgramWithTimeout(const std::string &ProgramPath,
134                                 const char **Args,
135                                 const std::string &StdInFile,
136                                 const std::string &StdOutFile,
137                                 const std::string &StdErrFile) {
138   // FIXME: install sigalarm handler here for timeout...
139 
140 #ifdef HAVE_SYS_WAIT_H
141   int Child = fork();
142   switch (Child) {
143   case -1:
144     std::cerr << "ERROR forking!\n";
145     exit(1);
146   case 0:               // Child
147     RedirectFD(StdInFile, 0);      // Redirect file descriptors...
148     RedirectFD(StdOutFile, 1);
149     if (StdOutFile != StdErrFile)
150       RedirectFD(StdErrFile, 2);
151     else
152       dup2(1, 2);
153 
154     execv(ProgramPath.c_str(), (char *const *)Args);
155     std::cerr << "Error executing program: '" << ProgramPath;
156     for (; *Args; ++Args)
157       std::cerr << " " << *Args;
158     std::cerr << "'\n";
159     exit(1);
160 
161   default: break;
162   }
163 
164   // Make sure all output has been written while waiting
165   std::cout << std::flush;
166 
167   int Status;
168   if (wait(&Status) != Child) {
169     if (errno == EINTR) {
170       static bool FirstTimeout = true;
171       if (FirstTimeout) {
172         std::cout <<
173  "*** Program execution timed out!  This mechanism is designed to handle\n"
174  "    programs stuck in infinite loops gracefully.  The -timeout option\n"
175  "    can be used to change the timeout threshold or disable it completely\n"
176  "    (with -timeout=0).  This message is only displayed once.\n";
177         FirstTimeout = false;
178       }
179       return -1;   // Timeout detected
180     }
181 
182     std::cerr << "Error waiting for child process!\n";
183     exit(1);
184   }
185   return Status;
186 
187 #else
188   std::cerr << "RunProgramWithTimeout not implemented on this platform!\n";
189   return -1;
190 #endif
191 }
192 
193 
194 //
195 // Function: ExecWait ()
196 //
197 // Description:
198 //  This function executes a program with the specified arguments and
199 //  environment.  It then waits for the progarm to termiante and then returns
200 //  to the caller.
201 //
202 // Inputs:
203 //  argv - The arguments to the program as an array of C strings.  The first
204 //         argument should be the name of the program to execute, and the
205 //         last argument should be a pointer to NULL.
206 //
207 //  envp - The environment passes to the program as an array of C strings in
208 //         the form of "name=value" pairs.  The last element should be a
209 //         pointer to NULL.
210 //
211 // Outputs:
212 //  None.
213 //
214 // Return value:
215 //  0 - No errors.
216 //  1 - The program could not be executed.
217 //  1 - The program returned a non-zero exit status.
218 //  1 - The program terminated abnormally.
219 //
220 // Notes:
221 //  The program will inherit the stdin, stdout, and stderr file descriptors
222 //  as well as other various configuration settings (umask).
223 //
224 //  This function should not print anything to stdout/stderr on its own.  It is
225 //  a generic library function.  The caller or executed program should report
226 //  errors in the way it sees fit.
227 //
228 //  This function does not use $PATH to find programs.
229 //
230 int llvm::ExecWait(const char * const old_argv[],
231                    const char * const old_envp[]) {
232 #ifdef HAVE_SYS_WAIT_H
233   //
234   // Create local versions of the parameters that can be passed into execve()
235   // without creating const problems.
236   //
237   char ** const argv = (char ** const) old_argv;
238   char ** const envp = (char ** const) old_envp;
239 
240   // Create a child process.
241   switch (fork()) {
242     // An error occured:  Return to the caller.
243     case -1:
244       return 1;
245       break;
246 
247     // Child process: Execute the program.
248     case 0:
249       execve (argv[0], argv, envp);
250       // If the execve() failed, we should exit and let the parent pick up
251       // our non-zero exit status.
252       exit (1);
253 
254     // Parent process: Break out of the switch to do our processing.
255     default:
256       break;
257   }
258 
259   // Parent process: Wait for the child process to termiante.
260   int status;
261   if ((wait (&status)) == -1)
262     return 1;
263 
264   // If the program exited normally with a zero exit status, return success!
265   if (WIFEXITED (status) && (WEXITSTATUS(status) == 0))
266     return 0;
267 #else
268   std::cerr << "llvm::ExecWait not implemented on this platform!\n";
269 #endif
270 
271   // Otherwise, return failure.
272   return 1;
273 }
274 
275 /// AllocateRWXMemory - Allocate a slab of memory with read/write/execute
276 /// permissions.  This is typically used for JIT applications where we want
277 /// to emit code to the memory then jump to it.  Getting this type of memory
278 /// is very OS specific.
279 ///
280 void *llvm::AllocateRWXMemory(unsigned NumBytes) {
281   if (NumBytes == 0) return 0;
282 
283 #if defined(HAVE_WINDOWS_H)
284   // On windows we use VirtualAlloc.
285   void *P = VirtualAlloc(0, NumBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
286   if (P == 0) {
287     std::cerr << "Error allocating executable memory!\n";
288     abort();
289   }
290   return P;
291 
292 #elif defined(HAVE_MMAP)
293   static const long pageSize = sysconf(_SC_PAGESIZE);
294   unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
295 
296 /* FIXME: This should use the proper autoconf flags */
297 #if defined(i386) || defined(__i386__) || defined(__x86__)
298   /* Linux and *BSD tend to have these flags named differently. */
299 #if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
300 # define MAP_ANONYMOUS MAP_ANON
301 #endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
302 #elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
303 /* nothing */
304 #else
305   std::cerr << "This architecture has an unknown MMAP implementation!\n";
306   abort();
307   return 0;
308 #endif
309 
310   int fd = -1;
311 #if defined(__linux__)
312   fd = 0;
313 #endif
314 
315   unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
316 #ifdef MAP_NORESERVE
317   mmapFlags |= MAP_NORESERVE;
318 #endif
319 
320   void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
321                   mmapFlags, fd, 0);
322   if (pa == MAP_FAILED) {
323     perror("mmap");
324     abort();
325   }
326   return pa;
327 #else
328   std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
329   abort();
330   return 0;
331 #endif
332 }
333 
334 
335