cmcmd.cxx 62 KB

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