38 ArrayRef<StringRef> Paths) {
39 assert(!Name.empty() &&
"Must have a name!");
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<wchar_t, MAX_PATH> U16Result;
72 for (StringRef
Ext : PathExts) {
73 SmallVector<wchar_t, MAX_PATH> U16Ext;
74 if (std::error_code EC = windows::UTF8ToUTF16(
Ext, U16Ext))
78 U16Result.reserve(Len);
82 SmallVector<wchar_t, MAX_PATH> U16NameExt;
83 if (std::error_code EC =
84 windows::UTF8ToUTF16(Twine(Name +
Ext).str(), U16NameExt))
87 Len = ::SearchPathW(Path,
c_str(U16NameExt),
nullptr,
88 U16Result.capacity(), U16Result.data(),
nullptr);
89 }
while (Len > U16Result.capacity());
98 U16Result.set_size(Len);
100 SmallVector<char, MAX_PATH> U8Result;
101 if (std::error_code EC =
102 windows::UTF16ToUTF8(U16Result.data(), U16Result.size(), U8Result))
105 return std::string(U8Result.begin(), U8Result.end());
108 static HANDLE RedirectIO(Optional<StringRef> Path,
int fd,
109 std::string *ErrMsg) {
112 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
113 GetCurrentProcess(), &h,
114 0, TRUE, DUPLICATE_SAME_ACCESS))
115 return INVALID_HANDLE_VALUE;
125 SECURITY_ATTRIBUTES sa;
126 sa.nLength =
sizeof(sa);
127 sa.lpSecurityDescriptor = 0;
128 sa.bInheritHandle = TRUE;
130 SmallVector<wchar_t, 128> fnameUnicode;
133 if (windows::UTF8ToUTF16(fname, fnameUnicode))
134 return INVALID_HANDLE_VALUE;
136 if (path::widenPath(fname, fnameUnicode))
137 return INVALID_HANDLE_VALUE;
139 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
140 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
141 FILE_ATTRIBUTE_NORMAL, NULL);
142 if (h == INVALID_HANDLE_VALUE) {
143 MakeErrMsg(ErrMsg, fname +
": Can't open file for " +
144 (fd ?
"input" :
"output"));
152 static bool Execute(ProcessInfo &PI, StringRef Program,
153 ArrayRef<StringRef>
Args,
Optional<ArrayRef<StringRef>> Env,
154 ArrayRef<Optional<StringRef>> Redirects,
155 unsigned MemoryLimit, std::string *ErrMsg) {
158 *ErrMsg =
"program not executable";
166 SmallString<64> ProgramStorage;
168 Program = Twine(Program +
".exe").toStringRef(ProgramStorage);
173 std::string Command = flattenWindowsCommandLine(Args);
176 std::vector<wchar_t> EnvBlock;
182 for (
const auto E : *Env) {
183 SmallVector<wchar_t, MAX_PATH> EnvString;
184 if (std::error_code ec = windows::UTF8ToUTF16(
E, EnvString)) {
185 SetLastError(ec.value());
186 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
190 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
191 EnvBlock.push_back(0);
193 EnvBlock.push_back(0);
198 memset(&si, 0,
sizeof(si));
200 si.hStdInput = INVALID_HANDLE_VALUE;
201 si.hStdOutput = INVALID_HANDLE_VALUE;
202 si.hStdError = INVALID_HANDLE_VALUE;
204 if (!Redirects.empty()) {
205 si.dwFlags = STARTF_USESTDHANDLES;
207 si.hStdInput = RedirectIO(Redirects[0], 0, ErrMsg);
208 if (si.hStdInput == INVALID_HANDLE_VALUE) {
212 si.hStdOutput = RedirectIO(Redirects[1], 1, ErrMsg);
213 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
214 CloseHandle(si.hStdInput);
218 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
221 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
222 GetCurrentProcess(), &si.hStdError,
223 0, TRUE, DUPLICATE_SAME_ACCESS)) {
224 CloseHandle(si.hStdInput);
225 CloseHandle(si.hStdOutput);
226 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
231 si.hStdError = RedirectIO(Redirects[2], 2, ErrMsg);
232 if (si.hStdError == INVALID_HANDLE_VALUE) {
233 CloseHandle(si.hStdInput);
234 CloseHandle(si.hStdOutput);
241 PROCESS_INFORMATION pi;
242 memset(&pi, 0,
sizeof(pi));
247 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
248 if (std::error_code ec = path::widenPath(Program, ProgramUtf16)) {
249 SetLastError(ec.value());
251 std::string(
"Unable to convert application name to UTF-16"));
255 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
256 if (std::error_code ec = windows::UTF8ToUTF16(Command, CommandUtf16)) {
257 SetLastError(ec.value());
259 std::string(
"Unable to convert command-line to UTF-16"));
263 BOOL
rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
264 TRUE, CREATE_UNICODE_ENVIRONMENT,
265 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
267 DWORD err = GetLastError();
271 CloseHandle(si.hStdInput);
272 CloseHandle(si.hStdOutput);
273 CloseHandle(si.hStdError);
278 MakeErrMsg(ErrMsg, std::string(
"Couldn't execute program '") +
279 Program.str() +
"'");
283 PI.Pid = pi.dwProcessId;
284 PI.Process = pi.hProcess;
291 if (MemoryLimit != 0) {
292 hJob = CreateJobObjectW(0, 0);
295 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
296 memset(&jeli, 0,
sizeof(jeli));
297 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
298 jeli.ProcessMemoryLimit = uintptr_t(MemoryLimit) * 1048576;
299 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
300 &jeli,
sizeof(jeli))) {
301 if (AssignProcessToJobObject(hJob, pi.hProcess))
306 SetLastError(GetLastError());
307 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
308 TerminateProcess(pi.hProcess, 1);
309 WaitForSingleObject(pi.hProcess, INFINITE);
317 static bool argNeedsQuotes(StringRef
Arg) {
323 static std::string quoteSingleArg(StringRef Arg) {
325 Result.push_back(
'"');
327 while (!Arg.empty()) {
328 size_t FirstNonBackslash = Arg.find_first_not_of(
'\\');
329 size_t BackslashCount = FirstNonBackslash;
333 BackslashCount = Arg.size();
334 Result.append(BackslashCount * 2,
'\\');
338 if (Arg[FirstNonBackslash] ==
'\"') {
341 Result.append(BackslashCount * 2 + 1,
'\\');
342 Result.push_back(
'\"');
347 Result.append(BackslashCount,
'\\');
348 Result.push_back(Arg[FirstNonBackslash]);
352 Arg = Arg.drop_front(FirstNonBackslash + 1);
355 Result.push_back(
'"');
360 std::string sys::flattenWindowsCommandLine(ArrayRef<StringRef> Args) {
362 for (StringRef Arg : Args) {
363 if (argNeedsQuotes(Arg))
364 Command += quoteSingleArg(Arg);
368 Command.push_back(
' ');
374 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
375 bool WaitUntilChildTerminates, std::string *ErrMsg) {
376 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
377 assert((PI.Process && PI.Process != INVALID_HANDLE_VALUE) &&
378 "invalid process handle to wait on, process not started?");
379 DWORD milliSecondsToWait = 0;
380 if (WaitUntilChildTerminates)
381 milliSecondsToWait = INFINITE;
382 else if (SecondsToWait > 0)
383 milliSecondsToWait = SecondsToWait * 1000;
385 ProcessInfo WaitResult = PI;
386 DWORD WaitStatus = WaitForSingleObject(PI.Process, milliSecondsToWait);
387 if (WaitStatus == WAIT_TIMEOUT) {
389 if (!TerminateProcess(PI.Process, 1)) {
391 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program");
394 WaitResult.ReturnCode = -2;
395 CloseHandle(PI.Process);
398 WaitForSingleObject(PI.Process, INFINITE);
399 CloseHandle(PI.Process);
402 return ProcessInfo();
408 BOOL rc = GetExitCodeProcess(PI.Process, &status);
409 DWORD err = GetLastError();
410 if (err != ERROR_INVALID_HANDLE)
411 CloseHandle(PI.Process);
416 MakeErrMsg(ErrMsg,
"Failed getting status for program");
419 WaitResult.ReturnCode = -2;
427 if ((status & 0xBFFF0000U) == 0x80000000U)
428 WaitResult.ReturnCode =
static_cast<int>(
status);
429 else if (status & 0xFF)
430 WaitResult.ReturnCode = status & 0x7FFFFFFF;
432 WaitResult.ReturnCode = 1;
438 int result = _setmode(_fileno(stdin), _O_BINARY);
440 return std::error_code(errno, std::generic_category());
441 return std::error_code();
445 int result = _setmode(_fileno(stdout), _O_BINARY);
447 return std::error_code(errno, std::generic_category());
448 return std::error_code();
462 SmallVector<wchar_t, 1> ArgsUTF16;
463 SmallVector<char, 1> ArgsCurCP;
465 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
468 if ((EC = windows::UTF16ToCurCP(
469 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
472 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
474 SmallVector<wchar_t, 1> ArgsUTF16;
476 if ((EC = windows::UTF8ToUTF16(Contents, ArgsUTF16)))
482 memcpy(BOM, &src, 2);
484 OS.write((
char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
496 ArrayRef<StringRef> Args) {
498 static const size_t MaxCommandStringLength = 32768;
499 SmallVector<StringRef, 8> FullArgs;
500 FullArgs.push_back(Program);
501 FullArgs.append(Args.begin(), Args.end());
502 std::string Result = flattenWindowsCommandLine(FullArgs);
503 return (Result.size() + 1) <= MaxCommandStringLength;
bool can_execute(const Twine &Path)
Can we execute this file?
Compute iterated dominance frontiers using a linear time algorithm.
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"...
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
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)
#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()
amdgpu Simplify well known AMD library false Value Value * Arg
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.