1 // Copyright 2011 Google Inc. All Rights Reserved.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
15 #include "msvc_helper.h"
23 string Replace(const string& input, const string& find, const string& replace) {
24 string result = input;
26 while ((start_pos = result.find(find, start_pos)) != string::npos) {
27 result.replace(start_pos, find.length(), replace);
28 start_pos += replace.length();
33 } // anonymous namespace
35 string EscapeForDepfile(const string& path) {
36 // Depfiles don't escape single \.
37 return Replace(path, " ", "\\ ");
40 int CLWrapper::Run(const string& command, string* output) {
41 SECURITY_ATTRIBUTES security_attributes = {};
42 security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
43 security_attributes.bInheritHandle = TRUE;
45 // Must be inheritable so subprocesses can dup to children.
46 HANDLE nul = CreateFile("NUL", GENERIC_READ,
47 FILE_SHARE_READ | FILE_SHARE_WRITE |
49 &security_attributes, OPEN_EXISTING, 0, NULL);
50 if (nul == INVALID_HANDLE_VALUE)
51 Fatal("couldn't open nul");
53 HANDLE stdout_read, stdout_write;
54 if (!CreatePipe(&stdout_read, &stdout_write, &security_attributes, 0))
55 Win32Fatal("CreatePipe");
57 if (!SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0))
58 Win32Fatal("SetHandleInformation");
60 PROCESS_INFORMATION process_info = {};
61 STARTUPINFO startup_info = {};
62 startup_info.cb = sizeof(STARTUPINFO);
63 startup_info.hStdInput = nul;
64 startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);
65 startup_info.hStdOutput = stdout_write;
66 startup_info.dwFlags |= STARTF_USESTDHANDLES;
68 if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
69 /* inherit handles */ TRUE, 0,
71 &startup_info, &process_info)) {
72 Win32Fatal("CreateProcess");
75 if (!CloseHandle(nul) ||
76 !CloseHandle(stdout_write)) {
77 Win32Fatal("CloseHandle");
80 // Read all output of the subprocess.
85 if (!::ReadFile(stdout_read, buf, sizeof(buf), &read_len, NULL) &&
86 GetLastError() != ERROR_BROKEN_PIPE) {
87 Win32Fatal("ReadFile");
89 output->append(buf, read_len);
92 // Wait for it to exit and grab its exit code.
93 if (WaitForSingleObject(process_info.hProcess, INFINITE) == WAIT_FAILED)
94 Win32Fatal("WaitForSingleObject");
96 if (!GetExitCodeProcess(process_info.hProcess, &exit_code))
97 Win32Fatal("GetExitCodeProcess");
99 if (!CloseHandle(stdout_read) ||
100 !CloseHandle(process_info.hProcess) ||
101 !CloseHandle(process_info.hThread)) {
102 Win32Fatal("CloseHandle");