cmcmd.cxx 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmcmd.h"
  4. #include <cmext/algorithm>
  5. #include <fcntl.h>
  6. #include "cm_uv.h"
  7. #include "cmAlgorithms.h"
  8. #include "cmDuration.h"
  9. #include "cmGlobalGenerator.h"
  10. #include "cmLocalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmQtAutoMocUic.h"
  13. #include "cmQtAutoRcc.h"
  14. #include "cmRange.h"
  15. #include "cmState.h"
  16. #include "cmStateDirectory.h"
  17. #include "cmStateSnapshot.h"
  18. #include "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. #include "cmUVProcessChain.h"
  21. #include "cmUtils.hxx"
  22. #include "cmVersion.h"
  23. #include "cmake.h"
  24. #if !defined(CMAKE_BOOTSTRAP)
  25. # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
  26. # include "cmFileTime.h"
  27. # include "cmServer.h"
  28. # include "cmServerConnection.h"
  29. # include "bindexplib.h"
  30. #endif
  31. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
  32. # include "cmsys/ConsoleBuf.hxx"
  33. #endif
  34. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  35. # include "cmVisualStudioWCEPlatformParser.h"
  36. #endif
  37. #include <array>
  38. #include <cstdio>
  39. #include <cstdlib>
  40. #include <cstring>
  41. #include <ctime>
  42. #include <iostream>
  43. #include <memory>
  44. #include <sstream>
  45. #include <utility>
  46. #include <cm/string_view>
  47. #include "cmsys/Directory.hxx"
  48. #include "cmsys/FStream.hxx"
  49. #include "cmsys/Process.h"
  50. #include "cmsys/Terminal.h"
  51. class cmConnection;
  52. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  53. std::vector<std::string>::const_iterator argEnd);
  54. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  55. std::vector<std::string>::const_iterator argEnd);
  56. void CMakeCommandUsage(const char* program)
  57. {
  58. std::ostringstream errorStream;
  59. #ifndef CMAKE_BOOTSTRAP
  60. /* clang-format off */
  61. errorStream
  62. << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
  63. /* clang-format on */
  64. #else
  65. /* clang-format off */
  66. errorStream
  67. << "cmake bootstrap\n";
  68. /* clang-format on */
  69. #endif
  70. // If you add new commands, change here,
  71. // and in cmakemain.cxx in the options table
  72. /* clang-format off */
  73. errorStream
  74. << "Usage: " << program << " -E <command> [arguments...]\n"
  75. << "Available commands: \n"
  76. << " capabilities - Report capabilities built into cmake "
  77. "in JSON format\n"
  78. << " chdir dir cmd [args...] - run command in a given directory\n"
  79. << " compare_files [--ignore-eol] file1 file2\n"
  80. << " - check if file1 is same as file2\n"
  81. << " copy <file>... destination - copy files to destination "
  82. "(either file or directory)\n"
  83. << " copy_directory <dir>... destination - copy content of <dir>... "
  84. "directories to 'destination' directory\n"
  85. << " copy_if_different <file>... destination - copy files if it has "
  86. "changed\n"
  87. << " echo [<string>...] - displays arguments as text\n"
  88. << " echo_append [<string>...] - displays arguments as text but no new "
  89. "line\n"
  90. << " env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...\n"
  91. << " - run command in a modified environment\n"
  92. << " environment - display the current environment\n"
  93. << " make_directory <dir>... - create parent and <dir> directories\n"
  94. << " md5sum <file>... - create MD5 checksum of files\n"
  95. << " sha1sum <file>... - create SHA1 checksum of files\n"
  96. << " sha224sum <file>... - create SHA224 checksum of files\n"
  97. << " sha256sum <file>... - create SHA256 checksum of files\n"
  98. << " sha384sum <file>... - create SHA384 checksum of files\n"
  99. << " sha512sum <file>... - create SHA512 checksum of files\n"
  100. << " remove [-f] <file>... - remove the file(s), use -f to force "
  101. "it (deprecated: use rm instead)\n"
  102. << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
  103. << " rename oldname newname - rename a file or directory "
  104. "(on one volume)\n"
  105. << " rm [-rRf] <file/dir>... - remove files or directories, use -f to "
  106. "force it, r or R to remove directories and their contents recursively\n"
  107. << " server - start cmake in server mode\n"
  108. << " sleep <number>... - sleep for given number of seconds\n"
  109. << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
  110. << " - create or extract a tar or zip archive\n"
  111. << " time command [args...] - run command and display elapsed time\n"
  112. << " touch <file>... - touch a <file>.\n"
  113. << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
  114. << " create_symlink old new - create a symbolic link new -> old\n"
  115. << " true - do nothing with an exit code of 0\n"
  116. << " false - do nothing with an exit code of 1\n"
  117. #if defined(_WIN32) && !defined(__CYGWIN__)
  118. << "Available on Windows only:\n"
  119. << " delete_regv key - delete registry value\n"
  120. << " env_vs8_wince sdkname - displays a batch file which sets the "
  121. "environment for the provided Windows CE SDK installed in VS2005\n"
  122. << " env_vs9_wince sdkname - displays a batch file which sets the "
  123. "environment for the provided Windows CE SDK installed in VS2008\n"
  124. << " write_regv key value - write registry value\n"
  125. #endif
  126. ;
  127. /* clang-format on */
  128. cmSystemTools::Error(errorStream.str());
  129. }
  130. static bool cmTarFilesFrom(std::string const& file,
  131. std::vector<std::string>& files)
  132. {
  133. if (cmSystemTools::FileIsDirectory(file)) {
  134. std::ostringstream e;
  135. e << "-E tar --files-from= file '" << file << "' is a directory";
  136. cmSystemTools::Error(e.str());
  137. return false;
  138. }
  139. cmsys::ifstream fin(file.c_str());
  140. if (!fin) {
  141. std::ostringstream e;
  142. e << "-E tar --files-from= file '" << file << "' not found";
  143. cmSystemTools::Error(e.str());
  144. return false;
  145. }
  146. std::string line;
  147. while (cmSystemTools::GetLineFromStream(fin, line)) {
  148. if (line.empty()) {
  149. continue;
  150. }
  151. if (cmHasLiteralPrefix(line, "--add-file=")) {
  152. files.push_back(line.substr(11));
  153. } else if (cmHasLiteralPrefix(line, "-")) {
  154. std::ostringstream e;
  155. e << "-E tar --files-from='" << file << "' file invalid line:\n"
  156. << line << "\n";
  157. cmSystemTools::Error(e.str());
  158. return false;
  159. } else {
  160. files.push_back(line);
  161. }
  162. }
  163. return true;
  164. }
  165. static bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
  166. {
  167. if (cmSystemTools::FileIsSymlink(dir)) {
  168. if (!cmSystemTools::RemoveFile(dir)) {
  169. std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
  170. return false;
  171. }
  172. } else if (!recursive) {
  173. std::cerr << "Error removing directory \"" << dir
  174. << "\" without recursive option.\n";
  175. return false;
  176. } else if (!cmSystemTools::RemoveADirectory(dir)) {
  177. std::cerr << "Error removing directory \"" << dir << "\".\n";
  178. return false;
  179. }
  180. return true;
  181. }
  182. static int HandleIWYU(const std::string& runCmd,
  183. const std::string& /* sourceFile */,
  184. const std::vector<std::string>& orig_cmd)
  185. {
  186. // Construct the iwyu command line by taking what was given
  187. // and adding all the arguments we give to the compiler.
  188. std::vector<std::string> iwyu_cmd = cmExpandedList(runCmd, true);
  189. cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
  190. // Run the iwyu command line. Capture its stderr and hide its stdout.
  191. // Ignore its return code because the tool always returns non-zero.
  192. std::string stdErr;
  193. int ret;
  194. if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
  195. nullptr, cmSystemTools::OUTPUT_NONE)) {
  196. std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
  197. return 1;
  198. }
  199. // Warn if iwyu reported anything.
  200. if (stdErr.find("should remove these lines:") != std::string::npos ||
  201. stdErr.find("should add these lines:") != std::string::npos) {
  202. std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
  203. << stdErr << "\n";
  204. }
  205. // always return 0 we don't want to break the compile
  206. return 0;
  207. }
  208. static int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
  209. const std::vector<std::string>& orig_cmd)
  210. {
  211. // Construct the clang-tidy command line by taking what was given
  212. // and adding our compiler command line. The clang-tidy tool will
  213. // automatically skip over the compiler itself and extract the
  214. // options.
  215. int ret;
  216. std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
  217. tidy_cmd.push_back(sourceFile);
  218. tidy_cmd.emplace_back("--");
  219. cm::append(tidy_cmd, orig_cmd);
  220. // Run the tidy command line. Capture its stdout and hide its stderr.
  221. std::string stdOut;
  222. std::string stdErr;
  223. if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
  224. nullptr, cmSystemTools::OUTPUT_NONE)) {
  225. std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
  226. return 1;
  227. }
  228. // Output the stdout from clang-tidy to stderr
  229. std::cerr << stdOut;
  230. // If clang-tidy exited with an error do the same.
  231. if (ret != 0) {
  232. std::cerr << stdErr;
  233. }
  234. return ret;
  235. }
  236. static int HandleLWYU(const std::string& runCmd,
  237. const std::string& /* sourceFile */,
  238. const std::vector<std::string>&)
  239. {
  240. // Construct the ldd -r -u (link what you use lwyu) command line
  241. // ldd -u -r lwuy target
  242. std::vector<std::string> lwyu_cmd;
  243. lwyu_cmd.emplace_back("ldd");
  244. lwyu_cmd.emplace_back("-u");
  245. lwyu_cmd.emplace_back("-r");
  246. lwyu_cmd.push_back(runCmd);
  247. // Run the ldd -u -r command line.
  248. // Capture its stdout and hide its stderr.
  249. // Ignore its return code because the tool always returns non-zero
  250. // if there are any warnings, but we just want to warn.
  251. std::string stdOut;
  252. std::string stdErr;
  253. int ret;
  254. if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
  255. nullptr, cmSystemTools::OUTPUT_NONE)) {
  256. std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
  257. return 1;
  258. }
  259. // Output the stdout from ldd -r -u to stderr
  260. // Warn if lwyu reported anything.
  261. if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
  262. std::cerr << "Warning: " << stdOut;
  263. }
  264. return 0;
  265. }
  266. static int HandleCppLint(const std::string& runCmd,
  267. const std::string& sourceFile,
  268. const std::vector<std::string>&)
  269. {
  270. // Construct the cpplint command line.
  271. std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
  272. cpplint_cmd.push_back(sourceFile);
  273. // Run the cpplint command line. Capture its output.
  274. std::string stdOut;
  275. int ret;
  276. if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
  277. nullptr, cmSystemTools::OUTPUT_NONE)) {
  278. std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
  279. << "\n";
  280. return 1;
  281. }
  282. if (!stdOut.empty()) {
  283. std::cerr << "Warning: cpplint diagnostics:\n";
  284. // Output the output from cpplint to stderr
  285. std::cerr << stdOut;
  286. }
  287. // always return 0 so the build can continue as cpplint returns non-zero
  288. // for any warning
  289. return 0;
  290. }
  291. static int HandleCppCheck(const std::string& runCmd,
  292. const std::string& sourceFile,
  293. const std::vector<std::string>& orig_cmd)
  294. {
  295. // Construct the cpplint command line.
  296. std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
  297. // extract all the -D, -U, and -I options from the compile line
  298. for (auto const& opt : orig_cmd) {
  299. if (opt.size() > 2) {
  300. if ((opt[0] == '-') &&
  301. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  302. cppcheck_cmd.push_back(opt);
  303. // convert cl / options to - options if needed
  304. #if defined(_WIN32)
  305. } else if ((opt[0] == '/') &&
  306. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  307. std::string optcopy = opt;
  308. optcopy[0] = '-';
  309. cppcheck_cmd.push_back(optcopy);
  310. #endif
  311. }
  312. }
  313. }
  314. // add the source file
  315. cppcheck_cmd.push_back(sourceFile);
  316. // Run the cpplint command line. Capture its output.
  317. std::string stdOut;
  318. std::string stdErr;
  319. int ret;
  320. if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
  321. nullptr, cmSystemTools::OUTPUT_NONE)) {
  322. std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
  323. << "\n";
  324. return 1;
  325. }
  326. std::cerr << stdOut;
  327. // Output the output from cpplint to stderr
  328. if (stdErr.find("(error)") != std::string::npos ||
  329. stdErr.find("(warning)") != std::string::npos ||
  330. stdErr.find("(style)") != std::string::npos ||
  331. stdErr.find("(performance)") != std::string::npos ||
  332. stdErr.find("(portability)") != std::string::npos ||
  333. stdErr.find("(information)") != std::string::npos) {
  334. if (ret == 0) {
  335. std::cerr << "Warning: cppcheck reported diagnostics:\n";
  336. } else {
  337. std::cerr << "Error: cppcheck reported failure:\n";
  338. }
  339. }
  340. std::cerr << stdErr;
  341. return ret;
  342. }
  343. using CoCompileHandler = int (*)(const std::string&, const std::string&,
  344. const std::vector<std::string>&);
  345. struct CoCompiler
  346. {
  347. const char* Option;
  348. CoCompileHandler Handler;
  349. bool NoOriginalCommand;
  350. };
  351. static const std::array<CoCompiler, 5> CoCompilers = {
  352. { // Table of options and handlers.
  353. { "--cppcheck=", HandleCppCheck, false },
  354. { "--cpplint=", HandleCppLint, false },
  355. { "--iwyu=", HandleIWYU, false },
  356. { "--lwyu=", HandleLWYU, true },
  357. { "--tidy=", HandleTidy, false } }
  358. };
  359. struct CoCompileJob
  360. {
  361. std::string Command;
  362. CoCompileHandler Handler;
  363. };
  364. // called when args[0] == "__run_co_compile"
  365. int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
  366. {
  367. std::vector<CoCompileJob> jobs;
  368. std::string sourceFile; // store --source=
  369. std::vector<std::string> launchers; // store --launcher=
  370. // Default is to run the original command found after -- if the option
  371. // does not need to do that, it should be specified here, currently only
  372. // lwyu does that.
  373. bool runOriginalCmd = true;
  374. std::vector<std::string> orig_cmd;
  375. bool doing_options = true;
  376. for (std::string const& arg : cmMakeRange(args).advance(2)) {
  377. // if the arg is -- then the rest of the args after
  378. // go into orig_cmd
  379. if (arg == "--") {
  380. doing_options = false;
  381. } else if (doing_options) {
  382. bool optionFound = false;
  383. for (CoCompiler const& cc : CoCompilers) {
  384. size_t optionLen = strlen(cc.Option);
  385. if (arg.compare(0, optionLen, cc.Option) == 0) {
  386. optionFound = true;
  387. CoCompileJob job;
  388. job.Command = arg.substr(optionLen);
  389. job.Handler = cc.Handler;
  390. jobs.push_back(std::move(job));
  391. if (cc.NoOriginalCommand) {
  392. runOriginalCmd = false;
  393. }
  394. }
  395. }
  396. if (!optionFound) {
  397. if (cmHasLiteralPrefix(arg, "--source=")) {
  398. sourceFile = arg.substr(9);
  399. } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
  400. cmExpandList(arg.substr(11), launchers, true);
  401. } else {
  402. // if it was not a co-compiler or --source/--launcher then error
  403. std::cerr << "__run_co_compile given unknown argument: " << arg
  404. << "\n";
  405. return 1;
  406. }
  407. }
  408. } else { // if not doing_options then push to orig_cmd
  409. orig_cmd.push_back(arg);
  410. }
  411. }
  412. if (jobs.empty()) {
  413. std::cerr << "__run_co_compile missing command to run. "
  414. "Looking for one or more of the following:\n";
  415. for (CoCompiler const& cc : CoCompilers) {
  416. std::cerr << cc.Option << "\n";
  417. }
  418. return 1;
  419. }
  420. if (runOriginalCmd && orig_cmd.empty()) {
  421. std::cerr << "__run_co_compile missing compile command after --\n";
  422. return 1;
  423. }
  424. for (CoCompileJob const& job : jobs) {
  425. // call the command handler here
  426. int ret = job.Handler(job.Command, sourceFile, orig_cmd);
  427. // if the command returns non-zero then return and fail.
  428. // for commands that do not want to break the build, they should return
  429. // 0 no matter what.
  430. if (ret != 0) {
  431. return ret;
  432. }
  433. }
  434. // if there is no original command to run return now
  435. if (!runOriginalCmd) {
  436. return 0;
  437. }
  438. // Prepend launcher argument(s), if any
  439. if (!launchers.empty()) {
  440. orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
  441. }
  442. // Now run the real compiler command and return its result value
  443. int ret;
  444. if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
  445. nullptr,
  446. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  447. std::cerr << "Error running '" << orig_cmd[0] << "'\n";
  448. return 1;
  449. }
  450. // return the return value from the original compiler command
  451. return ret;
  452. }
  453. int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args)
  454. {
  455. // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
  456. if (args.size() > 1) {
  457. // Copy file
  458. if (args[1] == "copy" && args.size() > 3) {
  459. // If multiple source files specified,
  460. // then destination must be directory
  461. if ((args.size() > 4) &&
  462. (!cmSystemTools::FileIsDirectory(args.back()))) {
  463. std::cerr << "Error: Target (for copy command) \"" << args.back()
  464. << "\" is not a directory.\n";
  465. return 1;
  466. }
  467. // If error occurs we want to continue copying next files.
  468. bool return_value = false;
  469. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  470. if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
  471. std::cerr << "Error copying file \"" << arg << "\" to \""
  472. << args.back() << "\".\n";
  473. return_value = true;
  474. }
  475. }
  476. return return_value;
  477. }
  478. // Copy file if different.
  479. if (args[1] == "copy_if_different" && args.size() > 3) {
  480. // If multiple source files specified,
  481. // then destination must be directory
  482. if ((args.size() > 4) &&
  483. (!cmSystemTools::FileIsDirectory(args.back()))) {
  484. std::cerr << "Error: Target (for copy_if_different command) \""
  485. << args.back() << "\" is not a directory.\n";
  486. return 1;
  487. }
  488. // If error occurs we want to continue copying next files.
  489. bool return_value = false;
  490. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  491. if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
  492. std::cerr << "Error copying file (if different) from \"" << arg
  493. << "\" to \"" << args.back() << "\".\n";
  494. return_value = true;
  495. }
  496. }
  497. return return_value;
  498. }
  499. // Copy directory content
  500. if (args[1] == "copy_directory" && args.size() > 3) {
  501. // If error occurs we want to continue copying next files.
  502. bool return_value = false;
  503. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  504. if (!cmSystemTools::CopyADirectory(arg, args.back())) {
  505. std::cerr << "Error copying directory from \"" << arg << "\" to \""
  506. << args.back() << "\".\n";
  507. return_value = true;
  508. }
  509. }
  510. return return_value;
  511. }
  512. // Rename a file or directory
  513. if (args[1] == "rename" && args.size() == 4) {
  514. if (!cmSystemTools::RenameFile(args[2], args[3])) {
  515. std::string e = cmSystemTools::GetLastSystemError();
  516. std::cerr << "Error renaming from \"" << args[2] << "\" to \""
  517. << args[3] << "\": " << e << "\n";
  518. return 1;
  519. }
  520. return 0;
  521. }
  522. // Compare files
  523. if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
  524. bool filesDiffer;
  525. if (args.size() == 4) {
  526. filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
  527. } else if (args[2] == "--ignore-eol") {
  528. filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
  529. } else {
  530. ::CMakeCommandUsage(args[0].c_str());
  531. return 1;
  532. }
  533. if (filesDiffer) {
  534. std::cerr << "Files \"" << args[args.size() - 2] << "\" to \""
  535. << args[args.size() - 1] << "\" are different.\n";
  536. return 1;
  537. }
  538. return 0;
  539. }
  540. #if !defined(CMAKE_BOOTSTRAP)
  541. if (args[1] == "__create_def") {
  542. if (args.size() < 4) {
  543. std::cerr << "__create_def Usage: -E __create_def outfile.def "
  544. "objlistfile [--nm=nm-path]\n";
  545. return 1;
  546. }
  547. cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
  548. if (!fin) {
  549. std::cerr << "could not open object list file: " << args[3].c_str()
  550. << "\n";
  551. return 1;
  552. }
  553. std::vector<std::string> files;
  554. {
  555. std::string file;
  556. cmFileTime outTime;
  557. bool outValid = outTime.Load(args[2]);
  558. while (cmSystemTools::GetLineFromStream(fin, file)) {
  559. files.push_back(file);
  560. if (outValid) {
  561. cmFileTime inTime;
  562. outValid = inTime.Load(file) && inTime.Older(outTime);
  563. }
  564. }
  565. if (outValid) {
  566. // The def file already exists and all input files are older than the
  567. // existing def file.
  568. return 0;
  569. }
  570. }
  571. FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
  572. if (!fout) {
  573. std::cerr << "could not open output .def file: " << args[2].c_str()
  574. << "\n";
  575. return 1;
  576. }
  577. bindexplib deffile;
  578. if (args.size() >= 5) {
  579. auto a = args[4];
  580. if (cmHasLiteralPrefix(a, "--nm=")) {
  581. deffile.SetNmPath(a.substr(5));
  582. std::cerr << a.substr(5) << "\n";
  583. } else {
  584. std::cerr << "unknown argument: " << a << "\n";
  585. }
  586. }
  587. for (auto const& file : files) {
  588. std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
  589. if (cmSystemTools::LowerCase(ext) == ".def") {
  590. if (!deffile.AddDefinitionFile(file.c_str())) {
  591. return 1;
  592. }
  593. } else {
  594. if (!deffile.AddObjectFile(file.c_str())) {
  595. return 1;
  596. }
  597. }
  598. }
  599. deffile.WriteFile(fout);
  600. fclose(fout);
  601. return 0;
  602. }
  603. #endif
  604. if (args[1] == "__run_co_compile") {
  605. return cmcmd::HandleCoCompileCommands(args);
  606. }
  607. // Echo string
  608. if (args[1] == "echo") {
  609. std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
  610. return 0;
  611. }
  612. // Echo string no new line
  613. if (args[1] == "echo_append") {
  614. std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
  615. return 0;
  616. }
  617. if (args[1] == "env") {
  618. auto ai = args.cbegin() + 2;
  619. auto ae = args.cend();
  620. for (; ai != ae; ++ai) {
  621. std::string const& a = *ai;
  622. if (cmHasLiteralPrefix(a, "--unset=")) {
  623. // Unset environment variable.
  624. cmSystemTools::UnPutEnv(a.substr(8));
  625. } else if (!a.empty() && a[0] == '-') {
  626. // Environment variable and command names cannot start in '-',
  627. // so this must be an unknown option.
  628. std::cerr << "cmake -E env: unknown option '" << a << "'"
  629. << std::endl;
  630. return 1;
  631. } else if (a.find('=') != std::string::npos) {
  632. // Set environment variable.
  633. cmSystemTools::PutEnv(a);
  634. } else {
  635. // This is the beginning of the command.
  636. break;
  637. }
  638. }
  639. if (ai == ae) {
  640. std::cerr << "cmake -E env: no command given" << std::endl;
  641. return 1;
  642. }
  643. // Execute command from remaining arguments.
  644. std::vector<std::string> cmd(ai, ae);
  645. int retval;
  646. if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
  647. nullptr,
  648. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  649. return retval;
  650. }
  651. return 1;
  652. }
  653. #if !defined(CMAKE_BOOTSTRAP)
  654. if (args[1] == "environment") {
  655. for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
  656. std::cout << env << std::endl;
  657. }
  658. return 0;
  659. }
  660. #endif
  661. if (args[1] == "make_directory" && args.size() > 2) {
  662. // If an error occurs, we want to continue making directories.
  663. bool return_value = false;
  664. for (auto const& arg : cmMakeRange(args).advance(2)) {
  665. if (!cmSystemTools::MakeDirectory(arg)) {
  666. std::cerr << "Error creating directory \"" << arg << "\".\n";
  667. return_value = true;
  668. }
  669. }
  670. return return_value;
  671. }
  672. if (args[1] == "remove_directory" && args.size() > 2) {
  673. // If an error occurs, we want to continue removing directories.
  674. bool return_value = false;
  675. for (auto const& arg : cmMakeRange(args).advance(2)) {
  676. if (cmSystemTools::FileIsDirectory(arg)) {
  677. if (!cmRemoveDirectory(arg)) {
  678. return_value = true;
  679. }
  680. }
  681. }
  682. return return_value;
  683. }
  684. // Remove file
  685. if (args[1] == "remove" && args.size() > 2) {
  686. bool force = false;
  687. for (auto const& arg : cmMakeRange(args).advance(2)) {
  688. if (arg == "\\-f" || arg == "-f") {
  689. force = true;
  690. } else {
  691. // Complain if the file could not be removed, still exists,
  692. // and the -f option was not given.
  693. if (!cmSystemTools::RemoveFile(arg) && !force &&
  694. cmSystemTools::FileExists(arg)) {
  695. return 1;
  696. }
  697. }
  698. }
  699. return 0;
  700. }
  701. // Remove directories or files with rm
  702. if (args[1] == "rm" && args.size() > 2) {
  703. // If an error occurs, we want to continue removing the remaining
  704. // files/directories.
  705. int return_value = 0;
  706. bool force = false;
  707. bool recursive = false;
  708. bool doing_options = true;
  709. bool at_least_one_file = false;
  710. for (auto const& arg : cmMakeRange(args).advance(2)) {
  711. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  712. if (arg == "--") {
  713. doing_options = false;
  714. }
  715. if (arg.find('f') != std::string::npos) {
  716. force = true;
  717. }
  718. if (arg.find_first_of("rR") != std::string::npos) {
  719. recursive = true;
  720. }
  721. if (arg.find_first_not_of("-frR") != std::string::npos) {
  722. cmSystemTools::Error("Unknown -E rm argument: " + arg);
  723. return 1;
  724. }
  725. } else {
  726. if (arg.empty()) {
  727. continue;
  728. }
  729. at_least_one_file = true;
  730. // Complain if the -f option was not given and
  731. // either file does not exist or
  732. // file could not be removed and still exists
  733. bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
  734. cmSystemTools::FileIsSymlink(arg) || force;
  735. if (cmSystemTools::FileIsDirectory(arg)) {
  736. if (!cmRemoveDirectory(arg, recursive)) {
  737. return_value = 1;
  738. }
  739. } else if ((!file_exists_or_forced_remove) ||
  740. (!cmSystemTools::RemoveFile(arg) &&
  741. cmSystemTools::FileExists(arg))) {
  742. if (!file_exists_or_forced_remove) {
  743. cmSystemTools::Error(
  744. "File to remove does not exist and force is not set: " + arg);
  745. } else {
  746. cmSystemTools::Error("File can't be removed and still exist: " +
  747. arg);
  748. }
  749. return_value = 1;
  750. }
  751. }
  752. }
  753. if (!at_least_one_file) {
  754. cmSystemTools::Error("Missing file/directory to remove");
  755. return 1;
  756. }
  757. return return_value;
  758. }
  759. // Touch file
  760. if (args[1] == "touch" && args.size() > 2) {
  761. for (auto const& arg : cmMakeRange(args).advance(2)) {
  762. if (!cmSystemTools::Touch(arg, true)) {
  763. std::cerr << "cmake -E touch: failed to update \"";
  764. std::cerr << arg << "\".\n";
  765. return 1;
  766. }
  767. }
  768. return 0;
  769. }
  770. // Touch file
  771. if (args[1] == "touch_nocreate" && args.size() > 2) {
  772. for (auto const& arg : cmMakeRange(args).advance(2)) {
  773. if (!cmSystemTools::Touch(arg, false)) {
  774. std::cerr << "cmake -E touch_nocreate: failed to update \"";
  775. std::cerr << arg << "\".\n";
  776. return 1;
  777. }
  778. }
  779. return 0;
  780. }
  781. // capabilities
  782. if (args[1] == "capabilities") {
  783. if (args.size() > 2) {
  784. std::cerr << "-E capabilities accepts no additional arguments\n";
  785. return 1;
  786. }
  787. cmake cm(cmake::RoleInternal, cmState::Unknown);
  788. std::cout << cm.ReportCapabilities();
  789. return 0;
  790. }
  791. // Sleep command
  792. if (args[1] == "sleep" && args.size() > 2) {
  793. double total = 0;
  794. for (auto const& arg : cmMakeRange(args).advance(2)) {
  795. double num = 0.0;
  796. char unit;
  797. char extra;
  798. int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
  799. if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
  800. total += num;
  801. } else {
  802. std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
  803. return 1;
  804. }
  805. }
  806. if (total > 0) {
  807. cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
  808. }
  809. return 0;
  810. }
  811. // Clock command
  812. if (args[1] == "time" && args.size() > 2) {
  813. std::vector<std::string> command(args.begin() + 2, args.end());
  814. clock_t clock_start;
  815. clock_t clock_finish;
  816. time_t time_start;
  817. time_t time_finish;
  818. time(&time_start);
  819. clock_start = clock();
  820. int ret = 0;
  821. cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
  822. clock_finish = clock();
  823. time(&time_finish);
  824. double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
  825. std::cout << "Elapsed time: "
  826. << static_cast<long>(time_finish - time_start) << " s. (time)"
  827. << ", "
  828. << static_cast<double>(clock_finish - clock_start) /
  829. clocks_per_sec
  830. << " s. (clock)"
  831. << "\n";
  832. return ret;
  833. }
  834. // Command to calculate the md5sum of a file
  835. if (args[1] == "md5sum" && args.size() >= 3) {
  836. return HashSumFile(args, cmCryptoHash::AlgoMD5);
  837. }
  838. // Command to calculate the sha1sum of a file
  839. if (args[1] == "sha1sum" && args.size() >= 3) {
  840. return HashSumFile(args, cmCryptoHash::AlgoSHA1);
  841. }
  842. if (args[1] == "sha224sum" && args.size() >= 3) {
  843. return HashSumFile(args, cmCryptoHash::AlgoSHA224);
  844. }
  845. if (args[1] == "sha256sum" && args.size() >= 3) {
  846. return HashSumFile(args, cmCryptoHash::AlgoSHA256);
  847. }
  848. if (args[1] == "sha384sum" && args.size() >= 3) {
  849. return HashSumFile(args, cmCryptoHash::AlgoSHA384);
  850. }
  851. if (args[1] == "sha512sum" && args.size() >= 3) {
  852. return HashSumFile(args, cmCryptoHash::AlgoSHA512);
  853. }
  854. // Command to change directory and run a program.
  855. if (args[1] == "chdir" && args.size() >= 4) {
  856. std::string const& directory = args[2];
  857. if (!cmSystemTools::FileExists(directory)) {
  858. cmSystemTools::Error("Directory does not exist for chdir command: " +
  859. args[2]);
  860. return 1;
  861. }
  862. std::string command =
  863. cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
  864. int retval = 0;
  865. if (cmSystemTools::RunSingleCommand(
  866. command, nullptr, nullptr, &retval, directory.c_str(),
  867. cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
  868. return retval;
  869. }
  870. return 1;
  871. }
  872. // Command to start progress for a build
  873. if (args[1] == "cmake_progress_start" && args.size() == 4) {
  874. // basically remove the directory
  875. std::string dirName = cmStrCat(args[2], "/Progress");
  876. cmSystemTools::RemoveADirectory(dirName);
  877. // is the last argument a filename that exists?
  878. FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
  879. int count;
  880. if (countFile) {
  881. if (1 != fscanf(countFile, "%i", &count)) {
  882. cmSystemTools::Message("Could not read from count file.");
  883. }
  884. fclose(countFile);
  885. } else {
  886. count = atoi(args[3].c_str());
  887. }
  888. if (count) {
  889. cmSystemTools::MakeDirectory(dirName);
  890. // write the count into the directory
  891. std::string fName = cmStrCat(dirName, "/count.txt");
  892. FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
  893. if (progFile) {
  894. fprintf(progFile, "%i\n", count);
  895. fclose(progFile);
  896. }
  897. }
  898. return 0;
  899. }
  900. // Command to report progress for a build
  901. if (args[1] == "cmake_progress_report" && args.size() >= 3) {
  902. // This has been superseded by cmake_echo_color --progress-*
  903. // options. We leave it here to avoid errors if somehow this
  904. // is invoked by an existing makefile without regenerating.
  905. return 0;
  906. }
  907. // Command to create a symbolic link. Fails on platforms not
  908. // supporting them.
  909. if (args[1] == "create_symlink" && args.size() == 4) {
  910. const char* destinationFileName = args[3].c_str();
  911. if ((cmSystemTools::FileExists(destinationFileName) ||
  912. cmSystemTools::FileIsSymlink(destinationFileName)) &&
  913. !cmSystemTools::RemoveFile(destinationFileName)) {
  914. std::string emsg = cmSystemTools::GetLastSystemError();
  915. std::cerr << "failed to create symbolic link '" << destinationFileName
  916. << "' because existing path cannot be removed: " << emsg
  917. << "\n";
  918. return 1;
  919. }
  920. if (!cmSystemTools::CreateSymlink(args[2], args[3])) {
  921. return 1;
  922. }
  923. return 0;
  924. }
  925. // Command to do nothing with an exit code of 0.
  926. if (args[1] == "true") {
  927. return 0;
  928. }
  929. // Command to do nothing with an exit code of 1.
  930. if (args[1] == "false") {
  931. return 1;
  932. }
  933. // Internal CMake shared library support.
  934. if (args[1] == "cmake_symlink_library" && args.size() == 5) {
  935. return cmcmd::SymlinkLibrary(args);
  936. }
  937. // Internal CMake versioned executable support.
  938. if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
  939. return cmcmd::SymlinkExecutable(args);
  940. }
  941. // Internal CMake dependency scanning support.
  942. if (args[1] == "cmake_depends" && args.size() >= 6) {
  943. const bool verbose = isCMakeVerbose();
  944. // Create a cmake object instance to process dependencies.
  945. // All we need is the `set` command.
  946. cmake cm(cmake::RoleScript, cmState::Unknown);
  947. std::string gen;
  948. std::string homeDir;
  949. std::string startDir;
  950. std::string homeOutDir;
  951. std::string startOutDir;
  952. std::string depInfo;
  953. bool color = false;
  954. if (args.size() >= 8) {
  955. // Full signature:
  956. //
  957. // -E cmake_depends <generator>
  958. // <home-src-dir> <start-src-dir>
  959. // <home-out-dir> <start-out-dir>
  960. // <dep-info> [--color=$(COLOR)]
  961. //
  962. // All paths are provided.
  963. gen = args[2];
  964. homeDir = args[3];
  965. startDir = args[4];
  966. homeOutDir = args[5];
  967. startOutDir = args[6];
  968. depInfo = args[7];
  969. if (args.size() >= 9 && args[8].length() >= 8 &&
  970. args[8].substr(0, 8) == "--color=") {
  971. // Enable or disable color based on the switch value.
  972. color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
  973. }
  974. } else {
  975. // Support older signature for existing makefiles:
  976. //
  977. // -E cmake_depends <generator>
  978. // <home-out-dir> <start-out-dir>
  979. // <dep-info>
  980. //
  981. // Just pretend the source directories are the same as the
  982. // binary directories so at least scanning will work.
  983. gen = args[2];
  984. homeDir = args[3];
  985. startDir = args[4];
  986. homeOutDir = args[3];
  987. startOutDir = args[3];
  988. depInfo = args[5];
  989. }
  990. // Create a local generator configured for the directory in
  991. // which dependencies will be scanned.
  992. homeDir = cmSystemTools::CollapseFullPath(homeDir);
  993. startDir = cmSystemTools::CollapseFullPath(startDir);
  994. homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
  995. startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
  996. cm.SetHomeDirectory(homeDir);
  997. cm.SetHomeOutputDirectory(homeOutDir);
  998. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  999. if (auto ggd = cm.CreateGlobalGenerator(gen)) {
  1000. cm.SetGlobalGenerator(std::move(ggd));
  1001. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1002. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1003. snapshot.GetDirectory().SetCurrentSource(startDir);
  1004. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1005. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1006. // Actually scan dependencies.
  1007. return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
  1008. }
  1009. return 1;
  1010. }
  1011. // Internal CMake link script support.
  1012. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1013. return cmcmd::ExecuteLinkScript(args);
  1014. }
  1015. #ifndef CMAKE_BOOTSTRAP
  1016. // Internal CMake ninja dependency scanning support.
  1017. if (args[1] == "cmake_ninja_depends") {
  1018. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1019. }
  1020. // Internal CMake ninja dyndep support.
  1021. if (args[1] == "cmake_ninja_dyndep") {
  1022. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1023. }
  1024. #endif
  1025. // Internal CMake unimplemented feature notification.
  1026. if (args[1] == "cmake_unimplemented_variable") {
  1027. std::cerr << "Feature not implemented for this platform.";
  1028. if (args.size() == 3) {
  1029. std::cerr << " Variable " << args[2] << " is not set.";
  1030. }
  1031. std::cerr << std::endl;
  1032. return 1;
  1033. }
  1034. if (args[1] == "vs_link_exe") {
  1035. return cmcmd::VisualStudioLink(args, 1);
  1036. }
  1037. if (args[1] == "vs_link_dll") {
  1038. return cmcmd::VisualStudioLink(args, 2);
  1039. }
  1040. if (args[1] == "cmake_llvm_rc") {
  1041. return cmcmd::RunLLVMRC(args);
  1042. }
  1043. // Internal CMake color makefile support.
  1044. if (args[1] == "cmake_echo_color") {
  1045. return cmcmd::ExecuteEchoColor(args);
  1046. }
  1047. #ifndef CMAKE_BOOTSTRAP
  1048. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1049. cm::string_view const infoFile = args[2];
  1050. cm::string_view const config = args[3];
  1051. return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
  1052. }
  1053. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1054. cm::string_view const infoFile = args[2];
  1055. cm::string_view const config =
  1056. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1057. return cmQtAutoRcc(infoFile, config) ? 0 : 1;
  1058. }
  1059. #endif
  1060. // Tar files
  1061. if (args[1] == "tar" && args.size() > 3) {
  1062. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1063. std::string const& flags = args[2];
  1064. std::string const& outFile = args[3];
  1065. std::vector<std::string> files;
  1066. std::string mtime;
  1067. std::string format;
  1068. cmSystemTools::cmTarCompression compress =
  1069. cmSystemTools::TarCompressNone;
  1070. int nCompress = 0;
  1071. bool doing_options = true;
  1072. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1073. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1074. if (arg == "--") {
  1075. doing_options = false;
  1076. } else if (arg == "--zstd") {
  1077. compress = cmSystemTools::TarCompressZstd;
  1078. ++nCompress;
  1079. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1080. mtime = arg.substr(8);
  1081. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1082. std::string const& files_from = arg.substr(13);
  1083. if (!cmTarFilesFrom(files_from, files)) {
  1084. return 1;
  1085. }
  1086. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1087. format = arg.substr(9);
  1088. if (!cmContains(knownFormats, format)) {
  1089. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1090. format);
  1091. return 1;
  1092. }
  1093. } else {
  1094. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1095. return 1;
  1096. }
  1097. } else {
  1098. files.push_back(arg);
  1099. }
  1100. }
  1101. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1102. bool verbose = false;
  1103. for (auto flag : flags) {
  1104. switch (flag) {
  1105. case '-':
  1106. case 'f': {
  1107. // Keep for backward compatibility. Ignored
  1108. } break;
  1109. case 'j': {
  1110. compress = cmSystemTools::TarCompressBZip2;
  1111. ++nCompress;
  1112. } break;
  1113. case 'J': {
  1114. compress = cmSystemTools::TarCompressXZ;
  1115. ++nCompress;
  1116. } break;
  1117. case 'z': {
  1118. compress = cmSystemTools::TarCompressGZip;
  1119. ++nCompress;
  1120. } break;
  1121. case 'v': {
  1122. verbose = true;
  1123. } break;
  1124. case 't': {
  1125. action = cmSystemTools::TarActionList;
  1126. } break;
  1127. case 'c': {
  1128. action = cmSystemTools::TarActionCreate;
  1129. } break;
  1130. case 'x': {
  1131. action = cmSystemTools::TarActionExtract;
  1132. } break;
  1133. default: {
  1134. cmSystemTools::Message(
  1135. std::string("tar: Unknown argument: ") + flag, "Warning");
  1136. }
  1137. }
  1138. }
  1139. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1140. cmSystemTools::Error("Can not use compression flags with format: " +
  1141. format);
  1142. return 1;
  1143. }
  1144. if (nCompress > 1) {
  1145. cmSystemTools::Error("Can only compress a tar file one way; "
  1146. "at most one flag of z, j, or J may be used");
  1147. return 1;
  1148. }
  1149. if (action == cmSystemTools::TarActionList) {
  1150. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1151. cmSystemTools::Error("Problem listing tar: " + outFile);
  1152. return 1;
  1153. }
  1154. } else if (action == cmSystemTools::TarActionCreate) {
  1155. if (files.empty()) {
  1156. cmSystemTools::Message("tar: No files or directories specified",
  1157. "Warning");
  1158. }
  1159. if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
  1160. format)) {
  1161. cmSystemTools::Error("Problem creating tar: " + outFile);
  1162. return 1;
  1163. }
  1164. } else if (action == cmSystemTools::TarActionExtract) {
  1165. if (!cmSystemTools::ExtractTar(outFile, files, verbose)) {
  1166. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1167. return 1;
  1168. }
  1169. #ifdef WIN32
  1170. // OK, on windows 7 after we untar some files,
  1171. // sometimes we can not rename the directory after
  1172. // the untar is done. This breaks the external project
  1173. // untar and rename code. So, by default we will wait
  1174. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1175. // is set in the env, its value will be used instead of 100.
  1176. int delay = 100;
  1177. std::string delayVar;
  1178. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1179. delay = atoi(delayVar.c_str());
  1180. }
  1181. if (delay) {
  1182. cmSystemTools::Delay(delay);
  1183. }
  1184. #endif
  1185. } else {
  1186. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1187. "(list), 'c' (create) or 'x' (extract)");
  1188. return 1;
  1189. }
  1190. return 0;
  1191. }
  1192. if (args[1] == "server") {
  1193. const std::string pipePrefix = "--pipe=";
  1194. bool supportExperimental = false;
  1195. bool isDebug = false;
  1196. std::string pipe;
  1197. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1198. if (arg == "--experimental") {
  1199. supportExperimental = true;
  1200. } else if (arg == "--debug") {
  1201. pipe.clear();
  1202. isDebug = true;
  1203. } else if (arg.substr(0, pipePrefix.size()) == pipePrefix) {
  1204. isDebug = false;
  1205. pipe = arg.substr(pipePrefix.size());
  1206. if (pipe.empty()) {
  1207. cmSystemTools::Error("No pipe given after --pipe=");
  1208. return 2;
  1209. }
  1210. } else {
  1211. cmSystemTools::Error("Unknown argument for server mode");
  1212. return 1;
  1213. }
  1214. }
  1215. #if !defined(CMAKE_BOOTSTRAP)
  1216. cmConnection* conn;
  1217. if (isDebug) {
  1218. conn = new cmServerStdIoConnection;
  1219. } else {
  1220. conn = new cmServerPipeConnection(pipe);
  1221. }
  1222. cmServer server(conn, supportExperimental);
  1223. std::string errorMessage;
  1224. if (server.Serve(&errorMessage)) {
  1225. return 0;
  1226. }
  1227. cmSystemTools::Error(errorMessage);
  1228. #else
  1229. static_cast<void>(supportExperimental);
  1230. static_cast<void>(isDebug);
  1231. cmSystemTools::Error("CMake was not built with server mode enabled");
  1232. #endif
  1233. return 1;
  1234. }
  1235. #if !defined(CMAKE_BOOTSTRAP)
  1236. // Internal CMake Fortran module support.
  1237. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1238. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1239. }
  1240. #endif
  1241. #if defined(_WIN32) && !defined(__CYGWIN__)
  1242. // Write registry value
  1243. if (args[1] == "write_regv" && args.size() > 3) {
  1244. return cmSystemTools::WriteRegistryValue(args[2].c_str(),
  1245. args[3].c_str())
  1246. ? 0
  1247. : 1;
  1248. }
  1249. // Delete registry value
  1250. if (args[1] == "delete_regv" && args.size() > 2) {
  1251. return cmSystemTools::DeleteRegistryValue(args[2].c_str()) ? 0 : 1;
  1252. }
  1253. // Remove file
  1254. if (args[1] == "comspec" && args.size() > 2) {
  1255. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1256. return 1;
  1257. }
  1258. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1259. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1260. }
  1261. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1262. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1263. }
  1264. #endif
  1265. }
  1266. ::CMakeCommandUsage(args[0].c_str());
  1267. return 1;
  1268. }
  1269. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1270. cmCryptoHash::Algo algo)
  1271. {
  1272. if (args.size() < 3) {
  1273. return -1;
  1274. }
  1275. int retval = 0;
  1276. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1277. // Cannot compute sum of a directory
  1278. if (cmSystemTools::FileIsDirectory(filename)) {
  1279. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1280. retval++;
  1281. } else {
  1282. std::string value = cmSystemTools::ComputeFileHash(filename, algo);
  1283. if (value.empty()) {
  1284. // To mimic "md5sum/shasum" behavior in a shell:
  1285. std::cerr << filename << ": No such file or directory" << std::endl;
  1286. retval++;
  1287. } else {
  1288. std::cout << value << " " << filename << std::endl;
  1289. }
  1290. }
  1291. }
  1292. return retval;
  1293. }
  1294. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1295. {
  1296. int result = 0;
  1297. std::string realName = args[2];
  1298. std::string soName = args[3];
  1299. std::string name = args[4];
  1300. cmSystemTools::ConvertToUnixSlashes(realName);
  1301. cmSystemTools::ConvertToUnixSlashes(soName);
  1302. cmSystemTools::ConvertToUnixSlashes(name);
  1303. if (soName != realName) {
  1304. if (!cmcmd::SymlinkInternal(realName, soName)) {
  1305. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1306. result = 1;
  1307. }
  1308. }
  1309. if (name != soName) {
  1310. if (!cmcmd::SymlinkInternal(soName, name)) {
  1311. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1312. result = 1;
  1313. }
  1314. }
  1315. return result;
  1316. }
  1317. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1318. {
  1319. int result = 0;
  1320. std::string const& realName = args[2];
  1321. std::string const& name = args[3];
  1322. if (name != realName) {
  1323. if (!cmcmd::SymlinkInternal(realName, name)) {
  1324. cmSystemTools::ReportLastSystemError("cmake_symlink_executable");
  1325. result = 1;
  1326. }
  1327. }
  1328. return result;
  1329. }
  1330. bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link)
  1331. {
  1332. if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
  1333. cmSystemTools::RemoveFile(link);
  1334. }
  1335. #if defined(_WIN32) && !defined(__CYGWIN__)
  1336. return cmSystemTools::CopyFileAlways(file, link);
  1337. #else
  1338. std::string linktext = cmSystemTools::GetFilenameName(file);
  1339. return cmSystemTools::CreateSymlink(linktext, link);
  1340. #endif
  1341. }
  1342. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1343. {
  1344. std::string dirName = cmStrCat(dir, "/Progress");
  1345. std::string fName;
  1346. FILE* progFile;
  1347. // read the count
  1348. fName = cmStrCat(dirName, "/count.txt");
  1349. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1350. int count = 0;
  1351. if (!progFile) {
  1352. return;
  1353. }
  1354. if (1 != fscanf(progFile, "%i", &count)) {
  1355. cmSystemTools::Message("Could not read from progress file.");
  1356. }
  1357. fclose(progFile);
  1358. const char* last = num.c_str();
  1359. for (const char* c = last;; ++c) {
  1360. if (*c == ',' || *c == '\0') {
  1361. if (c != last) {
  1362. fName = cmStrCat(dirName, '/');
  1363. fName.append(last, c - last);
  1364. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1365. if (progFile) {
  1366. fprintf(progFile, "empty");
  1367. fclose(progFile);
  1368. }
  1369. }
  1370. if (*c == '\0') {
  1371. break;
  1372. }
  1373. last = c + 1;
  1374. }
  1375. }
  1376. int fileNum =
  1377. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1378. if (count > 0) {
  1379. // print the progress
  1380. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1381. }
  1382. }
  1383. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1384. {
  1385. // The arguments are
  1386. // args[0] == <cmake-executable>
  1387. // args[1] == cmake_echo_color
  1388. bool enabled = true;
  1389. int color = cmsysTerminal_Color_Normal;
  1390. bool newline = true;
  1391. std::string progressDir;
  1392. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1393. if (arg.find("--switch=") == 0) {
  1394. // Enable or disable color based on the switch value.
  1395. std::string value = arg.substr(9);
  1396. if (!value.empty()) {
  1397. enabled = cmIsOn(value);
  1398. }
  1399. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1400. progressDir = arg.substr(15);
  1401. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1402. if (!progressDir.empty()) {
  1403. std::string const& progressNum = arg.substr(15);
  1404. cmcmdProgressReport(progressDir, progressNum);
  1405. }
  1406. } else if (arg == "--normal") {
  1407. color = cmsysTerminal_Color_Normal;
  1408. } else if (arg == "--black") {
  1409. color = cmsysTerminal_Color_ForegroundBlack;
  1410. } else if (arg == "--red") {
  1411. color = cmsysTerminal_Color_ForegroundRed;
  1412. } else if (arg == "--green") {
  1413. color = cmsysTerminal_Color_ForegroundGreen;
  1414. } else if (arg == "--yellow") {
  1415. color = cmsysTerminal_Color_ForegroundYellow;
  1416. } else if (arg == "--blue") {
  1417. color = cmsysTerminal_Color_ForegroundBlue;
  1418. } else if (arg == "--magenta") {
  1419. color = cmsysTerminal_Color_ForegroundMagenta;
  1420. } else if (arg == "--cyan") {
  1421. color = cmsysTerminal_Color_ForegroundCyan;
  1422. } else if (arg == "--white") {
  1423. color = cmsysTerminal_Color_ForegroundWhite;
  1424. } else if (arg == "--bold") {
  1425. color |= cmsysTerminal_Color_ForegroundBold;
  1426. } else if (arg == "--no-newline") {
  1427. newline = false;
  1428. } else if (arg == "--newline") {
  1429. newline = true;
  1430. } else {
  1431. // Color is enabled. Print with the current color.
  1432. cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
  1433. }
  1434. }
  1435. return 0;
  1436. }
  1437. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1438. {
  1439. // The arguments are
  1440. // args[0] == <cmake-executable>
  1441. // args[1] == cmake_link_script
  1442. // args[2] == <link-script-name>
  1443. // args[3] == --verbose=?
  1444. bool verbose = false;
  1445. if (args.size() >= 4) {
  1446. if (args[3].find("--verbose=") == 0) {
  1447. if (!cmIsOff(args[3].substr(10))) {
  1448. verbose = true;
  1449. }
  1450. }
  1451. }
  1452. // Allocate a process instance.
  1453. cmsysProcess* cp = cmsysProcess_New();
  1454. if (!cp) {
  1455. std::cerr << "Error allocating process instance in link script."
  1456. << std::endl;
  1457. return 1;
  1458. }
  1459. // Children should share stdout and stderr with this process.
  1460. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  1461. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  1462. // Run the command lines verbatim.
  1463. cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
  1464. // Read command lines from the script.
  1465. cmsys::ifstream fin(args[2].c_str());
  1466. if (!fin) {
  1467. std::cerr << "Error opening link script \"" << args[2] << "\""
  1468. << std::endl;
  1469. return 1;
  1470. }
  1471. // Run one command at a time.
  1472. std::string command;
  1473. int result = 0;
  1474. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1475. // Skip empty command lines.
  1476. if (command.find_first_not_of(" \t") == std::string::npos) {
  1477. continue;
  1478. }
  1479. // Setup this command line.
  1480. const char* cmd[2] = { command.c_str(), nullptr };
  1481. cmsysProcess_SetCommand(cp, cmd);
  1482. // Report the command if verbose output is enabled.
  1483. if (verbose) {
  1484. std::cout << command << std::endl;
  1485. }
  1486. // Run the command and wait for it to exit.
  1487. cmsysProcess_Execute(cp);
  1488. cmsysProcess_WaitForExit(cp, nullptr);
  1489. // Report failure if any.
  1490. switch (cmsysProcess_GetState(cp)) {
  1491. case cmsysProcess_State_Exited: {
  1492. int value = cmsysProcess_GetExitValue(cp);
  1493. if (value != 0) {
  1494. result = value;
  1495. }
  1496. } break;
  1497. case cmsysProcess_State_Exception:
  1498. std::cerr << "Error running link command: "
  1499. << cmsysProcess_GetExceptionString(cp) << std::endl;
  1500. result = 1;
  1501. break;
  1502. case cmsysProcess_State_Error:
  1503. std::cerr << "Error running link command: "
  1504. << cmsysProcess_GetErrorString(cp) << std::endl;
  1505. result = 2;
  1506. break;
  1507. default:
  1508. break;
  1509. }
  1510. }
  1511. // Free the process instance.
  1512. cmsysProcess_Delete(cp);
  1513. // Return the final resulting return value.
  1514. return result;
  1515. }
  1516. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1517. {
  1518. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1519. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1520. parser.ParseVersion(version);
  1521. if (parser.Found()) {
  1522. std::cout << "@echo off" << std::endl;
  1523. std::cout << "echo Environment Selection: " << name << std::endl;
  1524. std::cout << "set PATH=" << parser.GetPathDirectories() << std::endl;
  1525. std::cout << "set INCLUDE=" << parser.GetIncludeDirectories() << std::endl;
  1526. std::cout << "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1527. return 0;
  1528. }
  1529. #else
  1530. (void)version;
  1531. #endif
  1532. std::cerr << "Could not find " << name;
  1533. return -1;
  1534. }
  1535. int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
  1536. const std::string& intermediate_file)
  1537. {
  1538. cmUVProcessChainBuilder builder;
  1539. uv_fs_t fs_req;
  1540. int preprocessedFile =
  1541. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1542. 0644, nullptr);
  1543. uv_fs_req_cleanup(&fs_req);
  1544. builder
  1545. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1546. preprocessedFile)
  1547. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1548. .AddCommand(command);
  1549. auto process = builder.Start();
  1550. if (!process.Valid()) {
  1551. std::cerr << "Failed to start preprocessor.";
  1552. return 1;
  1553. }
  1554. if (!process.Wait()) {
  1555. std::cerr << "Failed to wait for preprocessor";
  1556. return 1;
  1557. }
  1558. auto status = process.GetStatus();
  1559. if (!status[0] || status[0]->ExitStatus != 0) {
  1560. auto errorStream = process.ErrorStream();
  1561. if (errorStream) {
  1562. std::cerr << errorStream->rdbuf();
  1563. }
  1564. return 1;
  1565. }
  1566. return 0;
  1567. }
  1568. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1569. {
  1570. // The arguments are
  1571. // args[0] == <cmake-executable>
  1572. // args[1] == cmake_llvm_rc
  1573. // args[2] == source_file_path
  1574. // args[3] == intermediate_file
  1575. // args[4..n] == preprocess+args
  1576. // args[n+1] == --
  1577. // args[n+2...] == llvm-rc+args
  1578. if (args.size() < 3) {
  1579. std::cerr << "Invalid cmake_llvm_rc arguments";
  1580. return 1;
  1581. }
  1582. const std::string& intermediate_file = args[3];
  1583. const std::string& source_file = args[2];
  1584. std::vector<std::string> preprocess;
  1585. std::vector<std::string> resource_compile;
  1586. std::vector<std::string>* pArgTgt = &preprocess;
  1587. for (std::string const& arg : cmMakeRange(args).advance(4)) {
  1588. if (arg == "--") {
  1589. pArgTgt = &resource_compile;
  1590. } else {
  1591. if (arg.find("SOURCE_DIR") != std::string::npos) {
  1592. std::string sourceDirArg = arg;
  1593. cmSystemTools::ReplaceString(
  1594. sourceDirArg, "SOURCE_DIR",
  1595. cmSystemTools::GetFilenamePath(source_file));
  1596. pArgTgt->push_back(sourceDirArg);
  1597. } else {
  1598. pArgTgt->push_back(arg);
  1599. }
  1600. }
  1601. }
  1602. if (preprocess.empty()) {
  1603. std::cerr << "Empty preprocessing command";
  1604. return 1;
  1605. }
  1606. if (resource_compile.empty()) {
  1607. std::cerr << "Empty resource compilation command";
  1608. return 1;
  1609. }
  1610. auto result = RunPreprocessor(preprocess, intermediate_file);
  1611. if (result != 0) {
  1612. cmSystemTools::RemoveFile(intermediate_file);
  1613. return result;
  1614. }
  1615. cmUVProcessChainBuilder builder;
  1616. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  1617. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1618. .AddCommand(resource_compile);
  1619. auto process = builder.Start();
  1620. result = 0;
  1621. if (!process.Valid()) {
  1622. std::cerr << "Failed to start resource compiler.";
  1623. result = 1;
  1624. } else {
  1625. if (!process.Wait()) {
  1626. std::cerr << "Failed to wait for resource compiler";
  1627. result = 1;
  1628. }
  1629. }
  1630. cmSystemTools::RemoveFile(intermediate_file);
  1631. if (result != 0) {
  1632. return result;
  1633. }
  1634. auto status = process.GetStatus();
  1635. if (!status[0] || status[0]->ExitStatus != 0) {
  1636. auto errorStream = process.ErrorStream();
  1637. if (errorStream) {
  1638. std::cerr << errorStream->rdbuf();
  1639. }
  1640. return 1;
  1641. }
  1642. return 0;
  1643. }
  1644. class cmVSLink
  1645. {
  1646. int Type;
  1647. bool Verbose;
  1648. bool Incremental;
  1649. bool LinkGeneratesManifest;
  1650. std::vector<std::string> LinkCommand;
  1651. std::vector<std::string> UserManifests;
  1652. std::string LinkerManifestFile;
  1653. std::string ManifestFile;
  1654. std::string ManifestFileRC;
  1655. std::string ManifestFileRes;
  1656. std::string TargetFile;
  1657. std::string MtPath;
  1658. std::string RcPath;
  1659. public:
  1660. cmVSLink(int type, bool verbose)
  1661. : Type(type)
  1662. , Verbose(verbose)
  1663. , Incremental(false)
  1664. , LinkGeneratesManifest(true)
  1665. {
  1666. }
  1667. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1668. std::vector<std::string>::const_iterator argEnd);
  1669. int Link();
  1670. private:
  1671. int LinkIncremental();
  1672. int LinkNonIncremental();
  1673. int RunMT(std::string const& out, bool notify);
  1674. };
  1675. // For visual studio 2005 and newer manifest files need to be embedded into
  1676. // exe and dll's. This code does that in such a way that incremental linking
  1677. // still works.
  1678. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1679. {
  1680. #if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP)
  1681. // Replace streambuf so we output in the system codepage. CMake is set up
  1682. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1683. // outputs using the system codepage so we need to change behavior when
  1684. // we run the link command.
  1685. cmsys::ConsoleBuf::Manager consoleOut(std::cout);
  1686. cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
  1687. #endif
  1688. if (args.size() < 2) {
  1689. return -1;
  1690. }
  1691. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  1692. std::vector<std::string> expandedArgs;
  1693. for (std::string const& i : args) {
  1694. // check for nmake temporary files
  1695. if (i[0] == '@' && i.find("@CMakeFiles") != 0) {
  1696. cmsys::ifstream fin(i.substr(1).c_str());
  1697. std::string line;
  1698. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1699. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  1700. }
  1701. } else {
  1702. expandedArgs.push_back(i);
  1703. }
  1704. }
  1705. cmVSLink vsLink(type, verbose);
  1706. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  1707. return -1;
  1708. }
  1709. return vsLink.Link();
  1710. }
  1711. enum NumberFormat
  1712. {
  1713. FORMAT_DECIMAL,
  1714. FORMAT_HEX
  1715. };
  1716. struct NumberFormatter
  1717. {
  1718. NumberFormat Format;
  1719. int Value;
  1720. NumberFormatter(NumberFormat format, int value)
  1721. : Format(format)
  1722. , Value(value)
  1723. {
  1724. }
  1725. };
  1726. std::ostream& operator<<(std::ostream& stream,
  1727. NumberFormatter const& formatter)
  1728. {
  1729. auto const& flags = stream.flags();
  1730. if (formatter.Format == FORMAT_DECIMAL) {
  1731. stream << std::dec << formatter.Value;
  1732. } else {
  1733. stream << "0x" << std::hex << formatter.Value;
  1734. }
  1735. stream.flags(flags);
  1736. return stream;
  1737. }
  1738. static bool RunCommand(const char* comment,
  1739. std::vector<std::string> const& command, bool verbose,
  1740. NumberFormat exitFormat, int* retCodeOut = nullptr,
  1741. bool (*retCodeOkay)(int) = nullptr)
  1742. {
  1743. if (verbose) {
  1744. std::cout << comment << ":\n";
  1745. std::cout << cmJoin(command, " ") << "\n";
  1746. }
  1747. std::string output;
  1748. int retCode = 0;
  1749. bool commandResult = cmSystemTools::RunSingleCommand(
  1750. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  1751. bool const retCodeSuccess =
  1752. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  1753. bool const success = commandResult && retCodeSuccess;
  1754. if (retCodeOut) {
  1755. if (commandResult || !retCodeSuccess) {
  1756. *retCodeOut = retCode;
  1757. } else {
  1758. *retCodeOut = -1;
  1759. }
  1760. }
  1761. if (!success) {
  1762. std::cout << comment << ": command \"" << cmJoin(command, " ")
  1763. << "\" failed (exit code "
  1764. << NumberFormatter(exitFormat, retCode)
  1765. << ") with the following output:\n"
  1766. << output;
  1767. } else {
  1768. // always print the output of the command, unless
  1769. // it is the dumb rc command banner
  1770. if (output.find("Resource Compiler Version") == std::string::npos) {
  1771. std::cout << output;
  1772. }
  1773. }
  1774. return success;
  1775. }
  1776. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  1777. std::vector<std::string>::const_iterator argEnd)
  1778. {
  1779. // Parse our own arguments.
  1780. std::string intDir;
  1781. auto arg = argBeg;
  1782. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  1783. if (*arg == "--") {
  1784. ++arg;
  1785. break;
  1786. }
  1787. if (*arg == "--manifests") {
  1788. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  1789. this->UserManifests.push_back(*arg);
  1790. }
  1791. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  1792. intDir = arg->substr(9);
  1793. ++arg;
  1794. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  1795. this->RcPath = arg->substr(5);
  1796. ++arg;
  1797. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  1798. this->MtPath = arg->substr(5);
  1799. ++arg;
  1800. } else {
  1801. std::cerr << "unknown argument '" << *arg << "'\n";
  1802. return false;
  1803. }
  1804. }
  1805. if (intDir.empty()) {
  1806. return false;
  1807. }
  1808. // The rest of the arguments form the link command.
  1809. if (arg == argEnd) {
  1810. return false;
  1811. }
  1812. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  1813. // Parse the link command to extract information we need.
  1814. for (; arg != argEnd; ++arg) {
  1815. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0) {
  1816. this->Incremental = true;
  1817. } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
  1818. this->Incremental = true;
  1819. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
  1820. this->LinkGeneratesManifest = false;
  1821. } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
  1822. this->TargetFile = arg->substr(3);
  1823. } else if (cmHasLiteralPrefix(*arg, "/out:")) {
  1824. this->TargetFile = arg->substr(5);
  1825. }
  1826. }
  1827. if (this->TargetFile.empty()) {
  1828. return false;
  1829. }
  1830. this->ManifestFile = intDir + "/embed.manifest";
  1831. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  1832. if (this->Incremental) {
  1833. // We will compile a resource containing the manifest and
  1834. // pass it to the link command.
  1835. this->ManifestFileRC = intDir + "/manifest.rc";
  1836. this->ManifestFileRes = intDir + "/manifest.res";
  1837. } else if (this->UserManifests.empty()) {
  1838. // Prior to support for user-specified manifests CMake placed the
  1839. // linker-generated manifest next to the binary (as if it were not to be
  1840. // embedded) when not linking incrementally. Preserve this behavior.
  1841. this->ManifestFile = this->TargetFile + ".manifest";
  1842. this->LinkerManifestFile = this->ManifestFile;
  1843. }
  1844. if (this->LinkGeneratesManifest) {
  1845. this->LinkCommand.emplace_back("/MANIFEST");
  1846. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  1847. }
  1848. return true;
  1849. }
  1850. int cmVSLink::Link()
  1851. {
  1852. if (this->Incremental &&
  1853. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  1854. if (this->Verbose) {
  1855. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  1856. }
  1857. return LinkIncremental();
  1858. }
  1859. if (this->Verbose) {
  1860. if (!this->Incremental) {
  1861. std::cout << "Visual Studio Non-Incremental Link\n";
  1862. } else {
  1863. std::cout << "Visual Studio Incremental Link without manifests\n";
  1864. }
  1865. }
  1866. return LinkNonIncremental();
  1867. }
  1868. static bool mtRetIsUpdate(int mtRet)
  1869. {
  1870. // 'mt /notify_update' returns a special value (differing between
  1871. // Windows and POSIX hosts) when it updated the manifest file.
  1872. return mtRet == 0x41020001 || mtRet == 0xbb;
  1873. }
  1874. int cmVSLink::LinkIncremental()
  1875. {
  1876. // This follows the steps listed here:
  1877. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  1878. // 1. Compiler compiles the application and generates the *.obj files.
  1879. // 2. An empty manifest file is generated if this is a clean build and if
  1880. // not the previous one is reused.
  1881. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  1882. // *.res file.
  1883. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  1884. // switch and embeds the dummy manifest file. The linker also generates
  1885. // the real manifest file based on the binaries that your binary depends
  1886. // on.
  1887. // 5. The manifest tool (mt.exe) is then used to generate the final
  1888. // manifest.
  1889. // If the final manifest is changed, then 6 and 7 are run, if not
  1890. // they are skipped, and it is done.
  1891. // 6. The resource compiler is invoked one more time.
  1892. // 7. Finally, the Linker does another incremental link, but since the
  1893. // only thing that has changed is the *.res file that contains the
  1894. // manifest it is a short link.
  1895. // Create a resource file referencing the manifest.
  1896. std::string absManifestFile =
  1897. cmSystemTools::CollapseFullPath(this->ManifestFile);
  1898. if (this->Verbose) {
  1899. std::cout << "Create " << this->ManifestFileRC << "\n";
  1900. }
  1901. {
  1902. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  1903. if (!fout) {
  1904. return -1;
  1905. }
  1906. // Insert a pragma statement to specify utf-8 encoding.
  1907. fout << "#pragma code_page(65001)\n";
  1908. fout << this->Type
  1909. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  1910. "24 /* RT_MANIFEST */ \""
  1911. << absManifestFile << "\"";
  1912. }
  1913. // If we have not previously generated a manifest file,
  1914. // generate an empty one so the resource compiler succeeds.
  1915. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  1916. if (this->Verbose) {
  1917. std::cout << "Create empty: " << this->ManifestFile << "\n";
  1918. }
  1919. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  1920. }
  1921. // Compile the resource file.
  1922. std::vector<std::string> rcCommand;
  1923. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  1924. rcCommand.emplace_back("/fo");
  1925. rcCommand.push_back(this->ManifestFileRes);
  1926. rcCommand.push_back(this->ManifestFileRC);
  1927. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1928. return -1;
  1929. }
  1930. // Tell the linker to use our manifest compiled into a resource.
  1931. this->LinkCommand.push_back(this->ManifestFileRes);
  1932. // Run the link command (possibly generates intermediate manifest).
  1933. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  1934. FORMAT_DECIMAL)) {
  1935. return -1;
  1936. }
  1937. // Run the manifest tool to create the final manifest.
  1938. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  1939. // If mt returns a special value then it updated the manifest file so
  1940. // we need to embed it again. Otherwise we are done.
  1941. if (!mtRetIsUpdate(mtRet)) {
  1942. return mtRet;
  1943. }
  1944. // Compile the resource file again.
  1945. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1946. return -1;
  1947. }
  1948. // Link incrementally again to use the updated resource.
  1949. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  1950. FORMAT_DECIMAL)) {
  1951. return -1;
  1952. }
  1953. return 0;
  1954. }
  1955. int cmVSLink::LinkNonIncremental()
  1956. {
  1957. // Run the link command (possibly generates intermediate manifest).
  1958. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  1959. return -1;
  1960. }
  1961. // If we have no manifest files we are done.
  1962. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  1963. return 0;
  1964. }
  1965. // Run the manifest tool to embed the final manifest in the binary.
  1966. std::string mtOut =
  1967. "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
  1968. return this->RunMT(mtOut, false);
  1969. }
  1970. int cmVSLink::RunMT(std::string const& out, bool notify)
  1971. {
  1972. std::vector<std::string> mtCommand;
  1973. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  1974. mtCommand.emplace_back("/nologo");
  1975. mtCommand.emplace_back("/manifest");
  1976. if (this->LinkGeneratesManifest) {
  1977. mtCommand.push_back(this->LinkerManifestFile);
  1978. }
  1979. cm::append(mtCommand, this->UserManifests);
  1980. mtCommand.push_back(out);
  1981. if (notify) {
  1982. // Add an undocumented option that enables a special return
  1983. // code to notify us when the manifest is modified.
  1984. mtCommand.emplace_back("/notify_update");
  1985. }
  1986. int mtRet = 0;
  1987. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  1988. mtRetIsUpdate)) {
  1989. return -1;
  1990. }
  1991. return mtRet;
  1992. }