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 // Wrapper around cl that adds /showIncludes to command line, and uses that to
16 // generate .d files that match the style from gcc -MD.
18 // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
26 #include "cmsys/Encoding.hxx"
28 #include "cmStringAlgorithms.h"
29 #include "cmSystemTools.h"
31 // We don't want any wildcard expansion.
32 // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
37 static void Fatal(const char* msg, ...)
40 fprintf(stderr, "ninja: FATAL: ");
42 vfprintf(stderr, msg, ap);
44 fprintf(stderr, "\n");
45 // On Windows, some tools may inject extra threads.
46 // exit() may block on locks held by those threads, so forcibly exit.
52 static void usage(const char* msg)
54 Fatal("%s\n\nusage:\n "
56 "<language C, CXX or RC> "
58 "<output path for *.d file> "
59 "<output path for *.obj file> "
60 "<prefix of /showIncludes> "
62 "<path to tool (cl or rc)> "
63 "<rest of command ...>\n",
67 static cm::string_view trimLeadingSpace(cm::string_view cmdline)
70 for (; cmdline[i] == ' '; ++i)
72 return cmdline.substr(i);
75 static void replaceAll(std::string& str, const std::string& search,
76 const std::string& repl)
78 std::string::size_type pos = 0;
79 while ((pos = str.find(search, pos)) != std::string::npos) {
80 str.replace(pos, search.size(), repl);
85 // Strips one argument from the cmdline and returns it. "surrounding quotes"
86 // are removed from the argument if there were any.
87 static std::string getArg(std::string& cmdline)
89 bool in_quoted = false;
92 cm::string_view cmdview = trimLeadingSpace(cmdline);
93 size_t spaceCnt = cmdline.size() - cmdview.size();
96 if (i >= cmdview.size())
97 usage("Couldn't parse arguments.");
98 if (!in_quoted && cmdview[i] == ' ')
100 if (cmdview[i] == '"')
101 in_quoted = !in_quoted;
104 cmdview = cmdview.substr(0, i);
105 if (cmdview[0] == '"' && cmdview[i - 1] == '"')
106 cmdview = cmdview.substr(1, i - 2);
107 std::string ret(cmdview);
108 cmdline.erase(0, spaceCnt + i);
112 static void parseCommandLine(LPWSTR wincmdline, std::string& lang,
113 std::string& srcfile, std::string& dfile,
114 std::string& objfile, std::string& prefix,
115 std::string& clpath, std::string& binpath,
118 std::string cmdline = cmsys::Encoding::ToNarrow(wincmdline);
119 /* self */ getArg(cmdline);
120 lang = getArg(cmdline);
121 srcfile = getArg(cmdline);
122 dfile = getArg(cmdline);
123 objfile = getArg(cmdline);
124 prefix = getArg(cmdline);
125 clpath = getArg(cmdline);
126 binpath = getArg(cmdline);
127 rest = std::string(trimLeadingSpace(cmdline));
130 // Not all backslashes need to be escaped in a depfile, but it's easier that
131 // way. See the re2c grammar in ninja's source code for more info.
132 static void escapePath(std::string& path)
134 replaceAll(path, "\\", "\\\\");
135 replaceAll(path, " ", "\\ ");
138 static void outputDepFile(const std::string& dfile, const std::string& objfile,
139 std::vector<std::string>& incs)
146 std::sort(incs.begin(), incs.end());
147 incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
149 FILE* out = cmsys::SystemTools::Fopen(dfile.c_str(), "wb");
151 // FIXME should this be fatal or not? delete obj? delete d?
154 std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
155 replaceAll(cwd, "/", "\\");
158 std::string tmp = objfile;
160 fprintf(out, "%s: \\\n", tmp.c_str());
162 std::vector<std::string>::iterator it = incs.begin();
163 for (; it != incs.end(); ++it) {
165 // The paths need to match the ones used to identify build artifacts in the
166 // build.ninja file. Therefore we need to canonicalize the path to use
167 // backward slashes and relativize the path to the build directory.
168 replaceAll(tmp, "/", "\\");
169 if (cmHasPrefix(tmp, cwd))
170 tmp.erase(0, cwd.size());
172 fprintf(out, "%s \\\n", tmp.c_str());
179 bool contains(const std::string& str, const std::string& what)
181 return str.find(what) != std::string::npos;
184 std::string replace(const std::string& str, const std::string& what,
185 const std::string& replacement)
187 size_t pos = str.find(what);
188 if (pos == std::string::npos)
190 std::string replaced = str;
191 return replaced.replace(pos, what.size(), replacement);
194 static int process(cm::string_view srcfilename, const std::string& dfile,
195 const std::string& objfile, const std::string& prefix,
196 const std::string& cmd, const std::string& dir = "",
200 // break up command line into a vector
201 std::vector<std::string> args;
202 cmSystemTools::ParseWindowsCommandLine(cmd.c_str(), args);
203 // convert to correct vector type for RunSingleCommand
204 std::vector<std::string> command;
205 for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
207 command.push_back(*i);
212 cmSystemTools::RunSingleCommand(command, &output, &output, &exit_code,
213 dir.c_str(), cmSystemTools::OUTPUT_NONE);
215 // process the include directives and output everything else
216 std::istringstream ss(output);
218 std::vector<std::string> includes;
219 bool isFirstLine = true; // cl prints always first the source filename
220 while (std::getline(ss, line)) {
221 cm::string_view inc(line);
222 if (cmHasPrefix(inc, prefix)) {
223 inc = trimLeadingSpace(inc.substr(prefix.size()));
224 if (inc.back() == '\r') // blech, stupid \r\n
225 inc = inc.substr(0, inc.size() - 1);
226 includes.emplace_back(std::string(inc));
228 if (!isFirstLine || !cmHasPrefix(inc, srcfilename)) {
229 if (!quiet || exit_code != 0) {
230 fprintf(stdout, "%s\n", line.c_str());
238 // don't update .d until/unless we succeed compilation
239 if (run && exit_code == 0)
240 outputDepFile(dfile, objfile, includes);
248 // Use the Win32 API instead of argc/argv so we can avoid interpreting the
249 // rest of command line after the .d and .obj. Custom parsing seemed
250 // preferable to the ugliness you get into in trying to re-escape quotes for
251 // subprocesses, so by avoiding argc/argv, the subprocess is called with
252 // the same command line verbatim.
254 std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
255 parseCommandLine(GetCommandLineW(), lang, srcfile, dfile, objfile, prefix,
258 // needed to suppress filename output of msvc tools
259 cm::string_view srcfilename(srcfile);
260 std::string::size_type pos = srcfile.rfind('\\');
261 if (pos != std::string::npos) {
262 srcfilename = srcfilename.substr(pos + 1);
265 std::string nol = " /nologo ";
266 std::string show = " /showIncludes ";
267 if (lang == "C" || lang == "CXX") {
268 return process(srcfilename, dfile, objfile, prefix,
269 binpath + nol + show + rest);
270 } else if (lang == "RC") {
271 // "misuse" cl.exe to get headers from .rc files
273 std::string clrest = rest;
274 // rc: /fo x.dir\x.rc.res -> cl: /out:x.dir\x.rc.res.dep.obj
275 clrest = replace(clrest, "/fo ", "/out:");
276 clrest = replace(clrest, objfile, objfile + ".dep.obj ");
278 cl = "\"" + cl + "\" /P /DRC_INVOKED /TC ";
280 // call cl in object dir so the .i is generated there
283 pos = objfile.rfind("\\");
284 if (pos != std::string::npos) {
285 objdir = objfile.substr(0, pos);
289 // extract dependencies with cl.exe
290 int exit_code = process(srcfilename, dfile, objfile, prefix,
291 cl + nol + show + clrest, objdir, true);
296 // compile rc file with rc.exe
297 return process(srcfilename, "", objfile, prefix, binpath + " " + rest,
298 std::string(), true);
301 usage("Invalid language specified.");