cmcldeps.cxx 9.1 KB

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