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/Support/Compiler.h" 22#include "llvm/Support/FileSystem.h" 23#include "llvm/Support/raw_ostream.h" 24#include <llvm/Config/config.h> 25#if HAVE_SYS_STAT_H 26#include <sys/stat.h> 27#endif 28#if HAVE_SYS_RESOURCE_H 29#include <sys/resource.h> 30#endif 31#if HAVE_SIGNAL_H 32#include <signal.h> 33#endif 34#if HAVE_FCNTL_H 35#include <fcntl.h> 36#endif 37#if HAVE_UNISTD_H 38#include <unistd.h> 39#endif 40#ifdef HAVE_POSIX_SPAWN 41#ifdef __sun__ 42#define _RESTRICT_KYWD 43#endif 44#include <spawn.h> 45#if defined(__APPLE__) 46#include <TargetConditionals.h> 47#endif 48#if !defined(__APPLE__) || defined(TARGET_OS_IPHONE) 49 extern char **environ; 50#else 51#include <crt_externs.h> // _NSGetEnviron 52#endif 53#endif 54 55namespace llvm { 56 57using namespace sys; 58 59ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {} 60 61ErrorOr<std::string> sys::findProgramByName(StringRef Name, 62 ArrayRef<StringRef> Paths) { 63 assert(!Name.empty() && "Must have a name!"); 64 // Use the given path verbatim if it contains any slashes; this matches 65 // the behavior of sh(1) and friends. 66 if (Name.find('/') != StringRef::npos) 67 return std::string(Name); 68 69 SmallVector<StringRef, 16> EnvironmentPaths; 70 if (Paths.empty()) 71 if (const char *PathEnv = std::getenv("PATH")) { 72 SplitString(PathEnv, EnvironmentPaths, ":"); 73 Paths = EnvironmentPaths; 74 } 75 76 for (auto Path : Paths) { 77 if (Path.empty()) 78 continue; 79 80 // Check to see if this first directory contains the executable... 81 SmallString<128> FilePath(Path); 82 sys::path::append(FilePath, Name); 83 if (sys::fs::can_execute(FilePath.c_str())) 84 return std::string(FilePath.str()); // Found the executable! 85 } 86 return std::errc::no_such_file_or_directory; 87} 88 89static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) { 90 if (!Path) // Noop 91 return false; 92 std::string File; 93 if (Path->empty()) 94 // Redirect empty paths to /dev/null 95 File = "/dev/null"; 96 else 97 File = *Path; 98 99 // Open the file 100 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666); 101 if (InFD == -1) { 102 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for " 103 + (FD == 0 ? "input" : "output")); 104 return true; 105 } 106 107 // Install it as the requested FD 108 if (dup2(InFD, FD) == -1) { 109 MakeErrMsg(ErrMsg, "Cannot dup2"); 110 close(InFD); 111 return true; 112 } 113 close(InFD); // Close the original FD 114 return false; 115} 116 117#ifdef HAVE_POSIX_SPAWN 118static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg, 119 posix_spawn_file_actions_t *FileActions) { 120 if (!Path) // Noop 121 return false; 122 const char *File; 123 if (Path->empty()) 124 // Redirect empty paths to /dev/null 125 File = "/dev/null"; 126 else 127 File = Path->c_str(); 128 129 if (int Err = posix_spawn_file_actions_addopen( 130 FileActions, FD, File, 131 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666)) 132 return MakeErrMsg(ErrMsg, "Cannot dup2", Err); 133 return false; 134} 135#endif 136 137static void TimeOutHandler(int Sig) { 138} 139 140static void SetMemoryLimits (unsigned size) 141{ 142#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT 143 struct rlimit r; 144 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576; 145 146 // Heap size 147 getrlimit (RLIMIT_DATA, &r); 148 r.rlim_cur = limit; 149 setrlimit (RLIMIT_DATA, &r); 150#ifdef RLIMIT_RSS 151 // Resident set size. 152 getrlimit (RLIMIT_RSS, &r); 153 r.rlim_cur = limit; 154 setrlimit (RLIMIT_RSS, &r); 155#endif 156#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it. 157 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb 158 // of virtual memory for shadow memory mapping. 159#if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD 160 // Virtual memory. 161 getrlimit (RLIMIT_AS, &r); 162 r.rlim_cur = limit; 163 setrlimit (RLIMIT_AS, &r); 164#endif 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 !defined(__APPLE__) || defined(TARGET_OS_IPHONE) 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#ifdef HAVE_SYS_WAIT_H 317 struct sigaction Act, Old; 318 assert(PI.Pid && "invalid pid to wait on, process not started?"); 319 320 int WaitPidOptions = 0; 321 pid_t ChildPid = PI.Pid; 322 if (WaitUntilTerminates) { 323 SecondsToWait = 0; 324 } else if (SecondsToWait) { 325 // Install a timeout handler. The handler itself does nothing, but the 326 // simple fact of having a handler at all causes the wait below to return 327 // with EINTR, unlike if we used SIG_IGN. 328 memset(&Act, 0, sizeof(Act)); 329 Act.sa_handler = TimeOutHandler; 330 sigemptyset(&Act.sa_mask); 331 sigaction(SIGALRM, &Act, &Old); 332 alarm(SecondsToWait); 333 } else if (SecondsToWait == 0) 334 WaitPidOptions = WNOHANG; 335 336 // Parent process: Wait for the child process to terminate. 337 int status; 338 ProcessInfo WaitResult; 339 340 do { 341 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions); 342 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR); 343 344 if (WaitResult.Pid != PI.Pid) { 345 if (WaitResult.Pid == 0) { 346 // Non-blocking wait. 347 return WaitResult; 348 } else { 349 if (SecondsToWait && errno == EINTR) { 350 // Kill the child. 351 kill(PI.Pid, SIGKILL); 352 353 // Turn off the alarm and restore the signal handler 354 alarm(0); 355 sigaction(SIGALRM, &Old, nullptr); 356 357 // Wait for child to die 358 if (wait(&status) != ChildPid) 359 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die"); 360 else 361 MakeErrMsg(ErrMsg, "Child timed out", 0); 362 363 WaitResult.ReturnCode = -2; // Timeout detected 364 return WaitResult; 365 } else if (errno != EINTR) { 366 MakeErrMsg(ErrMsg, "Error waiting for child process"); 367 WaitResult.ReturnCode = -1; 368 return WaitResult; 369 } 370 } 371 } 372 373 // We exited normally without timeout, so turn off the timer. 374 if (SecondsToWait && !WaitUntilTerminates) { 375 alarm(0); 376 sigaction(SIGALRM, &Old, nullptr); 377 } 378 379 // Return the proper exit status. Detect error conditions 380 // so we can return -1 for them and set ErrMsg informatively. 381 int result = 0; 382 if (WIFEXITED(status)) { 383 result = WEXITSTATUS(status); 384 WaitResult.ReturnCode = result; 385 386 if (result == 127) { 387 if (ErrMsg) 388 *ErrMsg = llvm::sys::StrError(ENOENT); 389 WaitResult.ReturnCode = -1; 390 return WaitResult; 391 } 392 if (result == 126) { 393 if (ErrMsg) 394 *ErrMsg = "Program could not be executed"; 395 WaitResult.ReturnCode = -1; 396 return WaitResult; 397 } 398 } else if (WIFSIGNALED(status)) { 399 if (ErrMsg) { 400 *ErrMsg = strsignal(WTERMSIG(status)); 401#ifdef WCOREDUMP 402 if (WCOREDUMP(status)) 403 *ErrMsg += " (core dumped)"; 404#endif 405 } 406 // Return a special value to indicate that the process received an unhandled 407 // signal during execution as opposed to failing to execute. 408 WaitResult.ReturnCode = -2; 409 } 410#else 411 if (ErrMsg) 412 *ErrMsg = "Program::Wait is not implemented on this platform yet!"; 413 ProcessInfo WaitResult; 414 WaitResult.ReturnCode = -2; 415#endif 416 return WaitResult; 417} 418 419 std::error_code sys::ChangeStdinToBinary(){ 420 // Do nothing, as Unix doesn't differentiate between text and binary. 421 return std::error_code(); 422} 423 424 std::error_code sys::ChangeStdoutToBinary(){ 425 // Do nothing, as Unix doesn't differentiate between text and binary. 426 return std::error_code(); 427} 428 429std::error_code 430llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents, 431 WindowsEncodingMethod Encoding /*unused*/) { 432 std::error_code EC; 433 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text); 434 435 if (EC) 436 return EC; 437 438 OS << Contents; 439 440 if (OS.has_error()) 441 return std::make_error_code(std::errc::io_error); 442 443 return EC; 444} 445 446bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) { 447 static long ArgMax = sysconf(_SC_ARG_MAX); 448 449 // System says no practical limit. 450 if (ArgMax == -1) 451 return true; 452 453 // Conservatively account for space required by environment variables. 454 long HalfArgMax = ArgMax / 2; 455 456 size_t ArgLength = 0; 457 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end(); 458 I != E; ++I) { 459 ArgLength += strlen(*I) + 1; 460 if (ArgLength > size_t(HalfArgMax)) { 461 return false; 462 } 463 } 464 return true; 465} 466} 467