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.
16 // Wrapper around cl that adds /showIncludes to command line, and uses that to
17 // generate .d files that match the style from gcc -MD.
19 // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
25 #include <cmSystemTools.h>
27 // We don't want any wildcard expansion.
28 // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
31 static void Fatal(const char* msg, ...) {
33 fprintf(stderr, "ninja: FATAL: ");
35 vfprintf(stderr, msg, ap);
37 fprintf(stderr, "\n");
38 // On Windows, some tools may inject extra threads.
39 // exit() may block on locks held by those threads, so forcibly exit.
45 static void usage(const char* msg) {
46 Fatal("%s\n\nusage:\n "
48 "<language C, CXX or RC> "
50 "<output path for *.d file> "
51 "<output path for *.obj file> "
52 "<prefix of /showIncludes> "
54 "<path to tool (cl or rc)> "
55 "<rest of command ...>\n", msg);
58 static std::string trimLeadingSpace(const std::string& cmdline) {
60 for (; cmdline[i] == ' '; ++i)
62 return cmdline.substr(i);
65 static void replaceAll(std::string& str, const std::string& search,
66 const std::string& repl) {
67 std::string::size_type pos = 0;
68 while ((pos = str.find(search, pos)) != std::string::npos) {
69 str.replace(pos, search.size(), repl);
74 bool startsWith(const std::string& str, const std::string& what) {
75 return str.compare(0, what.size(), what) == 0;
78 // Strips one argument from the cmdline and returns it. "surrounding quotes"
79 // are removed from the argument if there were any.
80 static std::string getArg(std::string& cmdline) {
82 bool in_quoted = false;
85 cmdline = trimLeadingSpace(cmdline);
88 if (i >= cmdline.size())
89 usage("Couldn't parse arguments.");
90 if (!in_quoted && cmdline[i] == ' ')
92 if (cmdline[i] == '"')
93 in_quoted = !in_quoted;
96 ret = cmdline.substr(0, i);
97 if (ret[0] == '"' && ret[i - 1] == '"')
98 ret = ret.substr(1, ret.size() - 2);
99 cmdline = cmdline.substr(i);
103 static void parseCommandLine(LPTSTR wincmdline,
105 std::string& srcfile,
107 std::string& objfile,
110 std::string& binpath,
112 std::string cmdline(wincmdline);
113 /* self */ getArg(cmdline);
114 lang = getArg(cmdline);
115 srcfile = getArg(cmdline);
116 dfile = getArg(cmdline);
117 objfile = getArg(cmdline);
118 prefix = getArg(cmdline);
119 clpath = getArg(cmdline);
120 binpath = getArg(cmdline);
121 rest = trimLeadingSpace(cmdline);
124 // Not all backslashes need to be escaped in a depfile, but it's easier that
125 // way. See the re2c grammar in ninja's source code for more info.
126 static void escapePath(std::string &path) {
127 replaceAll(path, "\\", "\\\\");
128 replaceAll(path, " ", "\\ ");
131 static void outputDepFile(const std::string& dfile, const std::string& objfile,
132 std::vector<std::string>& incs) {
138 std::sort(incs.begin(), incs.end());
139 incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
141 FILE* out = fopen(dfile.c_str(), "wb");
143 // FIXME should this be fatal or not? delete obj? delete d?
146 std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
147 replaceAll(cwd, "/", "\\");
150 std::string tmp = objfile;
152 fprintf(out, "%s: \\\n", tmp.c_str());
154 std::vector<std::string>::iterator it = incs.begin();
155 for (; it != incs.end(); ++it) {
157 // The paths need to match the ones used to identify build artifacts in the
158 // build.ninja file. Therefore we need to canonicalize the path to use
159 // backward slashes and relativize the path to the build directory.
160 replaceAll(tmp, "/", "\\");
161 if (startsWith(tmp, cwd))
162 tmp = tmp.substr(cwd.size());
164 fprintf(out, "%s \\\n", tmp.c_str());
172 bool contains(const std::string& str, const std::string& what) {
173 return str.find(what) != std::string::npos;
176 std::string replace(const std::string& str, const std::string& what,
177 const std::string& replacement) {
178 size_t pos = str.find(what);
179 if (pos == std::string::npos)
181 std::string replaced = str;
182 return replaced.replace(pos, what.size(), replacement);
187 static int process( const std::string& srcfilename,
188 const std::string& dfile,
189 const std::string& objfile,
190 const std::string& prefix,
191 const std::string& cmd,
192 const std::string& dir = "",
196 // break up command line into a vector
197 std::vector<std::string> args;
198 cmSystemTools::ParseWindowsCommandLine(cmd.c_str(), args);
199 // convert to correct vector type for RunSingleCommand
200 std::vector<cmStdString> command;
201 for(std::vector<std::string>::iterator i = args.begin();
202 i != args.end(); ++i)
204 command.push_back(i->c_str());
208 bool run = cmSystemTools::RunSingleCommand(command, &output, &exit_code,
209 dir.c_str(), cmSystemTools::OUTPUT_NONE);
211 // process the include directives and output everything else
212 std::stringstream ss(output);
214 std::vector<std::string> includes;
215 bool isFirstLine = true; // cl prints always first the source filename
216 while (std::getline(ss, line)) {
217 if (startsWith(line, prefix)) {
218 std::string inc = trimLeadingSpace(line.substr(prefix.size()).c_str());
219 if (inc[inc.size() - 1] == '\r') // blech, stupid \r\n
220 inc = inc.substr(0, inc.size() - 1);
221 includes.push_back(inc);
223 if (!isFirstLine || !startsWith(line, srcfilename)) {
224 if (!quiet || exit_code != 0) {
225 fprintf(stdout, "%s\n", line.c_str());
233 // don't update .d until/unless we succeed compilation
234 if (run && exit_code == 0)
235 outputDepFile(dfile, objfile, includes);
243 // Use the Win32 API instead of argc/argv so we can avoid interpreting the
244 // rest of command line after the .d and .obj. Custom parsing seemed
245 // preferable to the ugliness you get into in trying to re-escape quotes for
246 // subprocesses, so by avoiding argc/argv, the subprocess is called with
247 // the same command line verbatim.
249 std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
250 parseCommandLine(GetCommandLine(), lang, srcfile, dfile, objfile,
251 prefix, cl, binpath, rest);
253 // needed to suppress filename output of msvc tools
254 std::string srcfilename;
256 std::string::size_type pos = srcfile.rfind("\\");
257 if (pos == std::string::npos) {
258 srcfilename = srcfile;
260 srcfilename = srcfile.substr(pos + 1);
264 std::string nol = " /nologo ";
265 std::string show = " /showIncludes ";
266 if (lang == "C" || lang == "CXX") {
267 return process(srcfilename, dfile, objfile, prefix,
268 binpath + nol + show + rest);
269 } else if (lang == "RC") {
270 // "misuse" cl.exe to get headers from .rc files
272 std::string clrest = rest;
273 // rc: /fo x.dir\x.rc.res -> cl: /out:x.dir\x.rc.res.dep.obj
274 clrest = replace(clrest, "/fo", "/out:");
275 clrest = replace(clrest, objfile, objfile + ".dep.obj ");
277 // rc: src\x\x.rc -> cl: /Tc src\x\x.rc
278 if (srcfile.find(" ") != std::string::npos)
279 srcfile = "\"" + srcfile + "\"";
280 clrest = replace(clrest, srcfile, "/Tc " + srcfile);
282 cl = "\"" + cl + "\" /P /DRC_INVOKED ";
284 // call cl in object dir so the .i is generated there
287 std::string::size_type pos = objfile.rfind("\\");
288 if (pos != std::string::npos) {
289 objdir = objfile.substr(0, pos);
293 // extract dependencies with cl.exe
294 int exit_code = process(srcfilename, dfile, objfile,
295 prefix, cl + nol + show + clrest, objdir, true);
300 // compile rc file with rc.exe
301 return process(srcfilename, "" , objfile, prefix, binpath + " " + rest);
304 usage("Invalid language specified.");