cmcldeps.cxx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. // Wrapper around cl that adds /showIncludes to command line, and uses that to
  15. // generate .d files that match the style from gcc -MD.
  16. //
  17. // /showIncludes is equivalent to -MD, not -MMD, that is, system headers are
  18. // included.
  19. #include <algorithm>
  20. #include <sstream>
  21. #include <windows.h>
  22. #include "cmsys/Encoding.hxx"
  23. #include "cmStringAlgorithms.h"
  24. #include "cmSystemTools.h"
  25. // We don't want any wildcard expansion.
  26. // See http://msdn.microsoft.com/en-us/library/zay8tzh6(v=vs.85).aspx
  27. void _setargv()
  28. {
  29. }
  30. static void Fatal(const char* msg, ...)
  31. {
  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. static void usage(const char* msg)
  45. {
  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",
  56. msg);
  57. }
  58. static cm::string_view trimLeadingSpace(cm::string_view cmdline)
  59. {
  60. int i = 0;
  61. for (; cmdline[i] == ' '; ++i)
  62. ;
  63. return cmdline.substr(i);
  64. }
  65. static void replaceAll(std::string& str, const std::string& search,
  66. const std::string& repl)
  67. {
  68. std::string::size_type pos = 0;
  69. while ((pos = str.find(search, pos)) != std::string::npos) {
  70. str.replace(pos, search.size(), repl);
  71. pos += repl.size();
  72. }
  73. }
  74. // Strips one argument from the cmdline and returns it. "surrounding quotes"
  75. // are removed from the argument if there were any.
  76. static std::string getArg(std::string& cmdline)
  77. {
  78. bool in_quoted = false;
  79. unsigned int i = 0;
  80. cm::string_view cmdview = trimLeadingSpace(cmdline);
  81. size_t spaceCnt = cmdline.size() - cmdview.size();
  82. for (;; ++i) {
  83. if (i >= cmdview.size())
  84. usage("Couldn't parse arguments.");
  85. if (!in_quoted && cmdview[i] == ' ')
  86. break; // "a b" "x y"
  87. if (cmdview[i] == '"')
  88. in_quoted = !in_quoted;
  89. }
  90. cmdview = cmdview.substr(0, i);
  91. if (cmdview[0] == '"' && cmdview[i - 1] == '"')
  92. cmdview = cmdview.substr(1, i - 2);
  93. std::string ret(cmdview);
  94. cmdline.erase(0, spaceCnt + i);
  95. return ret;
  96. }
  97. static void parseCommandLine(LPWSTR wincmdline, std::string& lang,
  98. std::string& srcfile, std::string& dfile,
  99. std::string& objfile, std::string& prefix,
  100. std::string& clpath, std::string& binpath,
  101. std::string& rest)
  102. {
  103. std::string cmdline = cmsys::Encoding::ToNarrow(wincmdline);
  104. /* self */ getArg(cmdline);
  105. lang = getArg(cmdline);
  106. srcfile = getArg(cmdline);
  107. dfile = getArg(cmdline);
  108. objfile = getArg(cmdline);
  109. prefix = getArg(cmdline);
  110. clpath = getArg(cmdline);
  111. binpath = getArg(cmdline);
  112. rest = std::string(trimLeadingSpace(cmdline));
  113. }
  114. // Not all backslashes need to be escaped in a depfile, but it's easier that
  115. // way. See the re2c grammar in ninja's source code for more info.
  116. static void escapePath(std::string& path)
  117. {
  118. replaceAll(path, "\\", "\\\\");
  119. replaceAll(path, " ", "\\ ");
  120. }
  121. static void outputDepFile(const std::string& dfile, const std::string& objfile,
  122. std::vector<std::string>& incs)
  123. {
  124. if (dfile.empty())
  125. return;
  126. // strip duplicates
  127. std::sort(incs.begin(), incs.end());
  128. incs.erase(std::unique(incs.begin(), incs.end()), incs.end());
  129. FILE* out = cmsys::SystemTools::Fopen(dfile.c_str(), "wb");
  130. // FIXME should this be fatal or not? delete obj? delete d?
  131. if (!out)
  132. return;
  133. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  134. replaceAll(cwd, "/", "\\");
  135. cwd += "\\";
  136. std::string tmp = objfile;
  137. escapePath(tmp);
  138. fprintf(out, "%s: \\\n", tmp.c_str());
  139. std::vector<std::string>::iterator it = incs.begin();
  140. for (; it != incs.end(); ++it) {
  141. tmp = *it;
  142. // The paths need to match the ones used to identify build artifacts in the
  143. // build.ninja file. Therefore we need to canonicalize the path to use
  144. // backward slashes and relativize the path to the build directory.
  145. replaceAll(tmp, "/", "\\");
  146. if (cmHasPrefix(tmp, cwd))
  147. tmp.erase(0, cwd.size());
  148. escapePath(tmp);
  149. fprintf(out, "%s \\\n", tmp.c_str());
  150. }
  151. fprintf(out, "\n");
  152. fclose(out);
  153. }
  154. bool contains(const std::string& str, const std::string& what)
  155. {
  156. return str.find(what) != std::string::npos;
  157. }
  158. std::string replace(const std::string& str, const std::string& what,
  159. const std::string& replacement)
  160. {
  161. size_t pos = str.find(what);
  162. if (pos == std::string::npos)
  163. return str;
  164. std::string replaced = str;
  165. return replaced.replace(pos, what.size(), replacement);
  166. }
  167. static int process(cm::string_view srcfilename, const std::string& dfile,
  168. const std::string& objfile, const std::string& prefix,
  169. const std::string& cmd, const std::string& dir = "",
  170. bool quiet = false)
  171. {
  172. std::string output;
  173. // break up command line into a vector
  174. std::vector<std::string> args;
  175. cmSystemTools::ParseWindowsCommandLine(cmd.c_str(), args);
  176. // convert to correct vector type for RunSingleCommand
  177. std::vector<std::string> command;
  178. for (std::vector<std::string>::iterator i = args.begin(); i != args.end();
  179. ++i) {
  180. command.push_back(*i);
  181. }
  182. // run the command
  183. int exit_code = 0;
  184. bool run =
  185. cmSystemTools::RunSingleCommand(command, &output, &output, &exit_code,
  186. dir.c_str(), cmSystemTools::OUTPUT_NONE);
  187. // process the include directives and output everything else
  188. std::istringstream ss(output);
  189. std::string line;
  190. std::vector<std::string> includes;
  191. bool isFirstLine = true; // cl prints always first the source filename
  192. while (std::getline(ss, line)) {
  193. cm::string_view inc(line);
  194. if (cmHasPrefix(inc, prefix)) {
  195. inc = trimLeadingSpace(inc.substr(prefix.size()));
  196. if (inc.back() == '\r') // blech, stupid \r\n
  197. inc = inc.substr(0, inc.size() - 1);
  198. includes.emplace_back(std::string(inc));
  199. } else {
  200. if (!isFirstLine || !cmHasPrefix(inc, srcfilename)) {
  201. if (!quiet || exit_code != 0) {
  202. fprintf(stdout, "%s\n", line.c_str());
  203. }
  204. } else {
  205. isFirstLine = false;
  206. }
  207. }
  208. }
  209. // don't update .d until/unless we succeed compilation
  210. if (run && exit_code == 0)
  211. outputDepFile(dfile, objfile, includes);
  212. return exit_code;
  213. }
  214. int main()
  215. {
  216. // Use the Win32 API instead of argc/argv so we can avoid interpreting the
  217. // rest of command line after the .d and .obj. Custom parsing seemed
  218. // preferable to the ugliness you get into in trying to re-escape quotes for
  219. // subprocesses, so by avoiding argc/argv, the subprocess is called with
  220. // the same command line verbatim.
  221. std::string lang, srcfile, dfile, objfile, prefix, cl, binpath, rest;
  222. parseCommandLine(GetCommandLineW(), lang, srcfile, dfile, objfile, prefix,
  223. cl, binpath, rest);
  224. // needed to suppress filename output of msvc tools
  225. cm::string_view srcfilename(srcfile);
  226. std::string::size_type pos = srcfile.rfind('\\');
  227. if (pos != std::string::npos) {
  228. srcfilename = srcfilename.substr(pos + 1);
  229. }
  230. std::string nol = " /nologo ";
  231. std::string show = " /showIncludes ";
  232. if (lang == "C" || lang == "CXX") {
  233. return process(srcfilename, dfile, objfile, prefix,
  234. binpath + nol + show + rest);
  235. } else if (lang == "RC") {
  236. // "misuse" cl.exe to get headers from .rc files
  237. std::string clrest = rest;
  238. // rc: /fo x.dir\x.rc.res -> cl: /out:x.dir\x.rc.res.dep.obj
  239. clrest = replace(clrest, "/fo ", "/out:");
  240. clrest = replace(clrest, objfile, objfile + ".dep.obj ");
  241. cl = "\"" + cl + "\" /P /DRC_INVOKED /TC ";
  242. // call cl in object dir so the .i is generated there
  243. std::string objdir;
  244. {
  245. pos = objfile.rfind("\\");
  246. if (pos != std::string::npos) {
  247. objdir = objfile.substr(0, pos);
  248. }
  249. }
  250. // extract dependencies with cl.exe
  251. int exit_code = process(srcfilename, dfile, objfile, prefix,
  252. cl + nol + show + clrest, objdir, true);
  253. if (exit_code != 0)
  254. return exit_code;
  255. // compile rc file with rc.exe
  256. return process(srcfilename, "", objfile, prefix, binpath + " " + rest);
  257. }
  258. usage("Invalid language specified.");
  259. return 1;
  260. }