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