cmcmd.cxx 62 KB

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