Program.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. //===- Win32/Program.cpp - Win32 Program Implementation ------- -*- 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 provides the Win32 specific implementation of the Program class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "WindowsSupport.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/Support/ConvertUTF.h"
  16. #include "llvm/Support/Errc.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/WindowsError.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <cstdio>
  21. #include <fcntl.h>
  22. #include <io.h>
  23. #include <malloc.h>
  24. //===----------------------------------------------------------------------===//
  25. //=== WARNING: Implementation here must contain only Win32 specific code
  26. //=== and must not be UNIX code
  27. //===----------------------------------------------------------------------===//
  28. namespace llvm {
  29. using namespace sys;
  30. ProcessInfo::ProcessInfo() : ProcessHandle(0), Pid(0), ReturnCode(0) {}
  31. ErrorOr<std::string> sys::findProgramByName(StringRef Name,
  32. ArrayRef<StringRef> Paths) {
  33. #ifdef MSFT_SUPPORTS_CHILD_PROCESSES // HLSL Change
  34. assert(!Name.empty() && "Must have a name!");
  35. if (Name.find_first_of("/\\") != StringRef::npos)
  36. return std::string(Name);
  37. const wchar_t *Path = nullptr;
  38. std::wstring PathStorage;
  39. if (!Paths.empty()) {
  40. PathStorage.reserve(Paths.size() * MAX_PATH);
  41. for (unsigned i = 0; i < Paths.size(); ++i) {
  42. if (i)
  43. PathStorage.push_back(L';');
  44. StringRef P = Paths[i];
  45. SmallVector<wchar_t, MAX_PATH> TmpPath;
  46. if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
  47. return EC;
  48. PathStorage.append(TmpPath.begin(), TmpPath.end());
  49. }
  50. Path = PathStorage.c_str();
  51. }
  52. SmallVector<wchar_t, MAX_PATH> U16Name;
  53. if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
  54. return EC;
  55. SmallVector<StringRef, 12> PathExts;
  56. PathExts.push_back("");
  57. PathExts.push_back(".exe"); // FIXME: This must be in %PATHEXT%.
  58. if (const char *PathExtEnv = std::getenv("PATHEXT"))
  59. SplitString(PathExtEnv, PathExts, ";");
  60. SmallVector<wchar_t, MAX_PATH> U16Result;
  61. DWORD Len = MAX_PATH;
  62. for (StringRef Ext : PathExts) {
  63. SmallVector<wchar_t, MAX_PATH> U16Ext;
  64. if (std::error_code EC = windows::UTF8ToUTF16(Ext, U16Ext))
  65. return EC;
  66. do {
  67. U16Result.reserve(Len);
  68. Len = ::SearchPathW(Path, c_str(U16Name),
  69. U16Ext.empty() ? nullptr : c_str(U16Ext),
  70. U16Result.capacity(), U16Result.data(), nullptr);
  71. } while (Len > U16Result.capacity());
  72. if (Len != 0)
  73. break; // Found it.
  74. }
  75. if (Len == 0)
  76. return mapWindowsError(::GetLastError());
  77. U16Result.set_size(Len);
  78. SmallVector<char, MAX_PATH> U8Result;
  79. if (std::error_code EC =
  80. windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
  81. return EC;
  82. return std::string(U8Result.begin(), U8Result.end());
  83. #else
  84. return "";
  85. #endif
  86. }
  87. #ifdef MSFT_SUPPORTS_CHILD_PROCESSES // HLSL Change
  88. static HANDLE RedirectIO(const StringRef *path, int fd, std::string* ErrMsg) {
  89. HANDLE h;
  90. if (path == 0) {
  91. if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
  92. GetCurrentProcess(), &h,
  93. 0, TRUE, DUPLICATE_SAME_ACCESS))
  94. return INVALID_HANDLE_VALUE;
  95. return h;
  96. }
  97. std::string fname;
  98. if (path->empty())
  99. fname = "NUL";
  100. else
  101. fname = *path;
  102. SECURITY_ATTRIBUTES sa;
  103. sa.nLength = sizeof(sa);
  104. sa.lpSecurityDescriptor = 0;
  105. sa.bInheritHandle = TRUE;
  106. SmallVector<wchar_t, 128> fnameUnicode;
  107. if (path->empty()) {
  108. // Don't play long-path tricks on "NUL".
  109. if (windows::UTF8ToUTF16(fname, fnameUnicode))
  110. return INVALID_HANDLE_VALUE;
  111. } else {
  112. if (path::widenPath(fname, fnameUnicode))
  113. return INVALID_HANDLE_VALUE;
  114. }
  115. h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
  116. FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
  117. FILE_ATTRIBUTE_NORMAL, NULL);
  118. if (h == INVALID_HANDLE_VALUE) {
  119. MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
  120. (fd ? "input: " : "output: "));
  121. }
  122. return h;
  123. }
  124. /// ArgNeedsQuotes - Check whether argument needs to be quoted when calling
  125. /// CreateProcess.
  126. static bool ArgNeedsQuotes(const char *Str) {
  127. return Str[0] == '\0' || strpbrk(Str, "\t \"&\'()*<>\\`^|") != 0;
  128. }
  129. /// CountPrecedingBackslashes - Returns the number of backslashes preceding Cur
  130. /// in the C string Start.
  131. static unsigned int CountPrecedingBackslashes(const char *Start,
  132. const char *Cur) {
  133. unsigned int Count = 0;
  134. --Cur;
  135. while (Cur >= Start && *Cur == '\\') {
  136. ++Count;
  137. --Cur;
  138. }
  139. return Count;
  140. }
  141. /// EscapePrecedingEscapes - Append a backslash to Dst for every backslash
  142. /// preceding Cur in the Start string. Assumes Dst has enough space.
  143. static char *EscapePrecedingEscapes(char *Dst, const char *Start,
  144. const char *Cur) {
  145. unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
  146. while (PrecedingEscapes > 0) {
  147. *Dst++ = '\\';
  148. --PrecedingEscapes;
  149. }
  150. return Dst;
  151. }
  152. /// ArgLenWithQuotes - Check whether argument needs to be quoted when calling
  153. /// CreateProcess and returns length of quoted arg with escaped quotes
  154. static unsigned int ArgLenWithQuotes(const char *Str) {
  155. const char *Start = Str;
  156. bool Quoted = ArgNeedsQuotes(Str);
  157. unsigned int len = Quoted ? 2 : 0;
  158. while (*Str != '\0') {
  159. if (*Str == '\"') {
  160. // We need to add a backslash, but ensure that it isn't escaped.
  161. unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
  162. len += PrecedingEscapes + 1;
  163. }
  164. // Note that we *don't* need to escape runs of backslashes that don't
  165. // precede a double quote! See MSDN:
  166. // http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.85%29.aspx
  167. ++len;
  168. ++Str;
  169. }
  170. if (Quoted) {
  171. // Make sure the closing quote doesn't get escaped by a trailing backslash.
  172. unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
  173. len += PrecedingEscapes + 1;
  174. }
  175. return len;
  176. }
  177. }
  178. static std::unique_ptr<char[]> flattenArgs(const char **args) {
  179. // First, determine the length of the command line.
  180. unsigned len = 0;
  181. for (unsigned i = 0; args[i]; i++) {
  182. len += ArgLenWithQuotes(args[i]) + 1;
  183. }
  184. // Now build the command line.
  185. std::unique_ptr<char[]> command(new char[len+1]);
  186. char *p = command.get();
  187. for (unsigned i = 0; args[i]; i++) {
  188. const char *arg = args[i];
  189. const char *start = arg;
  190. bool needsQuoting = ArgNeedsQuotes(arg);
  191. if (needsQuoting)
  192. *p++ = '"';
  193. while (*arg != '\0') {
  194. if (*arg == '\"') {
  195. // Escape all preceding escapes (if any), and then escape the quote.
  196. p = EscapePrecedingEscapes(p, start, arg);
  197. *p++ = '\\';
  198. }
  199. *p++ = *arg++;
  200. }
  201. if (needsQuoting) {
  202. // Make sure our quote doesn't get escaped by a trailing backslash.
  203. p = EscapePrecedingEscapes(p, start, arg);
  204. *p++ = '"';
  205. }
  206. *p++ = ' ';
  207. }
  208. *p = 0;
  209. return command;
  210. }
  211. static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
  212. const char **envp, const StringRef **redirects,
  213. unsigned memoryLimit, std::string *ErrMsg) {
  214. if (!sys::fs::can_execute(Program)) {
  215. if (ErrMsg)
  216. *ErrMsg = "program not executable";
  217. return false;
  218. }
  219. // Windows wants a command line, not an array of args, to pass to the new
  220. // process. We have to concatenate them all, while quoting the args that
  221. // have embedded spaces (or are empty).
  222. std::unique_ptr<char[]> command = flattenArgs(args);
  223. // The pointer to the environment block for the new process.
  224. std::vector<wchar_t> EnvBlock;
  225. if (envp) {
  226. // An environment block consists of a null-terminated block of
  227. // null-terminated strings. Convert the array of environment variables to
  228. // an environment block by concatenating them.
  229. for (unsigned i = 0; envp[i]; ++i) {
  230. SmallVector<wchar_t, MAX_PATH> EnvString;
  231. if (std::error_code ec = windows::UTF8ToUTF16(envp[i], EnvString)) {
  232. SetLastError(ec.value());
  233. MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
  234. return false;
  235. }
  236. EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
  237. EnvBlock.push_back(0);
  238. }
  239. EnvBlock.push_back(0);
  240. }
  241. // Create a child process.
  242. STARTUPINFOW si;
  243. memset(&si, 0, sizeof(si));
  244. si.cb = sizeof(si);
  245. si.hStdInput = INVALID_HANDLE_VALUE;
  246. si.hStdOutput = INVALID_HANDLE_VALUE;
  247. si.hStdError = INVALID_HANDLE_VALUE;
  248. if (redirects) {
  249. si.dwFlags = STARTF_USESTDHANDLES;
  250. si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
  251. if (si.hStdInput == INVALID_HANDLE_VALUE) {
  252. MakeErrMsg(ErrMsg, "can't redirect stdin");
  253. return false;
  254. }
  255. si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
  256. if (si.hStdOutput == INVALID_HANDLE_VALUE) {
  257. CloseHandle(si.hStdInput);
  258. MakeErrMsg(ErrMsg, "can't redirect stdout");
  259. return false;
  260. }
  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 handle already open for stdout.
  264. if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
  265. GetCurrentProcess(), &si.hStdError,
  266. 0, TRUE, DUPLICATE_SAME_ACCESS)) {
  267. CloseHandle(si.hStdInput);
  268. CloseHandle(si.hStdOutput);
  269. MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
  270. return false;
  271. }
  272. } else {
  273. // Just redirect stderr
  274. si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
  275. if (si.hStdError == INVALID_HANDLE_VALUE) {
  276. CloseHandle(si.hStdInput);
  277. CloseHandle(si.hStdOutput);
  278. MakeErrMsg(ErrMsg, "can't redirect stderr");
  279. return false;
  280. }
  281. }
  282. }
  283. PROCESS_INFORMATION pi;
  284. memset(&pi, 0, sizeof(pi));
  285. fflush(stdout);
  286. fflush(stderr);
  287. SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
  288. if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
  289. SetLastError(ec.value());
  290. MakeErrMsg(ErrMsg,
  291. std::string("Unable to convert application name to UTF-16"));
  292. return false;
  293. }
  294. SmallVector<wchar_t, MAX_PATH> CommandUtf16;
  295. if (std::error_code ec = windows::UTF8ToUTF16(command.get(), CommandUtf16)) {
  296. SetLastError(ec.value());
  297. MakeErrMsg(ErrMsg,
  298. std::string("Unable to convert command-line to UTF-16"));
  299. return false;
  300. }
  301. BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
  302. TRUE, CREATE_UNICODE_ENVIRONMENT,
  303. EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
  304. &pi);
  305. DWORD err = GetLastError();
  306. // Regardless of whether the process got created or not, we are done with
  307. // the handles we created for it to inherit.
  308. CloseHandle(si.hStdInput);
  309. CloseHandle(si.hStdOutput);
  310. CloseHandle(si.hStdError);
  311. // Now return an error if the process didn't get created.
  312. if (!rc) {
  313. SetLastError(err);
  314. MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
  315. Program.str() + "'");
  316. return false;
  317. }
  318. PI.Pid = pi.dwProcessId;
  319. PI.ProcessHandle = pi.hProcess;
  320. // Make sure these get closed no matter what.
  321. ScopedCommonHandle hThread(pi.hThread);
  322. // Assign the process to a job if a memory limit is defined.
  323. ScopedJobHandle hJob;
  324. if (memoryLimit != 0) {
  325. hJob = CreateJobObjectW(0, 0);
  326. bool success = false;
  327. if (hJob) {
  328. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
  329. memset(&jeli, 0, sizeof(jeli));
  330. jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
  331. jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
  332. if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
  333. &jeli, sizeof(jeli))) {
  334. if (AssignProcessToJobObject(hJob, pi.hProcess))
  335. success = true;
  336. }
  337. }
  338. if (!success) {
  339. SetLastError(GetLastError());
  340. MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
  341. TerminateProcess(pi.hProcess, 1);
  342. WaitForSingleObject(pi.hProcess, INFINITE);
  343. return false;
  344. }
  345. }
  346. return true;
  347. }
  348. namespace llvm {
  349. ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
  350. bool WaitUntilChildTerminates, std::string *ErrMsg) {
  351. assert(PI.Pid && "invalid pid to wait on, process not started?");
  352. assert(PI.ProcessHandle &&
  353. "invalid process handle to wait on, process not started?");
  354. DWORD milliSecondsToWait = 0;
  355. if (WaitUntilChildTerminates)
  356. milliSecondsToWait = INFINITE;
  357. else if (SecondsToWait > 0)
  358. milliSecondsToWait = SecondsToWait * 1000;
  359. ProcessInfo WaitResult = PI;
  360. DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
  361. if (WaitStatus == WAIT_TIMEOUT) {
  362. if (SecondsToWait) {
  363. if (!TerminateProcess(PI.ProcessHandle, 1)) {
  364. if (ErrMsg)
  365. MakeErrMsg(ErrMsg, "Failed to terminate timed-out program.");
  366. // -2 indicates a crash or timeout as opposed to failure to execute.
  367. WaitResult.ReturnCode = -2;
  368. CloseHandle(PI.ProcessHandle);
  369. return WaitResult;
  370. }
  371. WaitForSingleObject(PI.ProcessHandle, INFINITE);
  372. CloseHandle(PI.ProcessHandle);
  373. } else {
  374. // Non-blocking wait.
  375. return ProcessInfo();
  376. }
  377. }
  378. // Get its exit status.
  379. DWORD status;
  380. BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
  381. DWORD err = GetLastError();
  382. if (err != ERROR_INVALID_HANDLE)
  383. CloseHandle(PI.ProcessHandle);
  384. if (!rc) {
  385. SetLastError(err);
  386. if (ErrMsg)
  387. MakeErrMsg(ErrMsg, "Failed getting status for program.");
  388. // -2 indicates a crash or timeout as opposed to failure to execute.
  389. WaitResult.ReturnCode = -2;
  390. return WaitResult;
  391. }
  392. if (!status)
  393. return WaitResult;
  394. // Pass 10(Warning) and 11(Error) to the callee as negative value.
  395. if ((status & 0xBFFF0000U) == 0x80000000U)
  396. WaitResult.ReturnCode = static_cast<int>(status);
  397. else if (status & 0xFF)
  398. WaitResult.ReturnCode = status & 0x7FFFFFFF;
  399. else
  400. WaitResult.ReturnCode = 1;
  401. return WaitResult;
  402. }
  403. #endif // HLSL Change - MSFT_SUPPORTS_CHILD_PROCESSES
  404. std::error_code sys::ChangeStdinToBinary() {
  405. #ifdef MSFT_SUPPORTS_TEXTMODE_STREAMS // HLSL Change
  406. int result = _setmode(_fileno(stdin), _O_BINARY);
  407. if (result == -1)
  408. return std::error_code(errno, std::generic_category());
  409. #endif // HLSL Change
  410. return std::error_code();
  411. }
  412. std::error_code sys::ChangeStdoutToBinary() {
  413. #ifdef MSFT_SUPPORTS_TEXTMODE_STREAMS // HLSL Change
  414. int result = _setmode(_fileno(stdout), _O_BINARY);
  415. if (result == -1)
  416. return std::error_code(errno, std::generic_category());
  417. #endif // HLSL Change
  418. return std::error_code();
  419. }
  420. std::error_code
  421. llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
  422. WindowsEncodingMethod Encoding) {
  423. std::error_code EC;
  424. llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
  425. if (EC)
  426. return EC;
  427. if (Encoding == WEM_UTF8) {
  428. OS << Contents;
  429. } else if (Encoding == WEM_CurrentCodePage) {
  430. SmallVector<wchar_t, 1> ArgsUTF16;
  431. SmallVector<char, 1> ArgsCurCP;
  432. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  433. return EC;
  434. if ((EC = windows::UTF16ToCurCP(
  435. ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
  436. return EC;
  437. OS.write(ArgsCurCP.data(), ArgsCurCP.size());
  438. } else if (Encoding == WEM_UTF16) {
  439. SmallVector<wchar_t, 1> ArgsUTF16;
  440. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  441. return EC;
  442. // Endianness guessing
  443. char BOM[2];
  444. uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
  445. memcpy(BOM, &src, 2);
  446. OS.write(BOM, 2);
  447. OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
  448. } else {
  449. llvm_unreachable("Unknown encoding");
  450. }
  451. if (OS.has_error())
  452. return make_error_code(errc::io_error);
  453. return EC;
  454. }
  455. #ifdef MSFT_SUPPORTS_CHILD_PROCESSES // HLSL Change
  456. bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
  457. // The documented max length of the command line passed to CreateProcess.
  458. static const size_t MaxCommandStringLength = 32768;
  459. size_t ArgLength = 0;
  460. for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
  461. I != E; ++I) {
  462. // Account for the trailing space for every arg but the last one and the
  463. // trailing NULL of the last argument.
  464. ArgLength += ArgLenWithQuotes(*I) + 1;
  465. if (ArgLength > MaxCommandStringLength) {
  466. return false;
  467. }
  468. }
  469. return true;
  470. }
  471. #endif // MSFT_SUPPORTS_CHILD_PROCESSES // HLSL Change
  472. }