Program.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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/Path.h"
  19. #include "llvm/Support/WindowsError.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. #include <cstdio>
  22. #include <fcntl.h>
  23. #include <io.h>
  24. #include <malloc.h>
  25. #include <numeric>
  26. //===----------------------------------------------------------------------===//
  27. //=== WARNING: Implementation here must contain only Win32 specific code
  28. //=== and must not be UNIX code
  29. //===----------------------------------------------------------------------===//
  30. namespace llvm {
  31. ProcessInfo::ProcessInfo() : Pid(0), Process(0), ReturnCode(0) {}
  32. ErrorOr<std::string> sys::findProgramByName(StringRef Name,
  33. ArrayRef<StringRef> Paths) {
  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. // Lets attach the extension manually. That is needed for files
  69. // with a point in name like aaa.bbb. SearchPathW will not add extension
  70. // from its argument to such files because it thinks they already had one.
  71. SmallVector<wchar_t, MAX_PATH> U16NameExt;
  72. if (std::error_code EC =
  73. windows::UTF8ToUTF16(Twine(Name + Ext).str(), U16NameExt))
  74. return EC;
  75. Len = ::SearchPathW(Path, c_str(U16NameExt), nullptr,
  76. U16Result.capacity(), U16Result.data(), nullptr);
  77. } while (Len > U16Result.capacity());
  78. if (Len != 0)
  79. break; // Found it.
  80. }
  81. if (Len == 0)
  82. return mapWindowsError(::GetLastError());
  83. U16Result.set_size(Len);
  84. SmallVector<char, MAX_PATH> U8Result;
  85. if (std::error_code EC =
  86. windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
  87. return EC;
  88. return std::string(U8Result.begin(), U8Result.end());
  89. }
  90. static HANDLE RedirectIO(Optional<StringRef> Path, int fd,
  91. std::string *ErrMsg) {
  92. HANDLE h;
  93. if (!Path) {
  94. if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
  95. GetCurrentProcess(), &h,
  96. 0, TRUE, DUPLICATE_SAME_ACCESS))
  97. return INVALID_HANDLE_VALUE;
  98. return h;
  99. }
  100. std::string fname;
  101. if (Path->empty())
  102. fname = "NUL";
  103. else
  104. fname = *Path;
  105. SECURITY_ATTRIBUTES sa;
  106. sa.nLength = sizeof(sa);
  107. sa.lpSecurityDescriptor = 0;
  108. sa.bInheritHandle = TRUE;
  109. SmallVector<wchar_t, 128> fnameUnicode;
  110. if (Path->empty()) {
  111. // Don't play long-path tricks on "NUL".
  112. if (windows::UTF8ToUTF16(fname, fnameUnicode))
  113. return INVALID_HANDLE_VALUE;
  114. } else {
  115. if (path::widenPath(fname, fnameUnicode))
  116. return INVALID_HANDLE_VALUE;
  117. }
  118. h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
  119. FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
  120. FILE_ATTRIBUTE_NORMAL, NULL);
  121. if (h == INVALID_HANDLE_VALUE) {
  122. MakeErrMsg(ErrMsg, fname + ": Can't open file for " +
  123. (fd ? "input" : "output"));
  124. }
  125. return h;
  126. }
  127. }
  128. static SmallVector<StringRef, 8> buildArgVector(const char **Args) {
  129. SmallVector<StringRef, 8> Result;
  130. for (unsigned I = 0; Args[I]; ++I)
  131. Result.push_back(StringRef(Args[I]));
  132. return Result;
  133. }
  134. static bool Execute(ProcessInfo &PI, StringRef Program, const char **Args,
  135. const char **Envp, ArrayRef<Optional<StringRef>> Redirects,
  136. unsigned MemoryLimit, std::string *ErrMsg) {
  137. if (!sys::fs::can_execute(Program)) {
  138. if (ErrMsg)
  139. *ErrMsg = "program not executable";
  140. return false;
  141. }
  142. // can_execute may succeed by looking at Program + ".exe". CreateProcessW
  143. // will implicitly add the .exe if we provide a command line without an
  144. // executable path, but since we use an explicit executable, we have to add
  145. // ".exe" ourselves.
  146. SmallString<64> ProgramStorage;
  147. if (!sys::fs::exists(Program))
  148. Program = Twine(Program + ".exe").toStringRef(ProgramStorage);
  149. // Windows wants a command line, not an array of args, to pass to the new
  150. // process. We have to concatenate them all, while quoting the args that
  151. // have embedded spaces (or are empty).
  152. auto ArgVector = buildArgVector(Args);
  153. std::string Command = flattenWindowsCommandLine(ArgVector);
  154. // The pointer to the environment block for the new process.
  155. std::vector<wchar_t> EnvBlock;
  156. if (Envp) {
  157. // An environment block consists of a null-terminated block of
  158. // null-terminated strings. Convert the array of environment variables to
  159. // an environment block by concatenating them.
  160. for (unsigned i = 0; Envp[i]; ++i) {
  161. SmallVector<wchar_t, MAX_PATH> EnvString;
  162. if (std::error_code ec = windows::UTF8ToUTF16(Envp[i], EnvString)) {
  163. SetLastError(ec.value());
  164. MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
  165. return false;
  166. }
  167. EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
  168. EnvBlock.push_back(0);
  169. }
  170. EnvBlock.push_back(0);
  171. }
  172. // Create a child process.
  173. STARTUPINFOW si;
  174. memset(&si, 0, sizeof(si));
  175. si.cb = sizeof(si);
  176. si.hStdInput = INVALID_HANDLE_VALUE;
  177. si.hStdOutput = INVALID_HANDLE_VALUE;
  178. si.hStdError = INVALID_HANDLE_VALUE;
  179. if (!Redirects.empty()) {
  180. si.dwFlags = STARTF_USESTDHANDLES;
  181. si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
  182. if (si.hStdInput == INVALID_HANDLE_VALUE) {
  183. MakeErrMsg(ErrMsg, "can't redirect stdin");
  184. return false;
  185. }
  186. si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
  187. if (si.hStdOutput == INVALID_HANDLE_VALUE) {
  188. CloseHandle(si.hStdInput);
  189. MakeErrMsg(ErrMsg, "can't redirect stdout");
  190. return false;
  191. }
  192. if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
  193. // If stdout and stderr should go to the same place, redirect stderr
  194. // to the handle already open for stdout.
  195. if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
  196. GetCurrentProcess(), &si.hStdError,
  197. 0, TRUE, DUPLICATE_SAME_ACCESS)) {
  198. CloseHandle(si.hStdInput);
  199. CloseHandle(si.hStdOutput);
  200. MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
  201. return false;
  202. }
  203. } else {
  204. // Just redirect stderr
  205. si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
  206. if (si.hStdError == INVALID_HANDLE_VALUE) {
  207. CloseHandle(si.hStdInput);
  208. CloseHandle(si.hStdOutput);
  209. MakeErrMsg(ErrMsg, "can't redirect stderr");
  210. return false;
  211. }
  212. }
  213. }
  214. PROCESS_INFORMATION pi;
  215. memset(&pi, 0, sizeof(pi));
  216. fflush(stdout);
  217. fflush(stderr);
  218. SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
  219. if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
  220. SetLastError(ec.value());
  221. MakeErrMsg(ErrMsg,
  222. std::string("Unable to convert application name to UTF-16"));
  223. return false;
  224. }
  225. SmallVector<wchar_t, MAX_PATH> CommandUtf16;
  226. if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
  227. SetLastError(ec.value());
  228. MakeErrMsg(ErrMsg,
  229. std::string("Unable to convert command-line to UTF-16"));
  230. return false;
  231. }
  232. BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
  233. TRUE, CREATE_UNICODE_ENVIRONMENT,
  234. EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
  235. &pi);
  236. DWORD err = GetLastError();
  237. // Regardless of whether the process got created or not, we are done with
  238. // the handles we created for it to inherit.
  239. CloseHandle(si.hStdInput);
  240. CloseHandle(si.hStdOutput);
  241. CloseHandle(si.hStdError);
  242. // Now return an error if the process didn't get created.
  243. if (!rc) {
  244. SetLastError(err);
  245. MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
  246. Program.str() + "'");
  247. return false;
  248. }
  249. PI.Pid = pi.dwProcessId;
  250. PI.Process = pi.hProcess;
  251. // Make sure these get closed no matter what.
  252. ScopedCommonHandle hThread(pi.hThread);
  253. // Assign the process to a job if a memory limit is defined.
  254. ScopedJobHandle hJob;
  255. if (MemoryLimit != 0) {
  256. hJob = CreateJobObjectW(0, 0);
  257. bool success = false;
  258. if (hJob) {
  259. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
  260. memset(&jeli, 0, sizeof(jeli));
  261. jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
  262. jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
  263. if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
  264. &jeli, sizeof(jeli))) {
  265. if (AssignProcessToJobObject(hJob, pi.hProcess))
  266. success = true;
  267. }
  268. }
  269. if (!success) {
  270. SetLastError(GetLastError());
  271. MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
  272. TerminateProcess(pi.hProcess, 1);
  273. WaitForSingleObject(pi.hProcess, INFINITE);
  274. return false;
  275. }
  276. }
  277. return true;
  278. }
  279. static bool argNeedsQuotes(StringRef Arg) {
  280. if (Arg.empty())
  281. return true;
  282. return StringRef::npos != Arg.find_first_of("\t \"&\'()*<>\\`^|");
  283. }
  284. static std::string quoteSingleArg(StringRef Arg) {
  285. std::string Result;
  286. Result.push_back('"');
  287. while (!Arg.empty()) {
  288. size_t FirstNonBackslash = Arg.find_first_not_of('\\');
  289. size_t BackslashCount = FirstNonBackslash;
  290. if (FirstNonBackslash == StringRef::npos) {
  291. // The entire remainder of the argument is backslashes. Escape all of
  292. // them and just early out.
  293. BackslashCount = Arg.size();
  294. Result.append(BackslashCount * 2, '\\');
  295. break;
  296. }
  297. if (Arg[FirstNonBackslash] == '\"') {
  298. // This is an embedded quote. Escape all preceding backslashes, then
  299. // add one additional backslash to escape the quote.
  300. Result.append(BackslashCount * 2 + 1, '\\');
  301. Result.push_back('\"');
  302. } else {
  303. // This is just a normal character. Don't escape any of the preceding
  304. // backslashes, just append them as they are and then append the
  305. // character.
  306. Result.append(BackslashCount, '\\');
  307. Result.push_back(Arg[FirstNonBackslash]);
  308. }
  309. // Drop all the backslashes, plus the following character.
  310. Arg = Arg.drop_front(FirstNonBackslash + 1);
  311. }
  312. Result.push_back('"');
  313. return Result;
  314. }
  315. namespace llvm {
  316. std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
  317. std::string Command;
  318. for (StringRef Arg : Args) {
  319. if (argNeedsQuotes(Arg))
  320. Command += quoteSingleArg(Arg);
  321. else
  322. Command += Arg;
  323. Command.push_back(' ');
  324. }
  325. return Command;
  326. }
  327. ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
  328. bool WaitUntilChildTerminates, std::string *ErrMsg) {
  329. assert(PI.Pid && "invalid pid to wait on, process not started?");
  330. assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
  331. "invalid process handle to wait on, process not started?");
  332. DWORD milliSecondsToWait = 0;
  333. if (WaitUntilChildTerminates)
  334. milliSecondsToWait = INFINITE;
  335. else if (SecondsToWait > 0)
  336. milliSecondsToWait = SecondsToWait * 1000;
  337. ProcessInfo WaitResult = PI;
  338. DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
  339. if (WaitStatus == WAIT_TIMEOUT) {
  340. if (SecondsToWait) {
  341. if (!TerminateProcess(PI.Process, 1)) {
  342. if (ErrMsg)
  343. MakeErrMsg(ErrMsg, "Failed to terminate timed-out program");
  344. // -2 indicates a crash or timeout as opposed to failure to execute.
  345. WaitResult.ReturnCode = -2;
  346. CloseHandle(PI.Process);
  347. return WaitResult;
  348. }
  349. WaitForSingleObject(PI.Process, INFINITE);
  350. CloseHandle(PI.Process);
  351. } else {
  352. // Non-blocking wait.
  353. return ProcessInfo();
  354. }
  355. }
  356. // Get its exit status.
  357. DWORD status;
  358. BOOL rc = GetExitCodeProcess(PI.Process, &status);
  359. DWORD err = GetLastError();
  360. if (err != ERROR_INVALID_HANDLE)
  361. CloseHandle(PI.Process);
  362. if (!rc) {
  363. SetLastError(err);
  364. if (ErrMsg)
  365. MakeErrMsg(ErrMsg, "Failed getting status for program");
  366. // -2 indicates a crash or timeout as opposed to failure to execute.
  367. WaitResult.ReturnCode = -2;
  368. return WaitResult;
  369. }
  370. if (!status)
  371. return WaitResult;
  372. // Pass 10(Warning) and 11(Error) to the callee as negative value.
  373. if ((status & 0xBFFF0000U) == 0x80000000U)
  374. WaitResult.ReturnCode = static_cast<int>(status);
  375. else if (status & 0xFF)
  376. WaitResult.ReturnCode = status & 0x7FFFFFFF;
  377. else
  378. WaitResult.ReturnCode = 1;
  379. return WaitResult;
  380. }
  381. std::error_code sys::ChangeStdinToBinary() {
  382. int result = _setmode(_fileno(stdin), _O_BINARY);
  383. if (result == -1)
  384. return std::error_code(errno, std::generic_category());
  385. return std::error_code();
  386. }
  387. std::error_code sys::ChangeStdoutToBinary() {
  388. int result = _setmode(_fileno(stdout), _O_BINARY);
  389. if (result == -1)
  390. return std::error_code(errno, std::generic_category());
  391. return std::error_code();
  392. }
  393. std::error_code
  394. llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
  395. WindowsEncodingMethod Encoding) {
  396. std::error_code EC;
  397. llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::F_Text);
  398. if (EC)
  399. return EC;
  400. if (Encoding == WEM_UTF8) {
  401. OS << Contents;
  402. } else if (Encoding == WEM_CurrentCodePage) {
  403. SmallVector<wchar_t, 1> ArgsUTF16;
  404. SmallVector<char, 1> ArgsCurCP;
  405. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  406. return EC;
  407. if ((EC = windows::UTF16ToCurCP(
  408. ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
  409. return EC;
  410. OS.write(ArgsCurCP.data(), ArgsCurCP.size());
  411. } else if (Encoding == WEM_UTF16) {
  412. SmallVector<wchar_t, 1> ArgsUTF16;
  413. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  414. return EC;
  415. // Endianness guessing
  416. char BOM[2];
  417. uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
  418. memcpy(BOM, &src, 2);
  419. OS.write(BOM, 2);
  420. OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
  421. } else {
  422. llvm_unreachable("Unknown encoding");
  423. }
  424. if (OS.has_error())
  425. return make_error_code(errc::io_error);
  426. return EC;
  427. }
  428. bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
  429. ArrayRef<StringRef> Args) {
  430. // The documented max length of the command line passed to CreateProcess.
  431. static const size_t MaxCommandStringLength = 32768;
  432. SmallVector<StringRef, 8> FullArgs;
  433. FullArgs.push_back(Program);
  434. FullArgs.append(Args.begin(), Args.end());
  435. std::string Result = flattenWindowsCommandLine(FullArgs);
  436. return (Result.size() + 1) <= MaxCommandStringLength;
  437. }
  438. }