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