Program.inc 16 KB

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