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(Optional<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#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT 149 struct rlimit r; 150 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576; 151 152 // Heap size 153 getrlimit (RLIMIT_DATA, &r); 154 r.rlim_cur = limit; 155 setrlimit (RLIMIT_DATA, &r); 156#ifdef RLIMIT_RSS 157 // Resident set size. 158 getrlimit (RLIMIT_RSS, &r); 159 r.rlim_cur = limit; 160 setrlimit (RLIMIT_RSS, &r); 161#endif 162#endif 163} 164 165} 166 167static bool Execute(ProcessInfo &PI, StringRef Program, const char **Args, 168 const char **Envp, ArrayRef<Optional<StringRef>> Redirects, 169 unsigned MemoryLimit, std::string *ErrMsg) { 170 if (!llvm::sys::fs::exists(Program)) { 171 if (ErrMsg) 172 *ErrMsg = std::string("Executable \"") + Program.str() + 173 std::string("\" doesn't exist!"); 174 return false; 175 } 176 177 // If this OS has posix_spawn and there is no memory limit being implied, use 178 // posix_spawn. It is more efficient than fork/exec. 179#ifdef HAVE_POSIX_SPAWN 180 if (MemoryLimit == 0) { 181 posix_spawn_file_actions_t FileActionsStore; 182 posix_spawn_file_actions_t *FileActions = nullptr; 183 184 // If we call posix_spawn_file_actions_addopen we have to make sure the 185 // c strings we pass to it stay alive until the call to posix_spawn, 186 // so we copy any StringRefs into this variable. 187 std::string RedirectsStorage[3]; 188 189 if (!Redirects.empty()) { 190 assert(Redirects.size() == 3); 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] || !Redirects[2] || *Redirects[1] != *Redirects[2]) { 207 // Just redirect stderr 208 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions)) 209 return false; 210 } else { 211 // If stdout and stderr should go to the same place, redirect stderr 212 // to the FD already open for stdout. 213 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2)) 214 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err); 215 } 216 } 217 218 if (!Envp) 219#if !USE_NSGETENVIRON 220 Envp = const_cast<const char **>(environ); 221#else 222 // environ is missing in dylibs. 223 Envp = const_cast<const char **>(*_NSGetEnviron()); 224#endif 225 226 // Explicitly initialized to prevent what appears to be a valgrind false 227 // positive. 228 pid_t PID = 0; 229 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions, 230 /*attrp*/nullptr, const_cast<char **>(Args), 231 const_cast<char **>(Envp)); 232 233 if (FileActions) 234 posix_spawn_file_actions_destroy(FileActions); 235 236 if (Err) 237 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err); 238 239 PI.Pid = PID; 240 241 return true; 242 } 243#endif 244 245 // Create a child process. 246 int child = fork(); 247 switch (child) { 248 // An error occurred: Return to the caller. 249 case -1: 250 MakeErrMsg(ErrMsg, "Couldn't fork"); 251 return false; 252 253 // Child process: Execute the program. 254 case 0: { 255 // Redirect file descriptors... 256 if (!Redirects.empty()) { 257 // Redirect stdin 258 if (RedirectIO(Redirects[0], 0, ErrMsg)) { return false; } 259 // Redirect stdout 260 if (RedirectIO(Redirects[1], 1, ErrMsg)) { return false; } 261 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) { 262 // If stdout and stderr should go to the same place, redirect stderr 263 // to the FD already open for stdout. 264 if (-1 == dup2(1,2)) { 265 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout"); 266 return false; 267 } 268 } else { 269 // Just redirect stderr 270 if (RedirectIO(Redirects[2], 2, ErrMsg)) { return false; } 271 } 272 } 273 274 // Set memory limits 275 if (MemoryLimit!=0) { 276 SetMemoryLimits(MemoryLimit); 277 } 278 279 // Execute! 280 std::string PathStr = Program; 281 if (Envp != nullptr) 282 execve(PathStr.c_str(), 283 const_cast<char **>(Args), 284 const_cast<char **>(Envp)); 285 else 286 execv(PathStr.c_str(), 287 const_cast<char **>(Args)); 288 // If the execve() failed, we should exit. Follow Unix protocol and 289 // return 127 if the executable was not found, and 126 otherwise. 290 // Use _exit rather than exit so that atexit functions and static 291 // object destructors cloned from the parent process aren't 292 // redundantly run, and so that any data buffered in stdio buffers 293 // cloned from the parent aren't redundantly written out. 294 _exit(errno == ENOENT ? 127 : 126); 295 } 296 297 // Parent process: Break out of the switch to do our processing. 298 default: 299 break; 300 } 301 302 PI.Pid = child; 303 304 return true; 305} 306 307namespace llvm { 308 309ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait, 310 bool WaitUntilTerminates, std::string *ErrMsg) { 311 struct sigaction Act, Old; 312 assert(PI.Pid && "invalid pid to wait on, process not started?"); 313 314 int WaitPidOptions = 0; 315 pid_t ChildPid = PI.Pid; 316 if (WaitUntilTerminates) { 317 SecondsToWait = 0; 318 } else if (SecondsToWait) { 319 // Install a timeout handler. The handler itself does nothing, but the 320 // simple fact of having a handler at all causes the wait below to return 321 // with EINTR, unlike if we used SIG_IGN. 322 memset(&Act, 0, sizeof(Act)); 323 Act.sa_handler = TimeOutHandler; 324 sigemptyset(&Act.sa_mask); 325 sigaction(SIGALRM, &Act, &Old); 326 alarm(SecondsToWait); 327 } else if (SecondsToWait == 0) 328 WaitPidOptions = WNOHANG; 329 330 // Parent process: Wait for the child process to terminate. 331 int status; 332 ProcessInfo WaitResult; 333 334 do { 335 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions); 336 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR); 337 338 if (WaitResult.Pid != PI.Pid) { 339 if (WaitResult.Pid == 0) { 340 // Non-blocking wait. 341 return WaitResult; 342 } else { 343 if (SecondsToWait && errno == EINTR) { 344 // Kill the child. 345 kill(PI.Pid, SIGKILL); 346 347 // Turn off the alarm and restore the signal handler 348 alarm(0); 349 sigaction(SIGALRM, &Old, nullptr); 350 351 // Wait for child to die 352 if (wait(&status) != ChildPid) 353 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die"); 354 else 355 MakeErrMsg(ErrMsg, "Child timed out", 0); 356 357 WaitResult.ReturnCode = -2; // Timeout detected 358 return WaitResult; 359 } else if (errno != EINTR) { 360 MakeErrMsg(ErrMsg, "Error waiting for child process"); 361 WaitResult.ReturnCode = -1; 362 return WaitResult; 363 } 364 } 365 } 366 367 // We exited normally without timeout, so turn off the timer. 368 if (SecondsToWait && !WaitUntilTerminates) { 369 alarm(0); 370 sigaction(SIGALRM, &Old, nullptr); 371 } 372 373 // Return the proper exit status. Detect error conditions 374 // so we can return -1 for them and set ErrMsg informatively. 375 int result = 0; 376 if (WIFEXITED(status)) { 377 result = WEXITSTATUS(status); 378 WaitResult.ReturnCode = result; 379 380 if (result == 127) { 381 if (ErrMsg) 382 *ErrMsg = llvm::sys::StrError(ENOENT); 383 WaitResult.ReturnCode = -1; 384 return WaitResult; 385 } 386 if (result == 126) { 387 if (ErrMsg) 388 *ErrMsg = "Program could not be executed"; 389 WaitResult.ReturnCode = -1; 390 return WaitResult; 391 } 392 } else if (WIFSIGNALED(status)) { 393 if (ErrMsg) { 394 *ErrMsg = strsignal(WTERMSIG(status)); 395#ifdef WCOREDUMP 396 if (WCOREDUMP(status)) 397 *ErrMsg += " (core dumped)"; 398#endif 399 } 400 // Return a special value to indicate that the process received an unhandled 401 // signal during execution as opposed to failing to execute. 402 WaitResult.ReturnCode = -2; 403 } 404 return WaitResult; 405} 406 407 std::error_code sys::ChangeStdinToBinary(){ 408 // Do nothing, as Unix doesn't differentiate between text and binary. 409 return std::error_code(); 410} 411 412 std::error_code sys::ChangeStdoutToBinary(){ 413 // Do nothing, as Unix doesn't differentiate between text and binary. 414 return std::error_code(); 415} 416 417std::error_code 418llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents, 419 WindowsEncodingMethod Encoding /*unused*/) { 420 std::error_code EC; 421 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text); 422 423 if (EC) 424 return EC; 425 426 OS << Contents; 427 428 if (OS.has_error()) 429 return make_error_code(errc::io_error); 430 431 return EC; 432} 433 434bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program, 435 ArrayRef<const char *> Args) { 436 static long ArgMax = sysconf(_SC_ARG_MAX); 437 438 // System says no practical limit. 439 if (ArgMax == -1) 440 return true; 441 442 // Conservatively account for space required by environment variables. 443 long HalfArgMax = ArgMax / 2; 444 445 size_t ArgLength = Program.size() + 1; 446 for (const char* Arg : Args) { 447 size_t length = strlen(Arg); 448 449 // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which 450 // does not have a constant unlike what the man pages would have you 451 // believe. Since this limit is pretty high, perform the check 452 // unconditionally rather than trying to be aggressive and limiting it to 453 // Linux only. 454 if (length >= (32 * 4096)) 455 return false; 456 457 ArgLength += length + 1; 458 if (ArgLength > size_t(HalfArgMax)) { 459 return false; 460 } 461 } 462 463 return true; 464} 465} 466