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