cmcmd.cxx 62 KB

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