cmcmd.cxx 64 KB

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