Imported Upstream version 3.25.0
[platform/upstream/cmake.git] / Source / cmcldeps.cxx
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 // Wrapper around cl that adds /showIncludes to command line, and uses that to
16 // generate .d files that match the style from gcc -MD.
17 //
18 // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
19 // included.
20
21 #include <algorithm>
22 #include <sstream>
23
24 #include <windows.h>
25
26 #include "cmsys/Encoding.hxx"
27
28 #include "cmStringAlgorithms.h"
29 #include "cmSystemTools.h"
30
31 // We don't want any wildcard expansion.
32 // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
33 void _setargv()
34 {
35 }
36
37 static void Fatal(const char* msg, ...)
38 {
39   va_list ap;
40   fprintf(stderr, "ninja: FATAL: ");
41   va_start(ap, msg);
42   vfprintf(stderr, msg, ap);
43   va_end(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.
47   fflush(stderr);
48   fflush(stdout);
49   ExitProcess(1);
50 }
51
52 static void usage(const char* msg)
53 {
54   Fatal("%s\n\nusage:\n    "
55         "cmcldeps "
56         "<language C, CXX or RC>  "
57         "<source file path>  "
58         "<output path for *.d file>  "
59         "<output path for *.obj file>  "
60         "<prefix of /showIncludes>  "
61         "<path to cl.exe>  "
62         "<path to tool (cl or rc)>  "
63         "<rest of command ...>\n",
64         msg);
65 }
66
67 static cm::string_view trimLeadingSpace(cm::string_view cmdline)
68 {
69   int i = 0;
70   for (; cmdline[i] == ' '; ++i)
71     ;
72   return cmdline.substr(i);
73 }
74
75 static void replaceAll(std::string& str, const std::string& search,
76                        const std::string& repl)
77 {
78   std::string::size_type pos = 0;
79   while ((pos = str.find(search, pos)) != std::string::npos) {
80     str.replace(pos, search.size(), repl);
81     pos += repl.size();
82   }
83 }
84
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)
88 {
89   bool in_quoted = false;
90   unsigned int i = 0;
91
92   cm::string_view cmdview = trimLeadingSpace(cmdline);
93   size_t spaceCnt = cmdline.size() - cmdview.size();
94
95   for (;; ++i) {
96     if (i >= cmdview.size())
97       usage("Couldn't parse arguments.");
98     if (!in_quoted && cmdview[i] == ' ')
99       break; // "a b" "x y"
100     if (cmdview[i] == '"')
101       in_quoted = !in_quoted;
102   }
103
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);
109   return ret;
110 }
111
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,
116                              std::string& rest)
117 {
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));
128 }
129
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)
133 {
134   replaceAll(path, "\\", "\\\\");
135   replaceAll(path, " ", "\\ ");
136 }
137
138 static void outputDepFile(const std::string& dfile, const std::string& objfile,
139                           std::vector<std::string>& incs)
140 {
141
142   if (dfile.empty())
143     return;
144
145   // strip duplicates
146   std::sort(incs.begin(), incs.end());
147   incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
148
149   FILE* out = cmsys::SystemTools::Fopen(dfile.c_str(), "wb");
150
151   // FIXME should this be fatal or not? delete obj? delete d?
152   if (!out)
153     return;
154   std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
155   replaceAll(cwd, "/", "\\");
156   cwd += "\\";
157
158   std::string tmp = objfile;
159   escapePath(tmp);
160   fprintf(out, "%s: \\\n", tmp.c_str());
161
162   std::vector<std::string>::iterator it = incs.begin();
163   for (; it != incs.end(); ++it) {
164     tmp = *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());
171     escapePath(tmp);
172     fprintf(out, "%s \\\n", tmp.c_str());
173   }
174
175   fprintf(out, "\n");
176   fclose(out);
177 }
178
179 bool contains(const std::string& str, const std::string& what)
180 {
181   return str.find(what) != std::string::npos;
182 }
183
184 std::string replace(const std::string& str, const std::string& what,
185                     const std::string& replacement)
186 {
187   size_t pos = str.find(what);
188   if (pos == std::string::npos)
189     return str;
190   std::string replaced = str;
191   return replaced.replace(pos, what.size(), replacement);
192 }
193
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 = "",
197                    bool quiet = false)
198 {
199   std::string output;
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();
206        ++i) {
207     command.push_back(*i);
208   }
209   // run the command
210   int exit_code = 0;
211   bool run =
212     cmSystemTools::RunSingleCommand(command, &output, &output, &exit_code,
213                                     dir.c_str(), cmSystemTools::OUTPUT_NONE);
214
215   // process the include directives and output everything else
216   std::istringstream ss(output);
217   std::string line;
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));
227     } else {
228       if (!isFirstLine || !cmHasPrefix(inc, srcfilename)) {
229         if (!quiet || exit_code != 0) {
230           fprintf(stdout, "%s\n", line.c_str());
231         }
232       } else {
233         isFirstLine = false;
234       }
235     }
236   }
237
238   // don't update .d until/unless we succeed compilation
239   if (run && exit_code == 0)
240     outputDepFile(dfile, objfile, includes);
241
242   return exit_code;
243 }
244
245 int main()
246 {
247
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.
253
254   std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
255   parseCommandLine(GetCommandLineW(), lang, srcfile, dfile, objfile, prefix,
256                    cl, binpath, rest);
257
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);
263   }
264
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
272
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, "-fo ", "-out:");
277     clrest = replace(clrest, objfile, objfile + ".dep.obj ");
278
279     cl = "\"" + cl + "\" /P /DRC_INVOKED /TC ";
280
281     // call cl in object dir so the .i is generated there
282     std::string objdir;
283     {
284       pos = objfile.rfind("\\");
285       if (pos != std::string::npos) {
286         objdir = objfile.substr(0, pos);
287       }
288     }
289
290     // extract dependencies with cl.exe
291     int exit_code = process(srcfilename, dfile, objfile, prefix,
292                             cl + nol + show + clrest, objdir, true);
293
294     if (exit_code != 0)
295       return exit_code;
296
297     // compile rc file with rc.exe
298     return process(srcfilename, "", objfile, prefix, binpath + " " + rest,
299                    std::string(), true);
300   }
301
302   usage("Invalid language specified.");
303   return 1;
304 }