37ErrorOr<std::string> sys::findProgramByName(StringRef Name,
38 ArrayRef<StringRef> Paths) {
41 if (
Name.find_first_of(
"/\\") != StringRef::npos)
42 return std::string(Name);
44 const wchar_t *
Path =
nullptr;
45 std::wstring PathStorage;
47 PathStorage.reserve(Paths.size() * MAX_PATH);
48 for (
unsigned i = 0; i < Paths.size(); ++i) {
50 PathStorage.push_back(L
';');
51 StringRef
P = Paths[i];
52 SmallVector<wchar_t, MAX_PATH> TmpPath;
53 if (std::error_code EC = windows::UTF8ToUTF16(
P, TmpPath))
55 PathStorage.append(TmpPath.begin(), TmpPath.end());
57 Path = PathStorage.c_str();
60 SmallVector<wchar_t, MAX_PATH> U16Name;
61 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
64 SmallVector<StringRef, 12> PathExts;
65 PathExts.push_back(
"");
66 PathExts.push_back(
".exe");
67 if (
const char *PathExtEnv = std::getenv(
"PATHEXT"))
70 SmallVector<char, MAX_PATH> U8Result;
71 for (StringRef Ext : PathExts) {
72 SmallVector<wchar_t, MAX_PATH> U16Result;
75 U16Result.resize_for_overwrite(Len);
79 SmallVector<wchar_t, MAX_PATH> U16NameExt;
80 if (std::error_code EC =
81 windows::UTF8ToUTF16(Twine(Name + Ext).str(), U16NameExt))
84 Len = ::SearchPathW(Path,
c_str(U16NameExt),
nullptr, U16Result.size(),
85 U16Result.data(),
nullptr);
86 }
while (Len > U16Result.size());
91 U16Result.truncate(Len);
93 if (std::error_code EC =
94 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
97 if (sys::fs::can_execute(U8Result))
103 if (U8Result.empty())
107 return std::string(U8Result.begin(), U8Result.end());
110bool MakeErrMsg(std::string *ErrMsg,
const std::string &prefix) {
114 DWORD LastError = GetLastError();
115 DWORD
R = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
116 FORMAT_MESSAGE_FROM_SYSTEM |
117 FORMAT_MESSAGE_MAX_WIDTH_MASK,
118 NULL, LastError, 0, (LPSTR)&buffer, 1, NULL);
120 *ErrMsg = prefix +
": " + buffer;
122 *ErrMsg = prefix +
": Unknown error";
129static HANDLE RedirectIO(std::optional<StringRef> Path,
int fd,
130 std::string *ErrMsg) {
133 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
134 GetCurrentProcess(), &h, 0, TRUE,
135 DUPLICATE_SAME_ACCESS))
136 return INVALID_HANDLE_VALUE;
144 fname = std::string(*Path);
146 SECURITY_ATTRIBUTES sa;
147 sa.nLength =
sizeof(sa);
148 sa.lpSecurityDescriptor = 0;
149 sa.bInheritHandle = TRUE;
151 SmallVector<wchar_t, 128> fnameUnicode;
154 if (windows::UTF8ToUTF16(fname, fnameUnicode))
155 return INVALID_HANDLE_VALUE;
157 if (sys::windows::widenPath(fname, fnameUnicode))
158 return INVALID_HANDLE_VALUE;
160 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
161 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
162 FILE_ATTRIBUTE_NORMAL, NULL);
163 if (h == INVALID_HANDLE_VALUE) {
165 fname +
": Can't open file for " + (fd ?
"input" :
"output"));
173static bool Execute(ProcessInfo &PI, StringRef Program,
174 ArrayRef<StringRef> Args,
175 std::optional<ArrayRef<StringRef>> Env,
176 ArrayRef<std::optional<StringRef>> Redirects,
177 unsigned MemoryLimit, std::string *ErrMsg,
178 BitVector *AffinityMask,
bool DetachProcess) {
179 if (!sys::fs::can_execute(Program)) {
181 *ErrMsg =
"program not executable";
189 SmallString<64> ProgramStorage;
190 if (!sys::fs::exists(Program))
191 Program = Twine(Program +
".exe").toStringRef(ProgramStorage);
196 auto Result = flattenWindowsCommandLine(Args);
197 if (std::error_code ec =
Result.getError()) {
198 SetLastError(ec.value());
199 MakeErrMsg(ErrMsg, std::string(
"Unable to convert command-line to UTF-16"));
202 std::wstring Command = *
Result;
205 std::vector<wchar_t> EnvBlock;
211 for (StringRef
E : *Env) {
212 SmallVector<wchar_t, MAX_PATH> EnvString;
213 if (std::error_code ec = windows::UTF8ToUTF16(
E, EnvString)) {
214 SetLastError(ec.value());
215 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
220 EnvBlock.push_back(0);
223 if (Env->size() == 0)
224 EnvBlock.push_back(0);
225 EnvBlock.push_back(0);
230 memset(&si, 0,
sizeof(si));
232 si.hStdInput = INVALID_HANDLE_VALUE;
233 si.hStdOutput = INVALID_HANDLE_VALUE;
234 si.hStdError = INVALID_HANDLE_VALUE;
236 if (!Redirects.empty()) {
237 si.dwFlags = STARTF_USESTDHANDLES;
239 si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
240 if (si.hStdInput == INVALID_HANDLE_VALUE) {
244 si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
245 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
246 CloseHandle(si.hStdInput);
250 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
253 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
254 GetCurrentProcess(), &si.hStdError, 0, TRUE,
255 DUPLICATE_SAME_ACCESS)) {
256 CloseHandle(si.hStdInput);
257 CloseHandle(si.hStdOutput);
258 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
263 si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
264 if (si.hStdError == INVALID_HANDLE_VALUE) {
265 CloseHandle(si.hStdInput);
266 CloseHandle(si.hStdOutput);
273 PROCESS_INFORMATION
pi;
274 memset(&pi, 0,
sizeof(pi));
279 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
280 if (std::error_code ec = sys::windows::widenPath(Program, ProgramUtf16)) {
281 SetLastError(ec.value());
283 std::string(
"Unable to convert application name to UTF-16"));
287 unsigned CreateFlags = CREATE_UNICODE_ENVIRONMENT;
289 CreateFlags |= CREATE_SUSPENDED;
291 CreateFlags |= DETACHED_PROCESS;
293 std::vector<wchar_t> CommandUtf16(Command.size() + 1, 0);
294 std::copy(Command.begin(), Command.end(), CommandUtf16.begin());
295 BOOL
rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0, TRUE,
296 CreateFlags, EnvBlock.empty() ? 0 : EnvBlock.data(),
298 DWORD err = GetLastError();
302 CloseHandle(si.hStdInput);
303 CloseHandle(si.hStdOutput);
304 CloseHandle(si.hStdError);
310 std::string(
"Couldn't execute program '") + Program.str() +
"'");
314 PI.Pid =
pi.dwProcessId;
315 PI.Process =
pi.hProcess;
322 if (MemoryLimit != 0) {
323 hJob = CreateJobObjectW(0, 0);
326 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
327 memset(&jeli, 0,
sizeof(jeli));
328 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
329 jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
330 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
331 &jeli,
sizeof(jeli))) {
332 if (AssignProcessToJobObject(hJob,
pi.hProcess))
337 SetLastError(GetLastError());
338 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
339 TerminateProcess(
pi.hProcess, 1);
340 WaitForSingleObject(
pi.hProcess, INFINITE);
347 ::SetProcessAffinityMask(
pi.hProcess,
348 (DWORD_PTR)AffinityMask->getData().front());
349 ::ResumeThread(
pi.hThread);
355static bool argNeedsQuotes(StringRef Arg) {
358 return StringRef::npos != Arg.find_first_of(
"\t \"&\'()*<>\\`^|\n");
361static std::string quoteSingleArg(StringRef Arg) {
365 while (!Arg.empty()) {
366 size_t FirstNonBackslash = Arg.find_first_not_of(
'\\');
367 size_t BackslashCount = FirstNonBackslash;
368 if (FirstNonBackslash == StringRef::npos) {
371 BackslashCount = Arg.size();
372 Result.append(BackslashCount * 2,
'\\');
376 if (Arg[FirstNonBackslash] ==
'\"') {
379 Result.append(BackslashCount * 2 + 1,
'\\');
385 Result.append(BackslashCount,
'\\');
386 Result.push_back(Arg[FirstNonBackslash]);
390 Arg = Arg.drop_front(FirstNonBackslash + 1);
401 if (argNeedsQuotes(Arg))
402 Command += quoteSingleArg(Arg);
406 Command.push_back(
' ');
410 if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16))
413 return std::wstring(CommandUtf16.begin(), CommandUtf16.end());
417 std::optional<unsigned> SecondsToWait,
419 std::optional<ProcessStatistics> *ProcStat,
421 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
422 assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
423 "invalid process handle to wait on, process not started?");
424 DWORD milliSecondsToWait = SecondsToWait ? *SecondsToWait * 1000 : INFINITE;
429 DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
430 if (WaitStatus == WAIT_TIMEOUT) {
431 if (!Polling && *SecondsToWait > 0) {
432 if (!TerminateProcess(PI.Process, 1)) {
434 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program");
437 WaitResult.ReturnCode = -2;
438 CloseHandle(PI.Process);
441 WaitForSingleObject(PI.Process, INFINITE);
442 CloseHandle(PI.Process);
451 FILETIME CreationTime, ExitTime, KernelTime, UserTime;
452 PROCESS_MEMORY_COUNTERS MemInfo;
453 if (GetProcessTimes(PI.Process, &CreationTime, &ExitTime, &KernelTime,
455 GetProcessMemoryInfo(PI.Process, &MemInfo,
sizeof(MemInfo))) {
456 auto UserT = std::chrono::duration_cast<std::chrono::microseconds>(
458 auto KernelT = std::chrono::duration_cast<std::chrono::microseconds>(
460 uint64_t PeakMemory = MemInfo.PeakPagefileUsage / 1024;
467 BOOL
rc = GetExitCodeProcess(PI.Process, &status);
468 DWORD err = GetLastError();
469 if (err != ERROR_INVALID_HANDLE)
470 CloseHandle(PI.Process);
475 MakeErrMsg(ErrMsg,
"Failed getting status for program");
478 WaitResult.ReturnCode = -2;
486 if ((status & 0xBFFF0000U) == 0x80000000U)
487 WaitResult.ReturnCode =
static_cast<int>(
status);
488 else if (status & 0xFF)
489 WaitResult.ReturnCode =
status & 0x7FFFFFFF;
491 WaitResult.ReturnCode = 1;
499 return std::error_code();
505 return std::error_code();
509 int result = _setmode(_fileno(stdin), _O_BINARY);
512 return std::error_code();
516 int result = _setmode(_fileno(stdout), _O_BINARY);
519 return std::error_code();
536 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
539 if ((EC = windows::UTF16ToCurCP(ArgsUTF16.data(), ArgsUTF16.size(),
543 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
547 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
553 memcpy(BOM, &src, 2);
555 OS.write((
char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
572 static const size_t MaxCommandStringLength = 32000;
575 FullArgs.append(
Args.begin(),
Args.end());
576 auto Result = flattenWindowsCommandLine(FullArgs);
578 return (
Result->size() + 1) <= MaxCommandStringLength;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE
static bool Execute(ProcessInfo &PI, StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env, ArrayRef< std::optional< StringRef > > Redirects, unsigned MemoryLimit, std::string *ErrMsg, BitVector *AffinityMask, bool DetachProcess)
static bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix, int errnum=-1)
This function builds an error message into ErrMsg using the prefix string and the Unix error number g...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Represents either an error or a value T.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
A raw_ostream that writes to a file descriptor.
A collection of legacy interfaces for querying information about the current executing process.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ OF_CRLF
The file should use a carriage linefeed '\r '.
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
LLVM_ABI std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
std::chrono::nanoseconds toDuration(FILETIME Time)
LLVM_ABI std::error_code ChangeStdinMode(fs::OpenFlags Flags)
LLVM_ABI std::error_code ChangeStdinToBinary()
LLVM_ABI bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
LLVM_ABI std::error_code writeFileWithEncoding(StringRef FileName, StringRef Contents, WindowsEncodingMethod Encoding=WEM_UTF8)
Saves the UTF8-encoded contents string into the file FileName using a specific encoding.
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems).
@ WEM_UTF8
UTF-8 is the LLVM native encoding, being the same as "do not performencoding conversion".
LLVM_ABI std::error_code ChangeStdoutToBinary()
LLVM_ABI ProcessInfo Wait(const ProcessInfo &PI, std::optional< unsigned > SecondsToWait, std::string *ErrMsg=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, bool Polling=false)
This function waits for the process specified by PI to finish.
This is an optimization pass for GlobalISel generic memory operations.
ScopedHandle< CommonHandleTraits > ScopedCommonHandle
std::error_code make_error_code(BitcodeError E)
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
ScopedHandle< JobHandleTraits > ScopedJobHandle
LLVM_ABI void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters,...
LLVM_ABI bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix)
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
LogicalResult success(bool IsSuccess=true)
Utility function to generate a LogicalResult.
This struct encapsulates information about a process.
This struct encapsulates information about a process execution.