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;
54 PathStorage.append(TmpPath.begin(), TmpPath.end());
56 Path = PathStorage.c_str();
59 SmallVector<wchar_t, MAX_PATH> 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;
77 U16Result.reserve(Len);
81 SmallVector<wchar_t, MAX_PATH> U16NameExt;
82 if (std::error_code EC =
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 =
104 return std::string(U8Result.begin(), U8Result.end());
107 static HANDLE RedirectIO(
const StringRef *path,
int fd, std::string* ErrMsg) {
110 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
111 GetCurrentProcess(), &h,
112 0, TRUE, DUPLICATE_SAME_ACCESS))
113 return INVALID_HANDLE_VALUE;
123 SECURITY_ATTRIBUTES sa;
124 sa.nLength =
sizeof(sa);
125 sa.lpSecurityDescriptor = 0;
126 sa.bInheritHandle = TRUE;
128 SmallVector<wchar_t, 128> fnameUnicode;
132 return INVALID_HANDLE_VALUE;
135 return INVALID_HANDLE_VALUE;
137 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
138 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
139 FILE_ATTRIBUTE_NORMAL, NULL);
140 if (h == INVALID_HANDLE_VALUE) {
141 MakeErrMsg(ErrMsg, fname +
": Can't open file for " +
142 (fd ?
"input" :
"output"));
150 static bool ArgNeedsQuotes(
const char *Str) {
151 return Str[0] ==
'\0' || strpbrk(Str,
"\t \"&\'()*<>\\`^|") != 0;
156 static unsigned int CountPrecedingBackslashes(
const char *Start,
158 unsigned int Count = 0;
160 while (Cur >= Start && *Cur ==
'\\') {
169 static char *EscapePrecedingEscapes(
char *Dst,
const char *Start,
171 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
172 while (PrecedingEscapes > 0) {
181 static unsigned int ArgLenWithQuotes(
const char *Str) {
182 const char *Start = Str;
183 bool Quoted = ArgNeedsQuotes(Str);
184 unsigned int len = Quoted ? 2 : 0;
186 while (*Str !=
'\0') {
189 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
190 len += PrecedingEscapes + 1;
202 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
203 len += PrecedingEscapes + 1;
211 static std::unique_ptr<char[]> flattenArgs(
const char **args) {
214 for (
unsigned i = 0; args[
i];
i++) {
215 len += ArgLenWithQuotes(args[
i]) + 1;
219 std::unique_ptr<char[]> command(
new char[len+1]);
220 char *p = command.get();
222 for (
unsigned i = 0; args[
i];
i++) {
223 const char *arg = args[
i];
224 const char *start = arg;
226 bool needsQuoting = ArgNeedsQuotes(arg);
230 while (*arg !=
'\0') {
233 p = EscapePrecedingEscapes(p, start, arg);
242 p = EscapePrecedingEscapes(p, start, arg);
252 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
253 const char **envp,
const StringRef **redirects,
254 unsigned memoryLimit, std::string *ErrMsg) {
257 *ErrMsg =
"program not executable";
265 SmallString<64> ProgramStorage;
267 Program = Twine(Program +
".exe").toStringRef(ProgramStorage);
272 std::unique_ptr<char[]> command = flattenArgs(args);
275 std::vector<wchar_t> EnvBlock;
281 for (
unsigned i = 0; envp[
i]; ++
i) {
282 SmallVector<wchar_t, MAX_PATH> EnvString;
284 SetLastError(ec.value());
285 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
289 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
290 EnvBlock.push_back(0);
292 EnvBlock.push_back(0);
297 memset(&si, 0,
sizeof(si));
299 si.hStdInput = INVALID_HANDLE_VALUE;
300 si.hStdOutput = INVALID_HANDLE_VALUE;
301 si.hStdError = INVALID_HANDLE_VALUE;
304 si.dwFlags = STARTF_USESTDHANDLES;
306 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
307 if (si.hStdInput == INVALID_HANDLE_VALUE) {
311 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
312 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
313 CloseHandle(si.hStdInput);
317 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
320 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
321 GetCurrentProcess(), &si.hStdError,
322 0, TRUE, DUPLICATE_SAME_ACCESS)) {
323 CloseHandle(si.hStdInput);
324 CloseHandle(si.hStdOutput);
325 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
330 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
331 if (si.hStdError == INVALID_HANDLE_VALUE) {
332 CloseHandle(si.hStdInput);
333 CloseHandle(si.hStdOutput);
340 PROCESS_INFORMATION pi;
341 memset(&pi, 0,
sizeof(pi));
346 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
348 SetLastError(ec.value());
350 std::string(
"Unable to convert application name to UTF-16"));
354 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
356 SetLastError(ec.value());
358 std::string(
"Unable to convert command-line to UTF-16"));
362 BOOL
rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
363 TRUE, CREATE_UNICODE_ENVIRONMENT,
364 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
366 DWORD err = GetLastError();
370 CloseHandle(si.hStdInput);
371 CloseHandle(si.hStdOutput);
372 CloseHandle(si.hStdError);
377 MakeErrMsg(ErrMsg, std::string(
"Couldn't execute program '") +
378 Program.str() +
"'");
382 PI.Pid = pi.dwProcessId;
383 PI.ProcessHandle = pi.hProcess;
390 if (memoryLimit != 0) {
391 hJob = CreateJobObjectW(0, 0);
394 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
395 memset(&jeli, 0,
sizeof(jeli));
396 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
397 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
398 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
399 &jeli,
sizeof(jeli))) {
400 if (AssignProcessToJobObject(hJob, pi.hProcess))
405 SetLastError(GetLastError());
406 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
407 TerminateProcess(pi.hProcess, 1);
408 WaitForSingleObject(pi.hProcess, INFINITE);
417 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
418 bool WaitUntilChildTerminates, std::string *ErrMsg) {
419 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
420 assert(PI.ProcessHandle &&
421 "invalid process handle to wait on, process not started?");
422 DWORD milliSecondsToWait = 0;
423 if (WaitUntilChildTerminates)
424 milliSecondsToWait = INFINITE;
425 else if (SecondsToWait > 0)
426 milliSecondsToWait = SecondsToWait * 1000;
428 ProcessInfo WaitResult = PI;
429 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
430 if (WaitStatus == WAIT_TIMEOUT) {
432 if (!TerminateProcess(PI.ProcessHandle, 1)) {
434 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program");
437 WaitResult.ReturnCode = -2;
438 CloseHandle(PI.ProcessHandle);
441 WaitForSingleObject(PI.ProcessHandle, INFINITE);
442 CloseHandle(PI.ProcessHandle);
445 return ProcessInfo();
451 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
452 DWORD err = GetLastError();
453 if (err != ERROR_INVALID_HANDLE)
454 CloseHandle(PI.ProcessHandle);
459 MakeErrMsg(ErrMsg,
"Failed getting status for program");
462 WaitResult.ReturnCode = -2;
470 if ((status & 0xBFFF0000U) == 0x80000000U)
471 WaitResult.ReturnCode =
static_cast<int>(
status);
472 else if (status & 0xFF)
473 WaitResult.ReturnCode = status & 0x7FFFFFFF;
475 WaitResult.ReturnCode = 1;
481 int result = _setmode(_fileno(stdin), _O_BINARY);
483 return std::error_code(errno, std::generic_category());
484 return std::error_code();
488 int result = _setmode(_fileno(stdout), _O_BINARY);
490 return std::error_code(errno, std::generic_category());
491 return std::error_code();
505 SmallVector<wchar_t, 1> ArgsUTF16;
506 SmallVector<char, 1> ArgsCurCP;
512 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
515 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
517 SmallVector<wchar_t, 1> ArgsUTF16;
525 memcpy(BOM, &src, 2);
527 OS.write((
char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
540 static const size_t MaxCommandStringLength = 32768;
543 size_t ArgLength = ArgLenWithQuotes(Program.str().c_str()) + 2;
544 for (ArrayRef<const char*>::iterator
I = Args.begin(),
E = Args.end();
547 ArgLength += ArgLenWithQuotes(*
I) + 1;
548 if (ArgLength > MaxCommandStringLength) {
bool can_execute(const Twine &Path)
Can we execute this file?
std::error_code ChangeStdoutToBinary()
UTF-8 is the LLVM native encoding, being the same as "do not perform encoding conversion"...
std::error_code make_error_code(BitcodeError E)
#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
std::error_code mapWindowsError(unsigned EV)
std::error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl< wchar_t > &utf16)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len, SmallVectorImpl< char > &utf8)
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, appending the result fragments to the output list.
static bool Execute(ProcessInfo &PI, StringRef Program, const char **args, const char **env, const StringRef **Redirects, unsigned memoryLimit, std::string *ErrMsg)
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< const char * > Args)
Return true if the given arguments fit within system-specific argument length limits.
std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len, SmallVectorImpl< char > &utf8)
Convert from UTF16 to the current code page used in the system.
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)...
The file should be opened in text mode on platforms that make this distinction.
std::error_code ChangeStdinToBinary()
A raw_ostream that writes to a file descriptor.
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths=None)
Find the first executable file Name in Paths.
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.
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
bool exists(file_status status)
Does file exist?
std::error_code widenPath(const Twine &Path8, SmallVectorImpl< wchar_t > &Path16)