cmcmd.cxx 61 KB

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