1//===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===// 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// This file implements the Unix specific portion of the Program class. 11// 12//===----------------------------------------------------------------------===// 13 14//===----------------------------------------------------------------------===// 15//=== WARNING: Implementation here must contain only generic UNIX code that 16//=== is guaranteed to work on *all* UNIX variants. 17//===----------------------------------------------------------------------===// 18 19#include "Unix.h" 20#include "llvm/Support/Compiler.h" 21#include "llvm/Support/FileSystem.h" 22#include "llvm/Support/raw_ostream.h" 23#include <llvm/Config/config.h> 24#if HAVE_SYS_STAT_H 25#include <sys/stat.h> 26#endif 27#if HAVE_SYS_RESOURCE_H 28#include <sys/resource.h> 29#endif 30#if HAVE_SIGNAL_H 31#include <signal.h> 32#endif 33#if HAVE_FCNTL_H 34#include <fcntl.h> 35#endif 36#if HAVE_UNISTD_H 37#include <unistd.h> 38#endif 39#ifdef HAVE_POSIX_SPAWN 40#ifdef __sun__ 41#define _RESTRICT_KYWD 42#endif 43#include <spawn.h> 44#if !defined(__APPLE__) 45 extern char **environ; 46#else 47#include <crt_externs.h> // _NSGetEnviron 48#endif 49#endif 50 51namespace llvm { 52 53using namespace sys; 54 55ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {} 56 57// This function just uses the PATH environment variable to find the program. 58std::string 59sys::FindProgramByName(const std::string& progName) { 60 61 // Check some degenerate cases 62 if (progName.length() == 0) // no program 63 return ""; 64 std::string temp = progName; 65 // Use the given path verbatim if it contains any slashes; this matches 66 // the behavior of sh(1) and friends. 67 if (progName.find('/') != std::string::npos) 68 return temp; 69 70 // At this point, the file name is valid and does not contain slashes. Search 71 // for it through the directories specified in the PATH environment variable. 72 73 // Get the path. If its empty, we can't do anything to find it. 74 const char *PathStr = getenv("PATH"); 75 if (!PathStr) 76 return ""; 77 78 // Now we have a colon separated list of directories to search; try them. 79 size_t PathLen = strlen(PathStr); 80 while (PathLen) { 81 // Find the first colon... 82 const char *Colon = std::find(PathStr, PathStr+PathLen, ':'); 83 84 // Check to see if this first directory contains the executable... 85 SmallString<128> FilePath(PathStr,Colon); 86 sys::path::append(FilePath, progName); 87 if (sys::fs::can_execute(Twine(FilePath))) 88 return FilePath.str(); // Found the executable! 89 90 // Nope it wasn't in this directory, check the next path in the list! 91 PathLen -= Colon-PathStr; 92 PathStr = Colon; 93 94 // Advance past duplicate colons 95 while (*PathStr == ':') { 96 PathStr++; 97 PathLen--; 98 } 99 } 100 return ""; 101} 102 103static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) { 104 if (!Path) // Noop 105 return false; 106 std::string File; 107 if (Path->empty()) 108 // Redirect empty paths to /dev/null 109 File = "/dev/null"; 110 else 111 File = *Path; 112 113 // Open the file 114 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666); 115 if (InFD == -1) { 116 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for " 117 + (FD == 0 ? "input" : "output")); 118 return true; 119 } 120 121 // Install it as the requested FD 122 if (dup2(InFD, FD) == -1) { 123 MakeErrMsg(ErrMsg, "Cannot dup2"); 124 close(InFD); 125 return true; 126 } 127 close(InFD); // Close the original FD 128 return false; 129} 130 131#ifdef HAVE_POSIX_SPAWN 132static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg, 133 posix_spawn_file_actions_t *FileActions) { 134 if (!Path) // Noop 135 return false; 136 const char *File; 137 if (Path->empty()) 138 // Redirect empty paths to /dev/null 139 File = "/dev/null"; 140 else 141 File = Path->c_str(); 142 143 if (int Err = posix_spawn_file_actions_addopen( 144 FileActions, FD, File, 145 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666)) 146 return MakeErrMsg(ErrMsg, "Cannot dup2", Err); 147 return false; 148} 149#endif 150 151static void TimeOutHandler(int Sig) { 152} 153 154static void SetMemoryLimits (unsigned size) 155{ 156#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT 157 struct rlimit r; 158 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576; 159 160 // Heap size 161 getrlimit (RLIMIT_DATA, &r); 162 r.rlim_cur = limit; 163 setrlimit (RLIMIT_DATA, &r); 164#ifdef RLIMIT_RSS 165 // Resident set size. 166 getrlimit (RLIMIT_RSS, &r); 167 r.rlim_cur = limit; 168 setrlimit (RLIMIT_RSS, &r); 169#endif 170#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it. 171 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb 172 // of virtual memory for shadow memory mapping. 173#if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD 174 // Virtual memory. 175 getrlimit (RLIMIT_AS, &r); 176 r.rlim_cur = limit; 177 setrlimit (RLIMIT_AS, &r); 178#endif 179#endif 180#endif 181} 182 183} 184 185static bool Execute(ProcessInfo &PI, StringRef Program, const char **args, 186 const char **envp, const StringRef **redirects, 187 unsigned memoryLimit, std::string *ErrMsg) { 188 if (!llvm::sys::fs::exists(Program)) { 189 if (ErrMsg) 190 *ErrMsg = std::string("Executable \"") + Program.str() + 191 std::string("\" doesn't exist!"); 192 return false; 193 } 194 195 // If this OS has posix_spawn and there is no memory limit being implied, use 196 // posix_spawn. It is more efficient than fork/exec. 197#ifdef HAVE_POSIX_SPAWN 198 if (memoryLimit == 0) { 199 posix_spawn_file_actions_t FileActionsStore; 200 posix_spawn_file_actions_t *FileActions = nullptr; 201 202 // If we call posix_spawn_file_actions_addopen we have to make sure the 203 // c strings we pass to it stay alive until the call to posix_spawn, 204 // so we copy any StringRefs into this variable. 205 std::string RedirectsStorage[3]; 206 207 if (redirects) { 208 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr}; 209 for (int I = 0; I < 3; ++I) { 210 if (redirects[I]) { 211 RedirectsStorage[I] = *redirects[I]; 212 RedirectsStr[I] = &RedirectsStorage[I]; 213 } 214 } 215 216 FileActions = &FileActionsStore; 217 posix_spawn_file_actions_init(FileActions); 218 219 // Redirect stdin/stdout. 220 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) || 221 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions)) 222 return false; 223 if (redirects[1] == nullptr || redirects[2] == nullptr || 224 *redirects[1] != *redirects[2]) { 225 // Just redirect stderr 226 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions)) 227 return false; 228 } else { 229 // If stdout and stderr should go to the same place, redirect stderr 230 // to the FD already open for stdout. 231 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2)) 232 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err); 233 } 234 } 235 236 if (!envp) 237#if !defined(__APPLE__) 238 envp = const_cast<const char **>(environ); 239#else 240 // environ is missing in dylibs. 241 envp = const_cast<const char **>(*_NSGetEnviron()); 242#endif 243 244 // Explicitly initialized to prevent what appears to be a valgrind false 245 // positive. 246 pid_t PID = 0; 247 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions, 248 /*attrp*/nullptr, const_cast<char **>(args), 249 const_cast<char **>(envp)); 250 251 if (FileActions) 252 posix_spawn_file_actions_destroy(FileActions); 253 254 if (Err) 255 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err); 256 257 PI.Pid = PID; 258 259 return true; 260 } 261#endif 262 263 // Create a child process. 264 int child = fork(); 265 switch (child) { 266 // An error occurred: Return to the caller. 267 case -1: 268 MakeErrMsg(ErrMsg, "Couldn't fork"); 269 return false; 270 271 // Child process: Execute the program. 272 case 0: { 273 // Redirect file descriptors... 274 if (redirects) { 275 // Redirect stdin 276 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; } 277 // Redirect stdout 278 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; } 279 if (redirects[1] && redirects[2] && 280 *(redirects[1]) == *(redirects[2])) { 281 // If stdout and stderr should go to the same place, redirect stderr 282 // to the FD already open for stdout. 283 if (-1 == dup2(1,2)) { 284 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout"); 285 return false; 286 } 287 } else { 288 // Just redirect stderr 289 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; } 290 } 291 } 292 293 // Set memory limits 294 if (memoryLimit!=0) { 295 SetMemoryLimits(memoryLimit); 296 } 297 298 // Execute! 299 std::string PathStr = Program; 300 if (envp != nullptr) 301 execve(PathStr.c_str(), 302 const_cast<char **>(args), 303 const_cast<char **>(envp)); 304 else 305 execv(PathStr.c_str(), 306 const_cast<char **>(args)); 307 // If the execve() failed, we should exit. Follow Unix protocol and 308 // return 127 if the executable was not found, and 126 otherwise. 309 // Use _exit rather than exit so that atexit functions and static 310 // object destructors cloned from the parent process aren't 311 // redundantly run, and so that any data buffered in stdio buffers 312 // cloned from the parent aren't redundantly written out. 313 _exit(errno == ENOENT ? 127 : 126); 314 } 315 316 // Parent process: Break out of the switch to do our processing. 317 default: 318 break; 319 } 320 321 PI.Pid = child; 322 323 return true; 324} 325 326namespace llvm { 327 328ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait, 329 bool WaitUntilTerminates, std::string *ErrMsg) { 330#ifdef HAVE_SYS_WAIT_H 331 struct sigaction Act, Old; 332 assert(PI.Pid && "invalid pid to wait on, process not started?"); 333 334 int WaitPidOptions = 0; 335 pid_t ChildPid = PI.Pid; 336 if (WaitUntilTerminates) { 337 SecondsToWait = 0; 338 ChildPid = -1; // mimic a wait() using waitpid() 339 } else if (SecondsToWait) { 340 // Install a timeout handler. The handler itself does nothing, but the 341 // simple fact of having a handler at all causes the wait below to return 342 // with EINTR, unlike if we used SIG_IGN. 343 memset(&Act, 0, sizeof(Act)); 344 Act.sa_handler = TimeOutHandler; 345 sigemptyset(&Act.sa_mask); 346 sigaction(SIGALRM, &Act, &Old); 347 alarm(SecondsToWait); 348 } else if (SecondsToWait == 0) 349 WaitPidOptions = WNOHANG; 350 351 // Parent process: Wait for the child process to terminate. 352 int status; 353 ProcessInfo WaitResult; 354 355 do { 356 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions); 357 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR); 358 359 if (WaitResult.Pid != PI.Pid) { 360 if (WaitResult.Pid == 0) { 361 // Non-blocking wait. 362 return WaitResult; 363 } else { 364 if (SecondsToWait && errno == EINTR) { 365 // Kill the child. 366 kill(PI.Pid, SIGKILL); 367 368 // Turn off the alarm and restore the signal handler 369 alarm(0); 370 sigaction(SIGALRM, &Old, nullptr); 371 372 // Wait for child to die 373 if (wait(&status) != ChildPid) 374 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die"); 375 else 376 MakeErrMsg(ErrMsg, "Child timed out", 0); 377 378 WaitResult.ReturnCode = -2; // Timeout detected 379 return WaitResult; 380 } else if (errno != EINTR) { 381 MakeErrMsg(ErrMsg, "Error waiting for child process"); 382 WaitResult.ReturnCode = -1; 383 return WaitResult; 384 } 385 } 386 } 387 388 // We exited normally without timeout, so turn off the timer. 389 if (SecondsToWait && !WaitUntilTerminates) { 390 alarm(0); 391 sigaction(SIGALRM, &Old, nullptr); 392 } 393 394 // Return the proper exit status. Detect error conditions 395 // so we can return -1 for them and set ErrMsg informatively. 396 int result = 0; 397 if (WIFEXITED(status)) { 398 result = WEXITSTATUS(status); 399 WaitResult.ReturnCode = result; 400 401 if (result == 127) { 402 if (ErrMsg) 403 *ErrMsg = llvm::sys::StrError(ENOENT); 404 WaitResult.ReturnCode = -1; 405 return WaitResult; 406 } 407 if (result == 126) { 408 if (ErrMsg) 409 *ErrMsg = "Program could not be executed"; 410 WaitResult.ReturnCode = -1; 411 return WaitResult; 412 } 413 } else if (WIFSIGNALED(status)) { 414 if (ErrMsg) { 415 *ErrMsg = strsignal(WTERMSIG(status)); 416#ifdef WCOREDUMP 417 if (WCOREDUMP(status)) 418 *ErrMsg += " (core dumped)"; 419#endif 420 } 421 // Return a special value to indicate that the process received an unhandled 422 // signal during execution as opposed to failing to execute. 423 WaitResult.ReturnCode = -2; 424 } 425#else 426 if (ErrMsg) 427 *ErrMsg = "Program::Wait is not implemented on this platform yet!"; 428 ProcessInfo WaitResult; 429 WaitResult.ReturnCode = -2; 430#endif 431 return WaitResult; 432} 433 434 std::error_code sys::ChangeStdinToBinary(){ 435 // Do nothing, as Unix doesn't differentiate between text and binary. 436 return std::error_code(); 437} 438 439 std::error_code sys::ChangeStdoutToBinary(){ 440 // Do nothing, as Unix doesn't differentiate between text and binary. 441 return std::error_code(); 442} 443 444std::error_code 445llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents, 446 WindowsEncodingMethod Encoding /*unused*/) { 447 std::error_code EC; 448 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text); 449 450 if (EC) 451 return EC; 452 453 OS << Contents; 454 455 if (OS.has_error()) 456 return std::make_error_code(std::errc::io_error); 457 458 return EC; 459} 460 461bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) { 462 static long ArgMax = sysconf(_SC_ARG_MAX); 463 464 // System says no practical limit. 465 if (ArgMax == -1) 466 return true; 467 468 // Conservatively account for space required by environment variables. 469 long HalfArgMax = ArgMax / 2; 470 471 size_t ArgLength = 0; 472 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end(); 473 I != E; ++I) { 474 ArgLength += strlen(*I) + 1; 475 if (ArgLength > size_t(HalfArgMax)) { 476 return false; 477 } 478 } 479 return true; 480} 481} 482