cmcmd.cxx 62 KB

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