cmcmd.cxx 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  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().c_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().c_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().c_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().c_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].c_str(), args[3].c_str())) {
  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.c_str(), verbose, color) ? 0
  889. : 2;
  890. }
  891. return 1;
  892. }
  893. // Internal CMake link script support.
  894. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  895. return cmcmd::ExecuteLinkScript(args);
  896. }
  897. #ifdef CMAKE_BUILD_WITH_CMAKE
  898. // Internal CMake ninja dependency scanning support.
  899. if (args[1] == "cmake_ninja_depends") {
  900. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  901. }
  902. // Internal CMake ninja dyndep support.
  903. if (args[1] == "cmake_ninja_dyndep") {
  904. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  905. }
  906. #endif
  907. // Internal CMake unimplemented feature notification.
  908. if (args[1] == "cmake_unimplemented_variable") {
  909. std::cerr << "Feature not implemented for this platform.";
  910. if (args.size() == 3) {
  911. std::cerr << " Variable " << args[2] << " is not set.";
  912. }
  913. std::cerr << std::endl;
  914. return 1;
  915. }
  916. if (args[1] == "vs_link_exe") {
  917. return cmcmd::VisualStudioLink(args, 1);
  918. }
  919. if (args[1] == "vs_link_dll") {
  920. return cmcmd::VisualStudioLink(args, 2);
  921. }
  922. // Internal CMake color makefile support.
  923. if (args[1] == "cmake_echo_color") {
  924. return cmcmd::ExecuteEchoColor(args);
  925. }
  926. #ifdef CMAKE_BUILD_WITH_CMAKE
  927. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  928. cmQtAutoGeneratorMocUic autoGen;
  929. std::string const& infoDir = args[2];
  930. std::string const& config = args[3];
  931. return autoGen.Run(infoDir, config) ? 0 : 1;
  932. }
  933. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  934. cmQtAutoGeneratorRcc autoGen;
  935. std::string const& infoFile = args[2];
  936. std::string config;
  937. if (args.size() > 3) {
  938. config = args[3];
  939. }
  940. return autoGen.Run(infoFile, config) ? 0 : 1;
  941. }
  942. #endif
  943. // Tar files
  944. if (args[1] == "tar" && args.size() > 3) {
  945. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  946. std::string const& flags = args[2];
  947. std::string const& outFile = args[3];
  948. std::vector<std::string> files;
  949. std::string mtime;
  950. std::string format;
  951. bool doing_options = true;
  952. for (std::string::size_type cc = 4; cc < args.size(); cc++) {
  953. std::string const& arg = args[cc];
  954. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  955. if (arg == "--") {
  956. doing_options = false;
  957. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  958. mtime = arg.substr(8);
  959. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  960. std::string const& files_from = arg.substr(13);
  961. if (!cmTarFilesFrom(files_from, files)) {
  962. return 1;
  963. }
  964. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  965. format = arg.substr(9);
  966. bool isKnown =
  967. std::find(cm::cbegin(knownFormats), cm::cend(knownFormats),
  968. format) != cm::cend(knownFormats);
  969. if (!isKnown) {
  970. cmSystemTools::Error("Unknown -E tar --format= argument: ",
  971. format.c_str());
  972. return 1;
  973. }
  974. } else {
  975. cmSystemTools::Error("Unknown option to -E tar: ", arg.c_str());
  976. return 1;
  977. }
  978. } else {
  979. files.push_back(arg);
  980. }
  981. }
  982. cmSystemTools::cmTarCompression compress =
  983. cmSystemTools::TarCompressNone;
  984. bool verbose = false;
  985. int nCompress = 0;
  986. if (flags.find_first_of('j') != std::string::npos) {
  987. compress = cmSystemTools::TarCompressBZip2;
  988. ++nCompress;
  989. }
  990. if (flags.find_first_of('J') != std::string::npos) {
  991. compress = cmSystemTools::TarCompressXZ;
  992. ++nCompress;
  993. }
  994. if (flags.find_first_of('z') != std::string::npos) {
  995. compress = cmSystemTools::TarCompressGZip;
  996. ++nCompress;
  997. }
  998. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  999. cmSystemTools::Error("Can not use compression flags with format: ",
  1000. format.c_str());
  1001. return 1;
  1002. }
  1003. if (nCompress > 1) {
  1004. cmSystemTools::Error("Can only compress a tar file one way; "
  1005. "at most one flag of z, j, or J may be used");
  1006. return 1;
  1007. }
  1008. if (flags.find_first_of('v') != std::string::npos) {
  1009. verbose = true;
  1010. }
  1011. if (flags.find_first_of('t') != std::string::npos) {
  1012. if (!cmSystemTools::ListTar(outFile.c_str(), verbose)) {
  1013. cmSystemTools::Error("Problem listing tar: ", outFile.c_str());
  1014. return 1;
  1015. }
  1016. } else if (flags.find_first_of('c') != std::string::npos) {
  1017. if (!cmSystemTools::CreateTar(outFile.c_str(), files, compress,
  1018. verbose, mtime, format)) {
  1019. cmSystemTools::Error("Problem creating tar: ", outFile.c_str());
  1020. return 1;
  1021. }
  1022. } else if (flags.find_first_of('x') != std::string::npos) {
  1023. if (!cmSystemTools::ExtractTar(outFile.c_str(), verbose)) {
  1024. cmSystemTools::Error("Problem extracting tar: ", outFile.c_str());
  1025. return 1;
  1026. }
  1027. #ifdef WIN32
  1028. // OK, on windows 7 after we untar some files,
  1029. // sometimes we can not rename the directory after
  1030. // the untar is done. This breaks the external project
  1031. // untar and rename code. So, by default we will wait
  1032. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1033. // is set in the env, its value will be used instead of 100.
  1034. int delay = 100;
  1035. std::string delayVar;
  1036. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1037. delay = atoi(delayVar.c_str());
  1038. }
  1039. if (delay) {
  1040. cmSystemTools::Delay(delay);
  1041. }
  1042. #endif
  1043. }
  1044. return 0;
  1045. }
  1046. if (args[1] == "server") {
  1047. const std::string pipePrefix = "--pipe=";
  1048. bool supportExperimental = false;
  1049. bool isDebug = false;
  1050. std::string pipe;
  1051. for (size_t i = 2; i < args.size(); ++i) {
  1052. const std::string& a = args[i];
  1053. if (a == "--experimental") {
  1054. supportExperimental = true;
  1055. } else if (a == "--debug") {
  1056. pipe.clear();
  1057. isDebug = true;
  1058. } else if (a.substr(0, pipePrefix.size()) == pipePrefix) {
  1059. isDebug = false;
  1060. pipe = a.substr(pipePrefix.size());
  1061. if (pipe.empty()) {
  1062. cmSystemTools::Error("No pipe given after --pipe=");
  1063. return 2;
  1064. }
  1065. } else {
  1066. cmSystemTools::Error("Unknown argument for server mode");
  1067. return 1;
  1068. }
  1069. }
  1070. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1071. cmConnection* conn;
  1072. if (isDebug) {
  1073. conn = new cmServerStdIoConnection;
  1074. } else {
  1075. conn = new cmServerPipeConnection(pipe);
  1076. }
  1077. cmServer server(conn, supportExperimental);
  1078. std::string errorMessage;
  1079. if (server.Serve(&errorMessage)) {
  1080. return 0;
  1081. }
  1082. cmSystemTools::Error(errorMessage.c_str());
  1083. #else
  1084. static_cast<void>(supportExperimental);
  1085. static_cast<void>(isDebug);
  1086. cmSystemTools::Error("CMake was not built with server mode enabled");
  1087. #endif
  1088. return 1;
  1089. }
  1090. #if defined(CMAKE_BUILD_WITH_CMAKE)
  1091. // Internal CMake Fortran module support.
  1092. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1093. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1094. }
  1095. #endif
  1096. #if defined(_WIN32) && !defined(__CYGWIN__)
  1097. // Write registry value
  1098. if (args[1] == "write_regv" && args.size() > 3) {
  1099. return cmSystemTools::WriteRegistryValue(args[2].c_str(),
  1100. args[3].c_str())
  1101. ? 0
  1102. : 1;
  1103. }
  1104. // Delete registry value
  1105. if (args[1] == "delete_regv" && args.size() > 2) {
  1106. return cmSystemTools::DeleteRegistryValue(args[2].c_str()) ? 0 : 1;
  1107. }
  1108. // Remove file
  1109. if (args[1] == "comspec" && args.size() > 2) {
  1110. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1111. return 1;
  1112. }
  1113. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1114. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1115. }
  1116. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1117. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1118. }
  1119. #endif
  1120. }
  1121. ::CMakeCommandUsage(args[0].c_str());
  1122. return 1;
  1123. }
  1124. int cmcmd::HashSumFile(std::vector<std::string>& args, cmCryptoHash::Algo algo)
  1125. {
  1126. if (args.size() < 3) {
  1127. return -1;
  1128. }
  1129. int retval = 0;
  1130. for (std::string::size_type cc = 2; cc < args.size(); cc++) {
  1131. const char* filename = args[cc].c_str();
  1132. // Cannot compute sum of a directory
  1133. if (cmSystemTools::FileIsDirectory(filename)) {
  1134. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1135. retval++;
  1136. } else {
  1137. std::string value = cmSystemTools::ComputeFileHash(filename, algo);
  1138. if (value.empty()) {
  1139. // To mimic "md5sum/shasum" behavior in a shell:
  1140. std::cerr << filename << ": No such file or directory" << std::endl;
  1141. retval++;
  1142. } else {
  1143. std::cout << value << " " << filename << std::endl;
  1144. }
  1145. }
  1146. }
  1147. return retval;
  1148. }
  1149. int cmcmd::SymlinkLibrary(std::vector<std::string>& args)
  1150. {
  1151. int result = 0;
  1152. std::string realName = args[2];
  1153. std::string soName = args[3];
  1154. std::string name = args[4];
  1155. cmSystemTools::ConvertToUnixSlashes(realName);
  1156. cmSystemTools::ConvertToUnixSlashes(soName);
  1157. cmSystemTools::ConvertToUnixSlashes(name);
  1158. if (soName != realName) {
  1159. if (!cmcmd::SymlinkInternal(realName, soName)) {
  1160. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1161. result = 1;
  1162. }
  1163. }
  1164. if (name != soName) {
  1165. if (!cmcmd::SymlinkInternal(soName, name)) {
  1166. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1167. result = 1;
  1168. }
  1169. }
  1170. return result;
  1171. }
  1172. int cmcmd::SymlinkExecutable(std::vector<std::string>& args)
  1173. {
  1174. int result = 0;
  1175. std::string const& realName = args[2];
  1176. std::string const& name = args[3];
  1177. if (name != realName) {
  1178. if (!cmcmd::SymlinkInternal(realName, name)) {
  1179. cmSystemTools::ReportLastSystemError("cmake_symlink_executable");
  1180. result = 1;
  1181. }
  1182. }
  1183. return result;
  1184. }
  1185. bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link)
  1186. {
  1187. if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
  1188. cmSystemTools::RemoveFile(link);
  1189. }
  1190. #if defined(_WIN32) && !defined(__CYGWIN__)
  1191. return cmSystemTools::CopyFileAlways(file.c_str(), link.c_str());
  1192. #else
  1193. std::string linktext = cmSystemTools::GetFilenameName(file);
  1194. return cmSystemTools::CreateSymlink(linktext, link);
  1195. #endif
  1196. }
  1197. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1198. {
  1199. std::string dirName = dir;
  1200. dirName += "/Progress";
  1201. std::string fName;
  1202. FILE* progFile;
  1203. // read the count
  1204. fName = dirName;
  1205. fName += "/count.txt";
  1206. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1207. int count = 0;
  1208. if (!progFile) {
  1209. return;
  1210. }
  1211. if (1 != fscanf(progFile, "%i", &count)) {
  1212. cmSystemTools::Message("Could not read from progress file.");
  1213. }
  1214. fclose(progFile);
  1215. const char* last = num.c_str();
  1216. for (const char* c = last;; ++c) {
  1217. if (*c == ',' || *c == '\0') {
  1218. if (c != last) {
  1219. fName = dirName;
  1220. fName += "/";
  1221. fName.append(last, c - last);
  1222. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1223. if (progFile) {
  1224. fprintf(progFile, "empty");
  1225. fclose(progFile);
  1226. }
  1227. }
  1228. if (*c == '\0') {
  1229. break;
  1230. }
  1231. last = c + 1;
  1232. }
  1233. }
  1234. int fileNum =
  1235. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1236. if (count > 0) {
  1237. // print the progress
  1238. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1239. }
  1240. }
  1241. int cmcmd::ExecuteEchoColor(std::vector<std::string>& args)
  1242. {
  1243. // The arguments are
  1244. // argv[0] == <cmake-executable>
  1245. // argv[1] == cmake_echo_color
  1246. bool enabled = true;
  1247. int color = cmsysTerminal_Color_Normal;
  1248. bool newline = true;
  1249. std::string progressDir;
  1250. for (unsigned int i = 2; i < args.size(); ++i) {
  1251. if (args[i].find("--switch=") == 0) {
  1252. // Enable or disable color based on the switch value.
  1253. std::string value = args[i].substr(9);
  1254. if (!value.empty()) {
  1255. enabled = cmSystemTools::IsOn(value);
  1256. }
  1257. } else if (cmHasLiteralPrefix(args[i], "--progress-dir=")) {
  1258. progressDir = args[i].substr(15);
  1259. } else if (cmHasLiteralPrefix(args[i], "--progress-num=")) {
  1260. if (!progressDir.empty()) {
  1261. std::string const& progressNum = args[i].substr(15);
  1262. cmcmdProgressReport(progressDir, progressNum);
  1263. }
  1264. } else if (args[i] == "--normal") {
  1265. color = cmsysTerminal_Color_Normal;
  1266. } else if (args[i] == "--black") {
  1267. color = cmsysTerminal_Color_ForegroundBlack;
  1268. } else if (args[i] == "--red") {
  1269. color = cmsysTerminal_Color_ForegroundRed;
  1270. } else if (args[i] == "--green") {
  1271. color = cmsysTerminal_Color_ForegroundGreen;
  1272. } else if (args[i] == "--yellow") {
  1273. color = cmsysTerminal_Color_ForegroundYellow;
  1274. } else if (args[i] == "--blue") {
  1275. color = cmsysTerminal_Color_ForegroundBlue;
  1276. } else if (args[i] == "--magenta") {
  1277. color = cmsysTerminal_Color_ForegroundMagenta;
  1278. } else if (args[i] == "--cyan") {
  1279. color = cmsysTerminal_Color_ForegroundCyan;
  1280. } else if (args[i] == "--white") {
  1281. color = cmsysTerminal_Color_ForegroundWhite;
  1282. } else if (args[i] == "--bold") {
  1283. color |= cmsysTerminal_Color_ForegroundBold;
  1284. } else if (args[i] == "--no-newline") {
  1285. newline = false;
  1286. } else if (args[i] == "--newline") {
  1287. newline = true;
  1288. } else {
  1289. // Color is enabled. Print with the current color.
  1290. cmSystemTools::MakefileColorEcho(color, args[i].c_str(), newline,
  1291. enabled);
  1292. }
  1293. }
  1294. return 0;
  1295. }
  1296. int cmcmd::ExecuteLinkScript(std::vector<std::string>& args)
  1297. {
  1298. // The arguments are
  1299. // argv[0] == <cmake-executable>
  1300. // argv[1] == cmake_link_script
  1301. // argv[2] == <link-script-name>
  1302. // argv[3] == --verbose=?
  1303. bool verbose = false;
  1304. if (args.size() >= 4) {
  1305. if (args[3].find("--verbose=") == 0) {
  1306. if (!cmSystemTools::IsOff(args[3].substr(10))) {
  1307. verbose = true;
  1308. }
  1309. }
  1310. }
  1311. // Allocate a process instance.
  1312. cmsysProcess* cp = cmsysProcess_New();
  1313. if (!cp) {
  1314. std::cerr << "Error allocating process instance in link script."
  1315. << std::endl;
  1316. return 1;
  1317. }
  1318. // Children should share stdout and stderr with this process.
  1319. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  1320. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  1321. // Run the command lines verbatim.
  1322. cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
  1323. // Read command lines from the script.
  1324. cmsys::ifstream fin(args[2].c_str());
  1325. if (!fin) {
  1326. std::cerr << "Error opening link script \"" << args[2] << "\""
  1327. << std::endl;
  1328. return 1;
  1329. }
  1330. // Run one command at a time.
  1331. std::string command;
  1332. int result = 0;
  1333. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1334. // Skip empty command lines.
  1335. if (command.find_first_not_of(" \t") == std::string::npos) {
  1336. continue;
  1337. }
  1338. // Setup this command line.
  1339. const char* cmd[2] = { command.c_str(), nullptr };
  1340. cmsysProcess_SetCommand(cp, cmd);
  1341. // Report the command if verbose output is enabled.
  1342. if (verbose) {
  1343. std::cout << command << std::endl;
  1344. }
  1345. // Run the command and wait for it to exit.
  1346. cmsysProcess_Execute(cp);
  1347. cmsysProcess_WaitForExit(cp, nullptr);
  1348. // Report failure if any.
  1349. switch (cmsysProcess_GetState(cp)) {
  1350. case cmsysProcess_State_Exited: {
  1351. int value = cmsysProcess_GetExitValue(cp);
  1352. if (value != 0) {
  1353. result = value;
  1354. }
  1355. } break;
  1356. case cmsysProcess_State_Exception:
  1357. std::cerr << "Error running link command: "
  1358. << cmsysProcess_GetExceptionString(cp) << std::endl;
  1359. result = 1;
  1360. break;
  1361. case cmsysProcess_State_Error:
  1362. std::cerr << "Error running link command: "
  1363. << cmsysProcess_GetErrorString(cp) << std::endl;
  1364. result = 2;
  1365. break;
  1366. default:
  1367. break;
  1368. }
  1369. }
  1370. // Free the process instance.
  1371. cmsysProcess_Delete(cp);
  1372. // Return the final resulting return value.
  1373. return result;
  1374. }
  1375. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1376. {
  1377. #if defined(CMAKE_BUILD_WITH_CMAKE) && defined(_WIN32) && !defined(__CYGWIN__)
  1378. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1379. parser.ParseVersion(version);
  1380. if (parser.Found()) {
  1381. std::cout << "@echo off" << std::endl;
  1382. std::cout << "echo Environment Selection: " << name << std::endl;
  1383. std::cout << "set PATH=" << parser.GetPathDirectories() << std::endl;
  1384. std::cout << "set INCLUDE=" << parser.GetIncludeDirectories() << std::endl;
  1385. std::cout << "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1386. return 0;
  1387. }
  1388. #else
  1389. (void)version;
  1390. #endif
  1391. std::cerr << "Could not find " << name;
  1392. return -1;
  1393. }
  1394. class cmVSLink
  1395. {
  1396. int Type;
  1397. bool Verbose;
  1398. bool Incremental;
  1399. bool LinkGeneratesManifest;
  1400. std::vector<std::string> LinkCommand;
  1401. std::vector<std::string> UserManifests;
  1402. std::string LinkerManifestFile;
  1403. std::string ManifestFile;
  1404. std::string ManifestFileRC;
  1405. std::string ManifestFileRes;
  1406. std::string TargetFile;
  1407. std::string MtPath;
  1408. std::string RcPath;
  1409. public:
  1410. cmVSLink(int type, bool verbose)
  1411. : Type(type)
  1412. , Verbose(verbose)
  1413. , Incremental(false)
  1414. , LinkGeneratesManifest(true)
  1415. {
  1416. }
  1417. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1418. std::vector<std::string>::const_iterator argEnd);
  1419. int Link();
  1420. private:
  1421. int LinkIncremental();
  1422. int LinkNonIncremental();
  1423. int RunMT(std::string const& out, bool notify);
  1424. };
  1425. // For visual studio 2005 and newer manifest files need to be embedded into
  1426. // exe and dll's. This code does that in such a way that incremental linking
  1427. // still works.
  1428. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1429. {
  1430. #if defined(_WIN32) && defined(CMAKE_BUILD_WITH_CMAKE)
  1431. // Replace streambuf so we output in the system codepage. CMake is set up
  1432. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1433. // outputs using the system codepage so we need to change behavior when
  1434. // we run the link command.
  1435. cmsys::ConsoleBuf::Manager consoleOut(std::cout);
  1436. cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
  1437. #endif
  1438. if (args.size() < 2) {
  1439. return -1;
  1440. }
  1441. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  1442. std::vector<std::string> expandedArgs;
  1443. for (std::string const& i : args) {
  1444. // check for nmake temporary files
  1445. if (i[0] == '@' && i.find("@CMakeFiles") != 0) {
  1446. cmsys::ifstream fin(i.substr(1).c_str());
  1447. std::string line;
  1448. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1449. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  1450. }
  1451. } else {
  1452. expandedArgs.push_back(i);
  1453. }
  1454. }
  1455. cmVSLink vsLink(type, verbose);
  1456. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  1457. return -1;
  1458. }
  1459. return vsLink.Link();
  1460. }
  1461. enum NumberFormat
  1462. {
  1463. FORMAT_DECIMAL,
  1464. FORMAT_HEX
  1465. };
  1466. struct NumberFormatter
  1467. {
  1468. NumberFormat Format;
  1469. int Value;
  1470. NumberFormatter(NumberFormat format, int value)
  1471. : Format(format)
  1472. , Value(value)
  1473. {
  1474. }
  1475. };
  1476. std::ostream& operator<<(std::ostream& stream,
  1477. NumberFormatter const& formatter)
  1478. {
  1479. auto const& flags = stream.flags();
  1480. if (formatter.Format == FORMAT_DECIMAL) {
  1481. stream << std::dec << formatter.Value;
  1482. } else {
  1483. stream << "0x" << std::hex << formatter.Value;
  1484. }
  1485. stream.flags(flags);
  1486. return stream;
  1487. }
  1488. static bool RunCommand(const char* comment, std::vector<std::string>& command,
  1489. bool verbose, NumberFormat exitFormat,
  1490. int* retCodeOut = nullptr,
  1491. bool (*retCodeOkay)(int) = nullptr)
  1492. {
  1493. if (verbose) {
  1494. std::cout << comment << ":\n";
  1495. std::cout << cmJoin(command, " ") << "\n";
  1496. }
  1497. std::string output;
  1498. int retCode = 0;
  1499. bool commandResult = cmSystemTools::RunSingleCommand(
  1500. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  1501. bool const retCodeSuccess =
  1502. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  1503. bool const success = commandResult && retCodeSuccess;
  1504. if (retCodeOut) {
  1505. if (commandResult || !retCodeSuccess) {
  1506. *retCodeOut = retCode;
  1507. } else {
  1508. *retCodeOut = -1;
  1509. }
  1510. }
  1511. if (!success) {
  1512. std::cout << comment << ": command \"" << cmJoin(command, " ")
  1513. << "\" failed (exit code "
  1514. << NumberFormatter(exitFormat, retCode)
  1515. << ") with the following output:\n"
  1516. << output;
  1517. } else {
  1518. // always print the output of the command, unless
  1519. // it is the dumb rc command banner
  1520. if (output.find("Resource Compiler Version") == std::string::npos) {
  1521. std::cout << output;
  1522. }
  1523. }
  1524. return success;
  1525. }
  1526. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  1527. std::vector<std::string>::const_iterator argEnd)
  1528. {
  1529. // Parse our own arguments.
  1530. std::string intDir;
  1531. std::vector<std::string>::const_iterator arg = argBeg;
  1532. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  1533. if (*arg == "--") {
  1534. ++arg;
  1535. break;
  1536. }
  1537. if (*arg == "--manifests") {
  1538. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  1539. this->UserManifests.push_back(*arg);
  1540. }
  1541. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  1542. intDir = arg->substr(9);
  1543. ++arg;
  1544. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  1545. this->RcPath = arg->substr(5);
  1546. ++arg;
  1547. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  1548. this->MtPath = arg->substr(5);
  1549. ++arg;
  1550. } else {
  1551. std::cerr << "unknown argument '" << *arg << "'\n";
  1552. return false;
  1553. }
  1554. }
  1555. if (intDir.empty()) {
  1556. return false;
  1557. }
  1558. // The rest of the arguments form the link command.
  1559. if (arg == argEnd) {
  1560. return false;
  1561. }
  1562. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  1563. // Parse the link command to extract information we need.
  1564. for (; arg != argEnd; ++arg) {
  1565. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0) {
  1566. this->Incremental = true;
  1567. } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
  1568. this->Incremental = true;
  1569. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
  1570. this->LinkGeneratesManifest = false;
  1571. } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
  1572. this->TargetFile = arg->substr(3);
  1573. } else if (cmHasLiteralPrefix(*arg, "/out:")) {
  1574. this->TargetFile = arg->substr(5);
  1575. }
  1576. }
  1577. if (this->TargetFile.empty()) {
  1578. return false;
  1579. }
  1580. this->ManifestFile = intDir + "/embed.manifest";
  1581. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  1582. if (this->Incremental) {
  1583. // We will compile a resource containing the manifest and
  1584. // pass it to the link command.
  1585. this->ManifestFileRC = intDir + "/manifest.rc";
  1586. this->ManifestFileRes = intDir + "/manifest.res";
  1587. } else if (this->UserManifests.empty()) {
  1588. // Prior to support for user-specified manifests CMake placed the
  1589. // linker-generated manifest next to the binary (as if it were not to be
  1590. // embedded) when not linking incrementally. Preserve this behavior.
  1591. this->ManifestFile = this->TargetFile + ".manifest";
  1592. this->LinkerManifestFile = this->ManifestFile;
  1593. }
  1594. if (this->LinkGeneratesManifest) {
  1595. this->LinkCommand.emplace_back("/MANIFEST");
  1596. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  1597. }
  1598. return true;
  1599. }
  1600. int cmVSLink::Link()
  1601. {
  1602. if (this->Incremental &&
  1603. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  1604. if (this->Verbose) {
  1605. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  1606. }
  1607. return LinkIncremental();
  1608. }
  1609. if (this->Verbose) {
  1610. if (!this->Incremental) {
  1611. std::cout << "Visual Studio Non-Incremental Link\n";
  1612. } else {
  1613. std::cout << "Visual Studio Incremental Link without manifests\n";
  1614. }
  1615. }
  1616. return LinkNonIncremental();
  1617. }
  1618. static bool mtRetIsUpdate(int mtRet)
  1619. {
  1620. // 'mt /notify_update' returns a special value (differing between
  1621. // Windows and POSIX hosts) when it updated the manifest file.
  1622. return mtRet == 0x41020001 || mtRet == 0xbb;
  1623. }
  1624. int cmVSLink::LinkIncremental()
  1625. {
  1626. // This follows the steps listed here:
  1627. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  1628. // 1. Compiler compiles the application and generates the *.obj files.
  1629. // 2. An empty manifest file is generated if this is a clean build and if
  1630. // not the previous one is reused.
  1631. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  1632. // *.res file.
  1633. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  1634. // switch and embeds the dummy manifest file. The linker also generates
  1635. // the real manifest file based on the binaries that your binary depends
  1636. // on.
  1637. // 5. The manifest tool (mt.exe) is then used to generate the final
  1638. // manifest.
  1639. // If the final manifest is changed, then 6 and 7 are run, if not
  1640. // they are skipped, and it is done.
  1641. // 6. The resource compiler is invoked one more time.
  1642. // 7. Finally, the Linker does another incremental link, but since the
  1643. // only thing that has changed is the *.res file that contains the
  1644. // manifest it is a short link.
  1645. // Create a resource file referencing the manifest.
  1646. std::string absManifestFile =
  1647. cmSystemTools::CollapseFullPath(this->ManifestFile);
  1648. if (this->Verbose) {
  1649. std::cout << "Create " << this->ManifestFileRC << "\n";
  1650. }
  1651. {
  1652. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  1653. if (!fout) {
  1654. return -1;
  1655. }
  1656. // Insert a pragma statement to specify utf-8 encoding.
  1657. fout << "#pragma code_page(65001)\n";
  1658. fout << this->Type
  1659. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  1660. "24 /* RT_MANIFEST */ \""
  1661. << absManifestFile << "\"";
  1662. }
  1663. // If we have not previously generated a manifest file,
  1664. // generate an empty one so the resource compiler succeeds.
  1665. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  1666. if (this->Verbose) {
  1667. std::cout << "Create empty: " << this->ManifestFile << "\n";
  1668. }
  1669. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  1670. }
  1671. // Compile the resource file.
  1672. std::vector<std::string> rcCommand;
  1673. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  1674. rcCommand.push_back("/fo" + this->ManifestFileRes);
  1675. rcCommand.push_back(this->ManifestFileRC);
  1676. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1677. return -1;
  1678. }
  1679. // Tell the linker to use our manifest compiled into a resource.
  1680. this->LinkCommand.push_back(this->ManifestFileRes);
  1681. // Run the link command (possibly generates intermediate manifest).
  1682. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  1683. FORMAT_DECIMAL)) {
  1684. return -1;
  1685. }
  1686. // Run the manifest tool to create the final manifest.
  1687. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  1688. // If mt returns a special value then it updated the manifest file so
  1689. // we need to embed it again. Otherwise we are done.
  1690. if (!mtRetIsUpdate(mtRet)) {
  1691. return mtRet;
  1692. }
  1693. // Compile the resource file again.
  1694. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1695. return -1;
  1696. }
  1697. // Link incrementally again to use the updated resource.
  1698. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  1699. FORMAT_DECIMAL)) {
  1700. return -1;
  1701. }
  1702. return 0;
  1703. }
  1704. int cmVSLink::LinkNonIncremental()
  1705. {
  1706. // Run the link command (possibly generates intermediate manifest).
  1707. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  1708. return -1;
  1709. }
  1710. // If we have no manifest files we are done.
  1711. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  1712. return 0;
  1713. }
  1714. // Run the manifest tool to embed the final manifest in the binary.
  1715. std::string mtOut =
  1716. "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
  1717. return this->RunMT(mtOut, false);
  1718. }
  1719. int cmVSLink::RunMT(std::string const& out, bool notify)
  1720. {
  1721. std::vector<std::string> mtCommand;
  1722. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  1723. mtCommand.emplace_back("/nologo");
  1724. mtCommand.emplace_back("/manifest");
  1725. if (this->LinkGeneratesManifest) {
  1726. mtCommand.push_back(this->LinkerManifestFile);
  1727. }
  1728. mtCommand.insert(mtCommand.end(), this->UserManifests.begin(),
  1729. this->UserManifests.end());
  1730. mtCommand.push_back(out);
  1731. if (notify) {
  1732. // Add an undocumented option that enables a special return
  1733. // code to notify us when the manifest is modified.
  1734. mtCommand.emplace_back("/notify_update");
  1735. }
  1736. int mtRet = 0;
  1737. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  1738. mtRetIsUpdate)) {
  1739. return -1;
  1740. }
  1741. return mtRet;
  1742. }