36 ArrayRef<StringRef> Paths) {
37 assert(!Name.empty() &&
"Must have a name!");
40 return std::string(Name);
42 const wchar_t *Path =
nullptr;
43 std::wstring PathStorage;
45 PathStorage.reserve(Paths.size() * MAX_PATH);
46 for (
unsigned i = 0; i < Paths.size(); ++i) {
48 PathStorage.push_back(
L';');
49 StringRef
P = Paths[i];
50 SmallVector<wchar_t, MAX_PATH> TmpPath;
53 PathStorage.append(TmpPath.begin(), TmpPath.end());
55 Path = PathStorage.c_str();
58 SmallVector<wchar_t, MAX_PATH> U16Name;
62 SmallVector<StringRef, 12> PathExts;
63 PathExts.push_back(
"");
64 PathExts.push_back(
".exe");
65 if (
const char *PathExtEnv = std::getenv(
"PATHEXT"))
68 SmallVector<wchar_t, MAX_PATH> U16Result;
70 for (StringRef
Ext : PathExts) {
71 SmallVector<wchar_t, MAX_PATH> U16Ext;
76 U16Result.reserve(Len);
80 SmallVector<wchar_t, MAX_PATH> U16NameExt;
81 if (std::error_code EC =
85 Len = ::SearchPathW(Path,
c_str(U16NameExt),
nullptr,
86 U16Result.capacity(), U16Result.data(),
nullptr);
87 }
while (Len > U16Result.capacity());
96 U16Result.set_size(Len);
98 SmallVector<char, MAX_PATH> U8Result;
99 if (std::error_code EC =
103 return std::string(U8Result.begin(), U8Result.end());
106 static HANDLE RedirectIO(
const StringRef *path,
int fd, std::string*
ErrMsg) {
109 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
110 GetCurrentProcess(), &h,
111 0, TRUE, DUPLICATE_SAME_ACCESS))
112 return INVALID_HANDLE_VALUE;
122 SECURITY_ATTRIBUTES sa;
123 sa.nLength =
sizeof(sa);
124 sa.lpSecurityDescriptor = 0;
125 sa.bInheritHandle = TRUE;
127 SmallVector<wchar_t, 128> fnameUnicode;
131 return INVALID_HANDLE_VALUE;
134 return INVALID_HANDLE_VALUE;
136 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
137 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
138 FILE_ATTRIBUTE_NORMAL, NULL);
139 if (h == INVALID_HANDLE_VALUE) {
140 MakeErrMsg(ErrMsg, fname +
": Can't open file for " +
141 (fd ?
"input" :
"output"));
149 static bool ArgNeedsQuotes(
const char *Str) {
150 return Str[0] ==
'\0' || strpbrk(Str,
"\t \"&\'()*<>\\`^|") != 0;
155 static unsigned int CountPrecedingBackslashes(
const char *Start,
157 unsigned int Count = 0;
159 while (Cur >= Start && *Cur ==
'\\') {
168 static char *EscapePrecedingEscapes(
char *Dst,
const char *Start,
170 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
171 while (PrecedingEscapes > 0) {
180 static unsigned int ArgLenWithQuotes(
const char *Str) {
181 const char *Start = Str;
182 bool Quoted = ArgNeedsQuotes(Str);
183 unsigned int len = Quoted ? 2 : 0;
185 while (*Str !=
'\0') {
188 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
189 len += PrecedingEscapes + 1;
201 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
202 len += PrecedingEscapes + 1;
210 static std::unique_ptr<char[]> flattenArgs(
const char **args) {
213 for (
unsigned i = 0; args[i]; i++) {
214 len += ArgLenWithQuotes(args[i]) + 1;
218 std::unique_ptr<char[]> command(
new char[len+1]);
219 char *p = command.get();
221 for (
unsigned i = 0; args[i]; i++) {
222 const char *arg = args[i];
223 const char *start = arg;
225 bool needsQuoting = ArgNeedsQuotes(arg);
229 while (*arg !=
'\0') {
232 p = EscapePrecedingEscapes(p, start, arg);
241 p = EscapePrecedingEscapes(p, start, arg);
251 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
252 const char **envp,
const StringRef **redirects,
253 unsigned memoryLimit, std::string *ErrMsg) {
256 *ErrMsg =
"program not executable";
264 SmallString<64> ProgramStorage;
266 Program = Twine(Program +
".exe").toStringRef(ProgramStorage);
271 std::unique_ptr<char[]> command = flattenArgs(args);
274 std::vector<wchar_t> EnvBlock;
280 for (
unsigned i = 0; envp[i]; ++i) {
281 SmallVector<wchar_t, MAX_PATH> EnvString;
283 SetLastError(ec.value());
284 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
288 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
289 EnvBlock.push_back(0);
291 EnvBlock.push_back(0);
296 memset(&si, 0,
sizeof(si));
298 si.hStdInput = INVALID_HANDLE_VALUE;
299 si.hStdOutput = INVALID_HANDLE_VALUE;
300 si.hStdError = INVALID_HANDLE_VALUE;
303 si.dwFlags = STARTF_USESTDHANDLES;
305 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
306 if (si.hStdInput == INVALID_HANDLE_VALUE) {
310 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
311 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
312 CloseHandle(si.hStdInput);
316 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
319 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
320 GetCurrentProcess(), &si.hStdError,
321 0, TRUE, DUPLICATE_SAME_ACCESS)) {
322 CloseHandle(si.hStdInput);
323 CloseHandle(si.hStdOutput);
324 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
329 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
330 if (si.hStdError == INVALID_HANDLE_VALUE) {
331 CloseHandle(si.hStdInput);
332 CloseHandle(si.hStdOutput);
339 PROCESS_INFORMATION pi;
340 memset(&pi, 0,
sizeof(pi));
345 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
347 SetLastError(ec.value());
349 std::string(
"Unable to convert application name to UTF-16"));
353 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
355 SetLastError(ec.value());
357 std::string(
"Unable to convert command-line to UTF-16"));
361 BOOL
rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
362 TRUE, CREATE_UNICODE_ENVIRONMENT,
363 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
365 DWORD err = GetLastError();
369 CloseHandle(si.hStdInput);
370 CloseHandle(si.hStdOutput);
371 CloseHandle(si.hStdError);
376 MakeErrMsg(ErrMsg, std::string(
"Couldn't execute program '") +
377 Program.str() +
"'");
381 PI.Pid = pi.dwProcessId;
382 PI.ProcessHandle = pi.hProcess;
389 if (memoryLimit != 0) {
390 hJob = CreateJobObjectW(0, 0);
393 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
394 memset(&jeli, 0,
sizeof(jeli));
395 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
396 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
397 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
398 &jeli,
sizeof(jeli))) {
399 if (AssignProcessToJobObject(hJob, pi.hProcess))
404 SetLastError(GetLastError());
405 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
406 TerminateProcess(pi.hProcess, 1);
407 WaitForSingleObject(pi.hProcess, INFINITE);
416 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
417 bool WaitUntilChildTerminates, std::string *ErrMsg) {
418 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
419 assert(PI.ProcessHandle &&
420 "invalid process handle to wait on, process not started?");
421 DWORD milliSecondsToWait = 0;
422 if (WaitUntilChildTerminates)
423 milliSecondsToWait = INFINITE;
424 else if (SecondsToWait > 0)
425 milliSecondsToWait = SecondsToWait * 1000;
427 ProcessInfo WaitResult = PI;
428 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
429 if (WaitStatus == WAIT_TIMEOUT) {
431 if (!TerminateProcess(PI.ProcessHandle, 1)) {
433 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program");
436 WaitResult.ReturnCode = -2;
437 CloseHandle(PI.ProcessHandle);
440 WaitForSingleObject(PI.ProcessHandle, INFINITE);
441 CloseHandle(PI.ProcessHandle);
444 return ProcessInfo();
450 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
451 DWORD err = GetLastError();
452 if (err != ERROR_INVALID_HANDLE)
453 CloseHandle(PI.ProcessHandle);
458 MakeErrMsg(ErrMsg,
"Failed getting status for program");
461 WaitResult.ReturnCode = -2;
469 if ((status & 0xBFFF0000U) == 0x80000000U)
470 WaitResult.ReturnCode =
static_cast<int>(
status);
471 else if (status & 0xFF)
472 WaitResult.ReturnCode = status & 0x7FFFFFFF;
474 WaitResult.ReturnCode = 1;
480 int result = _setmode(_fileno(stdin), _O_BINARY);
482 return std::error_code(errno, std::generic_category());
483 return std::error_code();
487 int result = _setmode(_fileno(stdout), _O_BINARY);
489 return std::error_code(errno, std::generic_category());
490 return std::error_code();
504 SmallVector<wchar_t, 1> ArgsUTF16;
505 SmallVector<char, 1> ArgsCurCP;
511 ArgsUTF16.data(), ArgsUTF16.size(), ArgsCurCP)))
514 OS.write(ArgsCurCP.data(), ArgsCurCP.size());
516 SmallVector<wchar_t, 1> ArgsUTF16;
524 memcpy(BOM, &src, 2);
526 OS.write((
char *)ArgsUTF16.data(), ArgsUTF16.size() << 1);
539 static const size_t MaxCommandStringLength = 32768;
542 size_t ArgLength = ArgLenWithQuotes(Program.str().c_str()) + 2;
543 for (ArrayRef<const char*>::iterator
I = Args.begin(),
E = Args.end();
546 ArgLength += ArgLenWithQuotes(*
I) + 1;
547 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
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
std::error_code mapWindowsError(unsigned EV)
std::error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl< wchar_t > &utf16)
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.
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()
success
Parameters (see the expansion example below): (the builder, addr, loaded, new_val, ordering, /* OUT.
llvm_unreachable("Unknown RegBank!")
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.
bool exists(file_status status)
Does file exist?
std::error_code widenPath(const Twine &Path8, SmallVectorImpl< wchar_t > &Path16)