Program.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 bool Execute(ProcessInfo &PI, StringRef Program,
  129. ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
  130. ArrayRef<Optional<StringRef>> Redirects,
  131. unsigned MemoryLimit, std::string *ErrMsg) {
  132. if (!sys::fs::can_execute(Program)) {
  133. if (ErrMsg)
  134. *ErrMsg = "program not executable";
  135. return false;
  136. }
  137. // can_execute may succeed by looking at Program + ".exe". CreateProcessW
  138. // will implicitly add the .exe if we provide a command line without an
  139. // executable path, but since we use an explicit executable, we have to add
  140. // ".exe" ourselves.
  141. SmallString<64> ProgramStorage;
  142. if (!sys::fs::exists(Program))
  143. Program = Twine(Program + ".exe").toStringRef(ProgramStorage);
  144. // Windows wants a command line, not an array of args, to pass to the new
  145. // process. We have to concatenate them all, while quoting the args that
  146. // have embedded spaces (or are empty).
  147. std::string Command = flattenWindowsCommandLine(Args);
  148. // The pointer to the environment block for the new process.
  149. std::vector<wchar_t> EnvBlock;
  150. if (Env) {
  151. // An environment block consists of a null-terminated block of
  152. // null-terminated strings. Convert the array of environment variables to
  153. // an environment block by concatenating them.
  154. for (const auto E : *Env) {
  155. SmallVector<wchar_t, MAX_PATH> EnvString;
  156. if (std::error_code ec = windows::UTF8ToUTF16(E, EnvString)) {
  157. SetLastError(ec.value());
  158. MakeErrMsg(ErrMsg, "Unable to convert environment variable to UTF-16");
  159. return false;
  160. }
  161. EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
  162. EnvBlock.push_back(0);
  163. }
  164. EnvBlock.push_back(0);
  165. }
  166. // Create a child process.
  167. STARTUPINFOW si;
  168. memset(&si, 0, sizeof(si));
  169. si.cb = sizeof(si);
  170. si.hStdInput = INVALID_HANDLE_VALUE;
  171. si.hStdOutput = INVALID_HANDLE_VALUE;
  172. si.hStdError = INVALID_HANDLE_VALUE;
  173. if (!Redirects.empty()) {
  174. si.dwFlags = STARTF_USESTDHANDLES;
  175. si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
  176. if (si.hStdInput == INVALID_HANDLE_VALUE) {
  177. MakeErrMsg(ErrMsg, "can't redirect stdin");
  178. return false;
  179. }
  180. si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
  181. if (si.hStdOutput == INVALID_HANDLE_VALUE) {
  182. CloseHandle(si.hStdInput);
  183. MakeErrMsg(ErrMsg, "can't redirect stdout");
  184. return false;
  185. }
  186. if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
  187. // If stdout and stderr should go to the same place, redirect stderr
  188. // to the handle already open for stdout.
  189. if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
  190. GetCurrentProcess(), &si.hStdError,
  191. 0, TRUE, DUPLICATE_SAME_ACCESS)) {
  192. CloseHandle(si.hStdInput);
  193. CloseHandle(si.hStdOutput);
  194. MakeErrMsg(ErrMsg, "can't dup stderr to stdout");
  195. return false;
  196. }
  197. } else {
  198. // Just redirect stderr
  199. si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
  200. if (si.hStdError == INVALID_HANDLE_VALUE) {
  201. CloseHandle(si.hStdInput);
  202. CloseHandle(si.hStdOutput);
  203. MakeErrMsg(ErrMsg, "can't redirect stderr");
  204. return false;
  205. }
  206. }
  207. }
  208. PROCESS_INFORMATION pi;
  209. memset(&pi, 0, sizeof(pi));
  210. fflush(stdout);
  211. fflush(stderr);
  212. SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
  213. if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
  214. SetLastError(ec.value());
  215. MakeErrMsg(ErrMsg,
  216. std::string("Unable to convert application name to UTF-16"));
  217. return false;
  218. }
  219. SmallVector<wchar_t, MAX_PATH> CommandUtf16;
  220. if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
  221. SetLastError(ec.value());
  222. MakeErrMsg(ErrMsg,
  223. std::string("Unable to convert command-line to UTF-16"));
  224. return false;
  225. }
  226. BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
  227. TRUE, CREATE_UNICODE_ENVIRONMENT,
  228. EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
  229. &pi);
  230. DWORD err = GetLastError();
  231. // Regardless of whether the process got created or not, we are done with
  232. // the handles we created for it to inherit.
  233. CloseHandle(si.hStdInput);
  234. CloseHandle(si.hStdOutput);
  235. CloseHandle(si.hStdError);
  236. // Now return an error if the process didn't get created.
  237. if (!rc) {
  238. SetLastError(err);
  239. MakeErrMsg(ErrMsg, std::string("Couldn't execute program '") +
  240. Program.str() + "'");
  241. return false;
  242. }
  243. PI.Pid = pi.dwProcessId;
  244. PI.Process = pi.hProcess;
  245. // Make sure these get closed no matter what.
  246. ScopedCommonHandle hThread(pi.hThread);
  247. // Assign the process to a job if a memory limit is defined.
  248. ScopedJobHandle hJob;
  249. if (MemoryLimit != 0) {
  250. hJob = CreateJobObjectW(0, 0);
  251. bool success = false;
  252. if (hJob) {
  253. JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
  254. memset(&jeli, 0, sizeof(jeli));
  255. jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
  256. jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
  257. if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
  258. &jeli, sizeof(jeli))) {
  259. if (AssignProcessToJobObject(hJob, pi.hProcess))
  260. success = true;
  261. }
  262. }
  263. if (!success) {
  264. SetLastError(GetLastError());
  265. MakeErrMsg(ErrMsg, std::string("Unable to set memory limit"));
  266. TerminateProcess(pi.hProcess, 1);
  267. WaitForSingleObject(pi.hProcess, INFINITE);
  268. return false;
  269. }
  270. }
  271. return true;
  272. }
  273. static bool argNeedsQuotes(StringRef Arg) {
  274. if (Arg.empty())
  275. return true;
  276. return StringRef::npos != Arg.find_first_of("\t \"&\'()*<>\\`^|");
  277. }
  278. static std::string quoteSingleArg(StringRef Arg) {
  279. std::string Result;
  280. Result.push_back('"');
  281. while (!Arg.empty()) {
  282. size_t FirstNonBackslash = Arg.find_first_not_of('\\');
  283. size_t BackslashCount = FirstNonBackslash;
  284. if (FirstNonBackslash == StringRef::npos) {
  285. // The entire remainder of the argument is backslashes. Escape all of
  286. // them and just early out.
  287. BackslashCount = Arg.size();
  288. Result.append(BackslashCount * 2, '\\');
  289. break;
  290. }
  291. if (Arg[FirstNonBackslash] == '\"') {
  292. // This is an embedded quote. Escape all preceding backslashes, then
  293. // add one additional backslash to escape the quote.
  294. Result.append(BackslashCount * 2 + 1, '\\');
  295. Result.push_back('\"');
  296. } else {
  297. // This is just a normal character. Don't escape any of the preceding
  298. // backslashes, just append them as they are and then append the
  299. // character.
  300. Result.append(BackslashCount, '\\');
  301. Result.push_back(Arg[FirstNonBackslash]);
  302. }
  303. // Drop all the backslashes, plus the following character.
  304. Arg = Arg.drop_front(FirstNonBackslash + 1);
  305. }
  306. Result.push_back('"');
  307. return Result;
  308. }
  309. namespace llvm {
  310. std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
  311. std::string Command;
  312. for (StringRef Arg : Args) {
  313. if (argNeedsQuotes(Arg))
  314. Command += quoteSingleArg(Arg);
  315. else
  316. Command += Arg;
  317. Command.push_back(' ');
  318. }
  319. return Command;
  320. }
  321. ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
  322. bool WaitUntilChildTerminates, std::string *ErrMsg) {
  323. assert(PI.Pid && "invalid pid to wait on, process not started?");
  324. assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
  325. "invalid process handle to wait on, process not started?");
  326. DWORD milliSecondsToWait = 0;
  327. if (WaitUntilChildTerminates)
  328. milliSecondsToWait = INFINITE;
  329. else if (SecondsToWait > 0)
  330. milliSecondsToWait = SecondsToWait * 1000;
  331. ProcessInfo WaitResult = PI;
  332. DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
  333. if (WaitStatus == WAIT_TIMEOUT) {
  334. if (SecondsToWait) {
  335. if (!TerminateProcess(PI.Process, 1)) {
  336. if (ErrMsg)
  337. MakeErrMsg(ErrMsg, "Failed to terminate timed-out program");
  338. // -2 indicates a crash or timeout as opposed to failure to execute.
  339. WaitResult.ReturnCode = -2;
  340. CloseHandle(PI.Process);
  341. return WaitResult;
  342. }
  343. WaitForSingleObject(PI.Process, INFINITE);
  344. CloseHandle(PI.Process);
  345. } else {
  346. // Non-blocking wait.
  347. return ProcessInfo();
  348. }
  349. }
  350. // Get its exit status.
  351. DWORD status;
  352. BOOL rc = GetExitCodeProcess(PI.Process, &status);
  353. DWORD err = GetLastError();
  354. if (err != ERROR_INVALID_HANDLE)
  355. CloseHandle(PI.Process);
  356. if (!rc) {
  357. SetLastError(err);
  358. if (ErrMsg)
  359. MakeErrMsg(ErrMsg, "Failed getting status for program");
  360. // -2 indicates a crash or timeout as opposed to failure to execute.
  361. WaitResult.ReturnCode = -2;
  362. return WaitResult;
  363. }
  364. if (!status)
  365. return WaitResult;
  366. // Pass 10(Warning) and 11(Error) to the callee as negative value.
  367. if ((status & 0xBFFF0000U) == 0x80000000U)
  368. WaitResult.ReturnCode = static_cast<int>(status);
  369. else if (status & 0xFF)
  370. WaitResult.ReturnCode = status & 0x7FFFFFFF;
  371. else
  372. WaitResult.ReturnCode = 1;
  373. return WaitResult;
  374. }
  375. std::error_code sys::ChangeStdinToBinary() {
  376. int result = _setmode(_fileno(stdin), _O_BINARY);
  377. if (result == -1)
  378. return std::error_code(errno, std::generic_category());
  379. return std::error_code();
  380. }
  381. std::error_code sys::ChangeStdoutToBinary() {
  382. int result = _setmode(_fileno(stdout), _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
  388. llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
  389. WindowsEncodingMethod Encoding) {
  390. std::error_code EC;
  391. llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::F_Text);
  392. if (EC)
  393. return EC;
  394. if (Encoding == WEM_UTF8) {
  395. OS << Contents;
  396. } else if (Encoding == WEM_CurrentCodePage) {
  397. SmallVector<wchar_t, 1> ArgsUTF16;
  398. SmallVector<char, 1> ArgsCurCP;
  399. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  400. return EC;
  401. if ((EC = windows::UTF16ToCurCP(
  402. ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
  403. return EC;
  404. OS.write(ArgsCurCP.data(), ArgsCurCP.size());
  405. } else if (Encoding == WEM_UTF16) {
  406. SmallVector<wchar_t, 1> ArgsUTF16;
  407. if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
  408. return EC;
  409. // Endianness guessing
  410. char BOM[2];
  411. uint16_t src = UNI_UTF16_BYTE_ORDER_MARK_NATIVE;
  412. memcpy(BOM, &src, 2);
  413. OS.write(BOM, 2);
  414. OS.write((char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
  415. } else {
  416. llvm_unreachable("Unknown encoding");
  417. }
  418. if (OS.has_error())
  419. return make_error_code(errc::io_error);
  420. return EC;
  421. }
  422. bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
  423. ArrayRef<StringRef> Args) {
  424. // The documented max length of the command line passed to CreateProcess.
  425. static const size_t MaxCommandStringLength = 32768;
  426. SmallVector<StringRef, 8> FullArgs;
  427. FullArgs.push_back(Program);
  428. FullArgs.append(Args.begin(), Args.end());
  429. std::string Result = flattenWindowsCommandLine(FullArgs);
  430. return (Result.size() + 1) <= MaxCommandStringLength;
  431. }
  432. }