35 if (progName.length() == 0)
37 std::string temp = progName;
39 if (progName.find(
'\\') != std::string::npos ||
40 progName.find(
'/') != std::string::npos)
45 SmallVector<wchar_t, MAX_PATH> progNameUnicode;
49 SmallVector<wchar_t, MAX_PATH> buffer;
53 len = ::SearchPathW(NULL, progNameUnicode.data(), L
".exe",
54 buffer.capacity(), buffer.data(), NULL);
61 }
while (len > buffer.capacity());
64 SmallVector<char, MAX_PATH> result;
68 return std::string(result.data(), result.size());
71 static HANDLE RedirectIO(
const StringRef *path,
int fd, std::string* ErrMsg) {
74 if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
75 GetCurrentProcess(), &h,
76 0,
TRUE, DUPLICATE_SAME_ACCESS))
77 return INVALID_HANDLE_VALUE;
87 SECURITY_ATTRIBUTES sa;
88 sa.nLength =
sizeof(sa);
89 sa.lpSecurityDescriptor = 0;
90 sa.bInheritHandle =
TRUE;
92 SmallVector<wchar_t, 128> fnameUnicode;
94 return INVALID_HANDLE_VALUE;
96 h = CreateFileW(fnameUnicode.data(), fd ? GENERIC_WRITE : GENERIC_READ,
97 FILE_SHARE_READ, &sa, fd == 0 ? OPEN_EXISTING : CREATE_ALWAYS,
98 FILE_ATTRIBUTE_NORMAL, NULL);
99 if (h == INVALID_HANDLE_VALUE) {
100 MakeErrMsg(ErrMsg, std::string(fname) +
": Can't open file for " +
101 (fd ?
"input: " :
"output: "));
109 static bool ArgNeedsQuotes(
const char *Str) {
110 return Str[0] ==
'\0' ||
strpbrk(Str,
"\t \"&\'()*<>\\`^|") != 0;
115 static unsigned int CountPrecedingBackslashes(
const char *Start,
117 unsigned int Count = 0;
119 while (Cur >= Start && *Cur ==
'\\') {
128 static char *EscapePrecedingEscapes(
char *Dst,
const char *Start,
130 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Cur);
131 while (PrecedingEscapes > 0) {
140 static unsigned int ArgLenWithQuotes(
const char *Str) {
141 const char *Start = Str;
142 bool Quoted = ArgNeedsQuotes(Str);
143 unsigned int len = Quoted ? 2 : 0;
145 while (*Str !=
'\0') {
148 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
149 len += PrecedingEscapes + 1;
161 unsigned PrecedingEscapes = CountPrecedingBackslashes(Start, Str);
162 len += PrecedingEscapes + 1;
170 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
171 const char **envp,
const StringRef **redirects,
172 unsigned memoryLimit, std::string *ErrMsg) {
175 *ErrMsg =
"program not executable";
185 for (
unsigned i = 0; args[i]; i++) {
186 len += ArgLenWithQuotes(args[i]) + 1;
190 OwningArrayPtr<char> command(
new char[len+1]);
191 char *p = command.get();
193 for (
unsigned i = 0; args[i]; i++) {
194 const char *arg = args[i];
195 const char *start = arg;
197 bool needsQuoting = ArgNeedsQuotes(arg);
201 while (*arg !=
'\0') {
204 p = EscapePrecedingEscapes(p, start, arg);
213 p = EscapePrecedingEscapes(p, start, arg);
222 std::vector<wchar_t> EnvBlock;
228 for (
unsigned i = 0; envp[i]; ++i) {
229 SmallVector<wchar_t, MAX_PATH> EnvString;
231 SetLastError(ec.value());
232 MakeErrMsg(ErrMsg,
"Unable to convert environment variable to UTF-16");
236 EnvBlock.insert(EnvBlock.end(), EnvString.begin(), EnvString.end());
237 EnvBlock.push_back(0);
239 EnvBlock.push_back(0);
244 memset(&si, 0,
sizeof(si));
246 si.hStdInput = INVALID_HANDLE_VALUE;
247 si.hStdOutput = INVALID_HANDLE_VALUE;
248 si.hStdError = INVALID_HANDLE_VALUE;
251 si.dwFlags = STARTF_USESTDHANDLES;
253 si.hStdInput = RedirectIO(redirects[0], 0, ErrMsg);
254 if (si.hStdInput == INVALID_HANDLE_VALUE) {
258 si.hStdOutput = RedirectIO(redirects[1], 1, ErrMsg);
259 if (si.hStdOutput == INVALID_HANDLE_VALUE) {
260 CloseHandle(si.hStdInput);
264 if (redirects[1] && redirects[2] && *(redirects[1]) == *(redirects[2])) {
267 if (!DuplicateHandle(GetCurrentProcess(), si.hStdOutput,
268 GetCurrentProcess(), &si.hStdError,
269 0,
TRUE, DUPLICATE_SAME_ACCESS)) {
270 CloseHandle(si.hStdInput);
271 CloseHandle(si.hStdOutput);
272 MakeErrMsg(ErrMsg,
"can't dup stderr to stdout");
277 si.hStdError = RedirectIO(redirects[2], 2, ErrMsg);
278 if (si.hStdError == INVALID_HANDLE_VALUE) {
279 CloseHandle(si.hStdInput);
280 CloseHandle(si.hStdOutput);
287 PROCESS_INFORMATION pi;
288 memset(&pi, 0,
sizeof(pi));
293 SmallVector<wchar_t, MAX_PATH> ProgramUtf16;
295 SetLastError(ec.value());
297 std::string(
"Unable to convert application name to UTF-16"));
301 SmallVector<wchar_t, MAX_PATH> CommandUtf16;
303 SetLastError(ec.value());
305 std::string(
"Unable to convert command-line to UTF-16"));
309 BOOL rc = CreateProcessW(ProgramUtf16.data(), CommandUtf16.data(), 0, 0,
310 TRUE, CREATE_UNICODE_ENVIRONMENT,
311 EnvBlock.empty() ? 0 : EnvBlock.data(), 0, &si,
313 DWORD err = GetLastError();
317 CloseHandle(si.hStdInput);
318 CloseHandle(si.hStdOutput);
319 CloseHandle(si.hStdError);
324 MakeErrMsg(ErrMsg, std::string(
"Couldn't execute program '") +
325 Program.str() +
"'");
329 PI.Pid = pi.dwProcessId;
330 PI.ProcessHandle = pi.hProcess;
337 if (memoryLimit != 0) {
338 hJob = CreateJobObjectW(0, 0);
339 bool success =
false;
341 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli;
342 memset(&jeli, 0,
sizeof(jeli));
343 jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
344 jeli.ProcessMemoryLimit = uintptr_t(memoryLimit) * 1048576;
345 if (SetInformationJobObject(hJob, JobObjectExtendedLimitInformation,
346 &jeli,
sizeof(jeli))) {
347 if (AssignProcessToJobObject(hJob, pi.hProcess))
352 SetLastError(GetLastError());
353 MakeErrMsg(ErrMsg, std::string(
"Unable to set memory limit"));
354 TerminateProcess(pi.hProcess, 1);
355 WaitForSingleObject(pi.hProcess, INFINITE);
364 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
365 bool WaitUntilChildTerminates, std::string *ErrMsg) {
366 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
367 assert(PI.ProcessHandle &&
368 "invalid process handle to wait on, process not started?");
369 DWORD milliSecondsToWait = 0;
370 if (WaitUntilChildTerminates)
371 milliSecondsToWait = INFINITE;
372 else if (SecondsToWait > 0)
373 milliSecondsToWait = SecondsToWait * 1000;
375 ProcessInfo WaitResult = PI;
376 DWORD WaitStatus = WaitForSingleObject(PI.ProcessHandle, milliSecondsToWait);
377 if (WaitStatus == WAIT_TIMEOUT) {
379 if (!TerminateProcess(PI.ProcessHandle, 1)) {
381 MakeErrMsg(ErrMsg,
"Failed to terminate timed-out program.");
384 WaitResult.ReturnCode = -2;
385 CloseHandle(PI.ProcessHandle);
388 WaitForSingleObject(PI.ProcessHandle, INFINITE);
389 CloseHandle(PI.ProcessHandle);
392 return ProcessInfo();
398 BOOL rc = GetExitCodeProcess(PI.ProcessHandle, &status);
399 DWORD err = GetLastError();
400 CloseHandle(PI.ProcessHandle);
405 MakeErrMsg(ErrMsg,
"Failed getting status for program.");
408 WaitResult.ReturnCode = -2;
416 if ((status & 0xBFFF0000U) == 0x80000000U)
417 WaitResult.ReturnCode =
static_cast<int>(
status);
418 else if (status & 0xFF)
419 WaitResult.ReturnCode = status & 0x7FFFFFFF;
421 WaitResult.ReturnCode = 1;
427 int result = _setmode( _fileno(stdin), _O_BINARY );
434 int result = _setmode( _fileno(stdout), _O_BINARY );
441 int result = _setmode( _fileno(stderr), _O_BINARY );
449 static const size_t MaxCommandStringLength = 32768;
450 size_t ArgLength = 0;
451 for (ArrayRef<const char*>::iterator
I = Args.begin(), E = Args.end();
455 ArgLength += ArgLenWithQuotes(*
I) + 1;
456 if (ArgLength > MaxCommandStringLength) {
bool can_execute(const Twine &Path)
Can we execute this file?
char *strpbrk(const char *s1, const char *s2);
error_code ChangeStdinToBinary()
bool argumentsFitWithinSystemLimits(ArrayRef< const char * > Args)
error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len, SmallVectorImpl< char > &utf8)
error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl< wchar_t > &utf16)
error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
error_code ChangeStderrToBinary()
static bool Execute(ProcessInfo &PI, StringRef Program, const char **args, const char **env, const StringRef **Redirects, unsigned memoryLimit, std::string *ErrMsg)
int fflush(FILE *stream);
bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix)
const error_category & generic_category()
std::string FindProgramByName(const std::string &name)
Construct a Program by finding it by name.
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=0)
error_code make_error_code(errc _e)
error_code ChangeStdoutToBinary()