cmcmd.cxx 60 KB

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