cmcmd.cxx 62 KB

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