packaging: Initial packaging
[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
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.
18 //
19 // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
20 // included.
21
22
23 #include <windows.h>
24 #include <sstream>
25 #include <cmSystemTools.h>
26
27 // We don't want any wildcard expansion.
28 // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
29 void _setargv() {}
30
31 static void Fatal(const char* msg, ...) {
32   va_list ap;
33   fprintf(stderr, "ninja: FATAL: ");
34   va_start(ap, msg);
35   vfprintf(stderr, msg, ap);
36   va_end(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.
40   fflush(stderr);
41   fflush(stdout);
42   ExitProcess(1);
43 }
44
45 static void usage(const char* msg) {
46   Fatal("%s\n\nusage:\n    "
47           "cmcldeps "
48           "<language C, CXX or RC>  "
49           "<source file path>  "
50           "<output path for *.d file>  "
51           "<output path for *.obj file>  "
52           "<prefix of /showIncludes>  "
53           "<path to cl.exe>  "
54           "<path to tool (cl or rc)>  "
55           "<rest of command ...>\n", msg);
56 }
57
58 static std::string trimLeadingSpace(const std::string& cmdline) {
59   int i = 0;
60   for (; cmdline[i] == ' '; ++i)
61     ;
62   return cmdline.substr(i);
63 }
64
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);
70     pos += repl.size();
71   }
72 }
73
74 bool startsWith(const std::string& str, const std::string& what) {
75   return str.compare(0, what.size(), what) == 0;
76 }
77
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) {
81   std::string ret;
82   bool in_quoted = false;
83   unsigned int i = 0;
84
85   cmdline = trimLeadingSpace(cmdline);
86
87   for (;; ++i) {
88     if (i >= cmdline.size())
89       usage("Couldn't parse arguments.");
90     if (!in_quoted && cmdline[i] == ' ')
91       break; // "a b" "x y"
92     if (cmdline[i] == '"')
93       in_quoted = !in_quoted;
94   }
95
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);
100   return ret;
101 }
102
103 static void parseCommandLine(LPTSTR wincmdline,
104                              std::string& lang,
105                              std::string& srcfile,
106                              std::string& dfile,
107                              std::string& objfile,
108                              std::string& prefix,
109                              std::string& clpath,
110                              std::string& binpath,
111                              std::string& rest) {
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);
122 }
123
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, " ", "\\ ");
129 }
130
131 static void outputDepFile(const std::string& dfile, const std::string& objfile,
132         std::vector<std::string>& incs) {
133
134   if (dfile.empty())
135     return;
136
137   // strip duplicates
138   std::sort(incs.begin(), incs.end());
139   incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
140
141   FILE* out = fopen(dfile.c_str(), "wb");
142
143   // FIXME should this be fatal or not? delete obj? delete d?
144   if (!out)
145     return;
146   std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
147   replaceAll(cwd, "/", "\\");
148   cwd += "\\";
149
150   std::string tmp = objfile;
151   escapePath(tmp);
152   fprintf(out, "%s: \\\n", tmp.c_str());
153
154   std::vector<std::string>::iterator it = incs.begin();
155   for (; it != incs.end(); ++it) {
156     tmp = *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());
163     escapePath(tmp);
164     fprintf(out, "%s \\\n", tmp.c_str());
165   }
166
167   fprintf(out, "\n");
168   fclose(out);
169 }
170
171
172 bool contains(const std::string& str, const std::string& what) {
173   return str.find(what) != std::string::npos;
174 }
175
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)
180     return str;
181   std::string replaced = str;
182   return replaced.replace(pos, what.size(), replacement);
183 }
184
185
186
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 = "",
193                     bool quiet = false)
194 {
195   std::string output;
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)
203     {
204     command.push_back(i->c_str());
205     }
206   // run the command
207   int exit_code = 0;
208   bool run = cmSystemTools::RunSingleCommand(command, &output, &exit_code,
209                                     dir.c_str(), cmSystemTools::OUTPUT_NONE);
210
211   // process the include directives and output everything else
212   std::stringstream ss(output);
213   std::string line;
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);
222     } else {
223       if (!isFirstLine || !startsWith(line, srcfilename)) {
224         if (!quiet || exit_code != 0) {
225           fprintf(stdout, "%s\n", line.c_str());
226         }
227       } else {
228         isFirstLine = false;
229       }
230     }
231   }
232
233   // don't update .d until/unless we succeed compilation
234   if (run && exit_code == 0)
235     outputDepFile(dfile, objfile, includes);
236
237   return exit_code;
238 }
239
240
241 int main() {
242
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.
248
249   std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
250   parseCommandLine(GetCommandLine(), lang, srcfile, dfile, objfile,
251                                      prefix, cl, binpath, rest);
252
253   // needed to suppress filename output of msvc tools
254   std::string srcfilename;
255   {
256   std::string::size_type pos = srcfile.rfind("\\");
257   if (pos == std::string::npos) {
258     srcfilename = srcfile;
259   } else {
260     srcfilename = srcfile.substr(pos + 1);
261   }
262   }
263
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
271
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 ");
276
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);
281
282     cl = "\"" + cl + "\" /P /DRC_INVOKED ";
283
284     // call cl in object dir so the .i is generated there
285     std::string objdir;
286     {
287     std::string::size_type pos = objfile.rfind("\\");
288     if (pos != std::string::npos) {
289       objdir = objfile.substr(0, pos);
290     }
291     }
292
293     // extract dependencies with cl.exe
294     int exit_code = process(srcfilename, dfile, objfile,
295                             prefix, cl + nol + show + clrest, objdir, true);
296
297     if (exit_code != 0)
298       return exit_code;
299
300     // compile rc file with rc.exe
301     return process(srcfilename, "" , objfile, prefix, binpath + " " + rest);
302   }
303
304   usage("Invalid language specified.");
305   return 1;
306 }