cmcmd.cxx 66 KB

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