cmcmd.cxx 63 KB

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