cmcmd.cxx 63 KB

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