cmcmd.cxx 61 KB

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