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