Ninja
msvc_helper-win32.cc
Go to the documentation of this file.
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
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
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
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.
14 
15 #include "msvc_helper.h"
16 
17 #include <algorithm>
18 #include <stdio.h>
19 #include <string.h>
20 #include <windows.h>
21 
22 #include "includes_normalize.h"
23 #include "util.h"
24 
25 namespace {
26 
27 /// Return true if \a input ends with \a needle.
28 bool EndsWith(const string& input, const string& needle) {
29  return (input.size() >= needle.size() &&
30  input.substr(input.size() - needle.size()) == needle);
31 }
32 
33 string Replace(const string& input, const string& find, const string& replace) {
34  string result = input;
35  size_t start_pos = 0;
36  while ((start_pos = result.find(find, start_pos)) != string::npos) {
37  result.replace(start_pos, find.length(), replace);
38  start_pos += replace.length();
39  }
40  return result;
41 }
42 
43 } // anonymous namespace
44 
45 string EscapeForDepfile(const string& path) {
46  // Depfiles don't escape single \.
47  return Replace(path, " ", "\\ ");
48 }
49 
50 // static
51 string CLParser::FilterShowIncludes(const string& line) {
52  static const char kMagicPrefix[] = "Note: including file: ";
53  const char* in = line.c_str();
54  const char* end = in + line.size();
55 
56  if (end - in > (int)sizeof(kMagicPrefix) - 1 &&
57  memcmp(in, kMagicPrefix, sizeof(kMagicPrefix) - 1) == 0) {
58  in += sizeof(kMagicPrefix) - 1;
59  while (*in == ' ')
60  ++in;
61  return line.substr(in - line.c_str());
62  }
63  return "";
64 }
65 
66 // static
67 bool CLParser::IsSystemInclude(string path) {
68  transform(path.begin(), path.end(), path.begin(), ::tolower);
69  // TODO: this is a heuristic, perhaps there's a better way?
70  return (path.find("program files") != string::npos ||
71  path.find("microsoft visual studio") != string::npos);
72 }
73 
74 // static
75 bool CLParser::FilterInputFilename(string line) {
76  transform(line.begin(), line.end(), line.begin(), ::tolower);
77  // TODO: other extensions, like .asm?
78  return EndsWith(line, ".c") ||
79  EndsWith(line, ".cc") ||
80  EndsWith(line, ".cxx") ||
81  EndsWith(line, ".cpp");
82 }
83 
84 string CLParser::Parse(const string& output) {
85  string filtered_output;
86 
87  // Loop over all lines in the output to process them.
88  size_t start = 0;
89  while (start < output.size()) {
90  size_t end = output.find_first_of("\r\n", start);
91  if (end == string::npos)
92  end = output.size();
93  string line = output.substr(start, end - start);
94 
95  string include = FilterShowIncludes(line);
96  if (!include.empty()) {
97  include = IncludesNormalize::Normalize(include, NULL);
98  if (!IsSystemInclude(include))
99  includes_.insert(include);
100  } else if (FilterInputFilename(line)) {
101  // Drop it.
102  // TODO: if we support compiling multiple output files in a single
103  // cl.exe invocation, we should stash the filename.
104  } else {
105  filtered_output.append(line);
106  filtered_output.append("\n");
107  }
108 
109  if (end < output.size() && output[end] == '\r')
110  ++end;
111  if (end < output.size() && output[end] == '\n')
112  ++end;
113  start = end;
114  }
115 
116  return filtered_output;
117 }
118 
119 int CLWrapper::Run(const string& command, string* output) {
120  SECURITY_ATTRIBUTES security_attributes = {};
121  security_attributes.nLength = sizeof(SECURITY_ATTRIBUTES);
122  security_attributes.bInheritHandle = TRUE;
123 
124  // Must be inheritable so subprocesses can dup to children.
125  HANDLE nul = CreateFile("NUL", GENERIC_READ,
126  FILE_SHARE_READ | FILE_SHARE_WRITE |
127  FILE_SHARE_DELETE,
128  &security_attributes, OPEN_EXISTING, 0, NULL);
129  if (nul == INVALID_HANDLE_VALUE)
130  Fatal("couldn't open nul");
131 
132  HANDLE stdout_read, stdout_write;
133  if (!CreatePipe(&stdout_read, &stdout_write, &security_attributes, 0))
134  Win32Fatal("CreatePipe");
135 
136  if (!SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0))
137  Win32Fatal("SetHandleInformation");
138 
139  PROCESS_INFORMATION process_info = {};
140  STARTUPINFO startup_info = {};
141  startup_info.cb = sizeof(STARTUPINFO);
142  startup_info.hStdInput = nul;
143  startup_info.hStdError = stdout_write;
144  startup_info.hStdOutput = stdout_write;
145  startup_info.dwFlags |= STARTF_USESTDHANDLES;
146 
147  if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
148  /* inherit handles */ TRUE, 0,
149  env_block_, NULL,
150  &startup_info, &process_info)) {
151  Win32Fatal("CreateProcess");
152  }
153 
154  if (!CloseHandle(nul) ||
155  !CloseHandle(stdout_write)) {
156  Win32Fatal("CloseHandle");
157  }
158 
159  // Read all output of the subprocess.
160  DWORD read_len = 1;
161  while (read_len) {
162  char buf[64 << 10];
163  read_len = 0;
164  if (!::ReadFile(stdout_read, buf, sizeof(buf), &read_len, NULL) &&
165  GetLastError() != ERROR_BROKEN_PIPE) {
166  Win32Fatal("ReadFile");
167  }
168  output->append(buf, read_len);
169  }
170 
171  // Wait for it to exit and grab its exit code.
172  if (WaitForSingleObject(process_info.hProcess, INFINITE) == WAIT_FAILED)
173  Win32Fatal("WaitForSingleObject");
174  DWORD exit_code = 0;
175  if (!GetExitCodeProcess(process_info.hProcess, &exit_code))
176  Win32Fatal("GetExitCodeProcess");
177 
178  if (!CloseHandle(stdout_read) ||
179  !CloseHandle(process_info.hProcess) ||
180  !CloseHandle(process_info.hThread)) {
181  Win32Fatal("CloseHandle");
182  }
183 
184  return exit_code;
185 }
static string FilterShowIncludes(const string &line)
Parse a line of cl.exe output and extract /showIncludes info.
static bool FilterInputFilename(string line)
Parse a line of cl.exe output and return true if it looks like it's printing an input filename...
static bool IsSystemInclude(string path)
Return true if a mentioned include file is a system path.
IN IN HANDLE
static string Normalize(const string &input, const char *relative_to)
Normalize by fixing slashes style, fixing redundant .
string Parse(const string &output)
Parse the full output of cl, returning the output (if any) that should printed.
void * env_block_
Definition: msvc_helper.h:61
int ReadFile(const string &path, string *contents, string *err)
Read a file to a string (in text mode: with CRLF conversion on Windows).
Definition: util.cc:178
int Run(const string &command, string *output)
Start a process and gather its raw output.
void Fatal(const char *msg,...)
Log a fatal message and exit.
Definition: util.cc:51
set< string > includes_
Definition: msvc_helper.h:46
string EscapeForDepfile(const string &path)
IN DWORD