cmcmd.cxx 63 KB

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