37 ArrayRef<StringRef> Paths) {
38 assert(!Name.empty() &&
"Must have a name!");
41 return std::string(Name);
43 const wchar_t *Path =
nullptr;
44 std::wstring PathStorage;
46 PathStorage.reserve(Paths.size() * MAX_PATH);
47 for (
unsigned i = 0; i < Paths.size(); ++i) {
49 PathStorage.push_back(L
';');
50 StringRef
P = Paths[i];
51 SmallVector<wchar_t, MAX_PATH> TmpPath;
52 if (std::error_code EC = windows::UTF8ToUTF16(P, TmpPath))
54 PathStorage.append(TmpPath.begin(), TmpPath.end());
56 Path = PathStorage.c_str();
59 SmallVector<wchar_t, MAX_PATH> U16Name;
60 if (std::error_code EC = windows::UTF8ToUTF16(Name, U16Name))
63 SmallVector<StringRef, 12> PathExts;
64 PathExts.push_back(
"");
65 PathExts.push_back(
".exe");
66 if (
const char *PathExtEnv = std::getenv(
"PATHEXT"))
69 SmallVector<wchar_t, MAX_PATH> U16Result;
71 for (StringRef
Ext : PathExts) {
72 SmallVector<wchar_t, MAX_PATH> U16Ext;
73 if (std::error_code EC = windows::UTF8ToUTF16(
Ext, U16Ext))
77 U16Result.reserve(Len);
81 SmallVector<wchar_t, MAX_PATH> U16NameExt;
82 if (std::error_code EC =
83 windows::UTF8ToUTF16(Twine(Name +
Ext).str(), U16NameExt))
86 Len = ::SearchPathW(Path,
c_str(U16NameExt),
nullptr,
87 U16Result.capacity(), U16Result.data(),
nullptr);
88 }
while (Len > U16Result.capacity());
97 U16Result.set_size(Len);
99 SmallVector<char, MAX_PATH> U8Result;
100 if (std::error_code EC =
101 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
104 return std::string(U8Result.begin(), U8Result.end());
107 bool MakeErrMsg(std::string *ErrMsg,
const std::string &prefix) {
111 DWORD LastError = GetLastError();
112 DWORD R = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
113 FORMAT_MESSAGE_FROM_SYSTEM |
114 FORMAT_MESSAGE_MAX_WIDTH_MASK,
115 NULL, LastError, 0, (LPSTR)&buffer, 1, NULL);
117 *ErrMsg = prefix +
": " + buffer;
119 *ErrMsg = prefix +
": Unknown error";
126 static HANDLE RedirectIO(Optional<StringRef> Path,
int fd,
127 std::string *ErrMsg) {
130 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
131 GetCurrentProcess(), &h,
132 0, TRUE, DUPLICATE_SAME_ACCESS))
133 return INVALID_HANDLE_VALUE;
143 SECURITY_ATTRIBUTES sa;
144 sa.nLength =
sizeof(sa);
145 sa.lpSecurityDescriptor = 0;
146 sa.bInheritHandle = TRUE;
148 SmallVector<wchar_t, 128> fnameUnicode;
151 if (windows::UTF8ToUTF16(fname, fnameUnicode))
152 return INVALID_HANDLE_VALUE;
154 if (path::widenPath(fname, fnameUnicode))
155 return INVALID_HANDLE_VALUE;
157 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
158 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
159 FILE_ATTRIBUTE_NORMAL, NULL);
160 if (h == INVALID_HANDLE_VALUE) {
161 MakeErrMsg(ErrMsg, fname +
": Can't open file for " +
162 (fd ?
"input" :
"output"));
170 static bool Execute(ProcessInfo &PI, StringRef Program,
171 ArrayRef<StringRef>
Args,
Optional<ArrayRef<StringRef>> Env,
172 ArrayRef<Optional<StringRef>> Redirects,
173 unsigned MemoryLimit, std::string *ErrMsg) {
176 *ErrMsg =
"program not executable";
184 SmallString<64> ProgramStorage;
186 Program = Twine(Program +
".exe").toStringRef(ProgramStorage);
191 std::string Command = flattenWindowsCommandLine(Args);
194 std::vector<wchar_t> EnvBlock;
200 for (StringRef
E : *Env) {
201 SmallVector<wchar_t, MAX_PATH> EnvString;
202 if (std::error_code ec = windows::UTF8ToUTF16(
E, EnvString)) {
203 SetLastError(ec.value());
204 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
208 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
209 EnvBlock.push_back(0);
211 EnvBlock.push_back(0);
216 memset(&si, 0,
sizeof(si));
218 si.hStdInput = INVALID_HANDLE_VALUE;
219 si.hStdOutput = INVALID_HANDLE_VALUE;
220 si.hStdError = INVALID_HANDLE_VALUE;
222 if (!Redirects.empty()) {
223 si.dwFlags = STARTF_USESTDHANDLES;
225 si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
226 if (si.hStdInput == INVALID_HANDLE_VALUE) {
230 si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
231 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
232 CloseHandle(si.hStdInput);
236 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
239 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
240 GetCurrentProcess(), &si.hStdError,
241 0, TRUE, DUPLICATE_SAME_ACCESS)) {
242 CloseHandle(si.hStdInput);
243 CloseHandle(si.hStdOutput);
244 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
249 si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
250 if (si.hStdError == INVALID_HANDLE_VALUE) {
251 CloseHandle(si.hStdInput);
252 CloseHandle(si.hStdOutput);
259 PROCESS_INFORMATION
pi;
260 memset(&pi, 0,
sizeof(pi));
265 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
266 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
267 SetLastError(ec.value());
269 std::string(
"Unable to convert application name to UTF-16"));
273 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
274 if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
275 SetLastError(ec.value());
277 std::string(
"Unable to convert command-line to UTF-16"));
281 BOOL
rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
282 TRUE, CREATE_UNICODE_ENVIRONMENT,
283 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
285 DWORD err = GetLastError();
289 CloseHandle(si.hStdInput);
290 CloseHandle(si.hStdOutput);
291 CloseHandle(si.hStdError);
296 MakeErrMsg(ErrMsg, std::string(
"Couldn't execute program '") +
297 Program.str() +
"'");
301 PI.Pid = pi.dwProcessId;
302 PI.Process = pi.hProcess;
309 if (MemoryLimit != 0) {
310 hJob = CreateJobObjectW(0, 0);
313 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
314 memset(&jeli, 0,
sizeof(jeli));
315 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
316 jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
317 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
318 &jeli,
sizeof(jeli))) {
319 if (AssignProcessToJobObject(hJob, pi.hProcess))
324 SetLastError(GetLastError());
325 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
326 TerminateProcess(pi.hProcess, 1);
327 WaitForSingleObject(pi.hProcess, INFINITE);
335 static bool argNeedsQuotes(StringRef
Arg) {
341 static std::string quoteSingleArg(StringRef Arg) {
343 Result.push_back(
'"');
345 while (!Arg.empty()) {
346 size_t FirstNonBackslash = Arg.find_first_not_of(
'\\');
347 size_t BackslashCount = FirstNonBackslash;
351 BackslashCount = Arg.size();
352 Result.append(BackslashCount * 2,
'\\');
356 if (Arg[FirstNonBackslash] ==
'\"') {
359 Result.append(BackslashCount * 2 + 1,
'\\');
360 Result.push_back(
'\"');
365 Result.append(BackslashCount,
'\\');
366 Result.push_back(Arg[FirstNonBackslash]);
370 Arg = Arg.drop_front(FirstNonBackslash + 1);
373 Result.push_back(
'"');
378 std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
380 for (StringRef Arg : Args) {
381 if (argNeedsQuotes(Arg))
382 Command += quoteSingleArg(Arg);
386 Command.push_back(
' ');
392 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
393 bool WaitUntilChildTerminates, std::string *ErrMsg) {
394 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
395 assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
396 "invalid process handle to wait on, process not started?");
397 DWORD milliSecondsToWait = 0;
398 if (WaitUntilChildTerminates)
399 milliSecondsToWait = INFINITE;
400 else if (SecondsToWait > 0)
401 milliSecondsToWait = SecondsToWait * 1000;
403 ProcessInfo WaitResult = PI;
404 DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
405 if (WaitStatus == WAIT_TIMEOUT) {
407 if (!TerminateProcess(PI.Process, 1)) {
409 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program");
412 WaitResult.ReturnCode = -2;
413 CloseHandle(PI.Process);
416 WaitForSingleObject(PI.Process, INFINITE);
417 CloseHandle(PI.Process);
420 return ProcessInfo();
426 BOOL rc = GetExitCodeProcess(PI.Process, &status);
427 DWORD err = GetLastError();
428 if (err != ERROR_INVALID_HANDLE)
429 CloseHandle(PI.Process);
434 MakeErrMsg(ErrMsg,
"Failed getting status for program");
437 WaitResult.ReturnCode = -2;
445 if ((status & 0xBFFF0000U) == 0x80000000U)
446 WaitResult.ReturnCode =
static_cast<int>(
status);
447 else if (status & 0xFF)
448 WaitResult.ReturnCode = status & 0x7FFFFFFF;
450 WaitResult.ReturnCode = 1;
456 int result = _setmode(_fileno(stdin), _O_BINARY);
458 return std::error_code(errno, std::generic_category());
459 return std::error_code();
463 int result = _setmode(_fileno(stdout), _O_BINARY);
465 return std::error_code(errno, std::generic_category());
466 return std::error_code();
480 SmallVector<wchar_t, 1> ArgsUTF16;
481 SmallVector<char, 1> ArgsCurCP;
483 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
486 if ((EC = windows::UTF16ToCurCP(
487 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
490 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
492 SmallVector<wchar_t, 1> ArgsUTF16;
494 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
500 memcpy(BOM, &src, 2);
502 OS.write((
char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
514 ArrayRef<StringRef> Args) {
516 static const size_t MaxCommandStringLength = 32768;
517 SmallVector<StringRef, 8> FullArgs;
518 FullArgs.push_back(Program);
519 FullArgs.append(Args.begin(), Args.end());
520 std::string Result = flattenWindowsCommandLine(FullArgs);
521 return (Result.size() + 1) <= MaxCommandStringLength;
ScopedHandle< JobHandleTraits > ScopedJobHandle
bool can_execute(const Twine &Path)
Can we execute this file?
This class represents lattice values for constants.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
std::error_code ChangeStdoutToBinary()
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
UTF-8 is the LLVM native encoding, being the same as "do not perform encoding conversion"...
ScopedHandle< CommonHandleTraits > ScopedCommonHandle
std::error_code make_error_code(BitcodeError E)
void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \\\)
SplitString - Split up the specified string according to the specified delimiters, appending the result fragments to the output list.
#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE
The file should be opened in text mode on platforms that make this distinction.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
std::error_code mapWindowsError(unsigned EV)
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
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.
bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix)
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems)...
std::error_code ChangeStdinToBinary()
success
Parameters (see the expansion example below): (the builder, addr, loaded, new_val, ordering, /* OUT.
A raw_ostream that writes to a file descriptor.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=nullptr)
This function waits for the process specified by PI to finish.
bool exists(const basic_file_status &status)
Does file exist?
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
std::string utohexstr(uint64_t X, bool LowerCase=false)