cmcmd.cxx 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553
  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 <functional>
  5. #include <iterator>
  6. #include <cm/optional>
  7. #include <cmext/algorithm>
  8. #include <cm3p/uv.h>
  9. #include <fcntl.h>
  10. #include "cm_fileno.hxx"
  11. #include "cmCommandLineArgument.h"
  12. #include "cmConsoleBuf.h"
  13. #include "cmCryptoHash.h"
  14. #include "cmDuration.h"
  15. #include "cmGlobalGenerator.h"
  16. #include "cmList.h"
  17. #include "cmLocalGenerator.h"
  18. #include "cmMakefile.h"
  19. #include "cmQtAutoMocUic.h"
  20. #include "cmQtAutoRcc.h"
  21. #include "cmRange.h"
  22. #include "cmState.h"
  23. #include "cmStateDirectory.h"
  24. #include "cmStateSnapshot.h"
  25. #include "cmStringAlgorithms.h"
  26. #include "cmSystemTools.h"
  27. #include "cmTransformDepfile.h"
  28. #include "cmUVProcessChain.h"
  29. #include "cmUVStream.h"
  30. #include "cmUtils.hxx"
  31. #include "cmValue.h"
  32. #include "cmVersion.h"
  33. #include "cmake.h"
  34. #if !defined(CMAKE_BOOTSTRAP)
  35. # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
  36. # include "cmFileTime.h"
  37. # include "bindexplib.h"
  38. #endif
  39. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  40. # include <algorithm>
  41. # include "cmCMakePath.h"
  42. # include "cmProcessTools.h"
  43. #endif
  44. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  45. # include "cmVisualStudioWCEPlatformParser.h"
  46. #endif
  47. #include <array>
  48. #include <chrono>
  49. #include <cstdio>
  50. #include <cstdlib>
  51. #include <cstring>
  52. #include <iostream>
  53. #include <memory>
  54. #include <sstream>
  55. #include <utility>
  56. #ifdef _WIN32
  57. # include <fcntl.h> // for _O_BINARY
  58. # include <io.h> // for _setmode
  59. #endif
  60. #include <cm/string_view>
  61. #include "cmsys/Directory.hxx"
  62. #include "cmsys/FStream.hxx"
  63. #include "cmsys/RegularExpression.hxx"
  64. #include "cmsys/Terminal.h"
  65. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  66. std::vector<std::string>::const_iterator argEnd);
  67. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  68. std::vector<std::string>::const_iterator argEnd);
  69. namespace {
  70. void CMakeCommandUsage(std::string const& program)
  71. {
  72. std::ostringstream errorStream;
  73. #ifndef CMAKE_BOOTSTRAP
  74. /* clang-format off */
  75. errorStream
  76. << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
  77. /* clang-format on */
  78. #else
  79. /* clang-format off */
  80. errorStream
  81. << "cmake bootstrap\n";
  82. /* clang-format on */
  83. #endif
  84. // If you add new commands, change here,
  85. // and in cmakemain.cxx in the options table
  86. /* clang-format off */
  87. errorStream
  88. << "Usage: " << program << " -E <command> [arguments...]\n"
  89. << "Available commands: \n"
  90. << " capabilities - Report capabilities built into cmake "
  91. "in JSON format\n"
  92. << " cat [--] <files>... - concat the files and print them to the "
  93. "standard output\n"
  94. << " chdir dir cmd [args...] - run command in a given directory\n"
  95. << " compare_files [--ignore-eol] file1 file2\n"
  96. << " - check if file1 is same as file2\n"
  97. << " copy <file>... destination - copy files to destination "
  98. "(either file or directory)\n"
  99. << " copy_directory <dir>... destination - copy content of <dir>... "
  100. "directories to 'destination' directory\n"
  101. << " copy_directory_if_different <dir>... destination - copy changed content of <dir>... "
  102. "directories to 'destination' directory\n"
  103. << " copy_if_different <file>... destination - copy files if it has "
  104. "changed\n"
  105. << " echo [<string>...] - displays arguments as text\n"
  106. << " echo_append [<string>...] - displays arguments as text but no new "
  107. "line\n"
  108. << " env [--unset=NAME ...] [NAME=VALUE ...] [--] <command> [<arg>...]\n"
  109. << " - run command in a modified environment\n"
  110. << " environment - display the current environment\n"
  111. << " make_directory <dir>... - create parent and <dir> directories\n"
  112. << " md5sum <file>... - create MD5 checksum of files\n"
  113. << " sha1sum <file>... - create SHA1 checksum of files\n"
  114. << " sha224sum <file>... - create SHA224 checksum of files\n"
  115. << " sha256sum <file>... - create SHA256 checksum of files\n"
  116. << " sha384sum <file>... - create SHA384 checksum of files\n"
  117. << " sha512sum <file>... - create SHA512 checksum of files\n"
  118. << " remove [-f] <file>... - remove the file(s), use -f to force "
  119. "it (deprecated: use rm instead)\n"
  120. << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
  121. << " rename oldname newname - rename a file or directory "
  122. "(on one volume)\n"
  123. << " rm [-rRf] [--] <file/dir>... - remove files or directories, use -f "
  124. "to force it, r or R to remove directories and their contents "
  125. "recursively\n"
  126. << " sleep <number>... - sleep for given number of seconds\n"
  127. << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
  128. << " - create or extract a tar or zip archive\n"
  129. << " time command [args...] - run command and display elapsed time\n"
  130. << " touch <file>... - touch a <file>.\n"
  131. << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
  132. << " create_symlink old new - create a symbolic link new -> old\n"
  133. << " create_hardlink old new - create a hard link new -> old\n"
  134. << " true - do nothing with an exit code of 0\n"
  135. << " false - do nothing with an exit code of 1\n"
  136. #if defined(_WIN32) && !defined(__CYGWIN__)
  137. << "Available on Windows only:\n"
  138. << " delete_regv key - delete registry value\n"
  139. << " env_vs8_wince sdkname - displays a batch file which sets the "
  140. "environment for the provided Windows CE SDK installed in VS2005\n"
  141. << " env_vs9_wince sdkname - displays a batch file which sets the "
  142. "environment for the provided Windows CE SDK installed in VS2008\n"
  143. << " write_regv key value - write registry value\n"
  144. #endif
  145. ;
  146. /* clang-format on */
  147. cmSystemTools::Error(errorStream.str());
  148. }
  149. bool cmTarFilesFrom(std::string const& file, std::vector<std::string>& files)
  150. {
  151. if (cmSystemTools::FileIsDirectory(file)) {
  152. std::ostringstream e;
  153. e << "-E tar --files-from= file '" << file << "' is a directory";
  154. cmSystemTools::Error(e.str());
  155. return false;
  156. }
  157. cmsys::ifstream fin(file.c_str());
  158. if (!fin) {
  159. std::ostringstream e;
  160. e << "-E tar --files-from= file '" << file << "' not found";
  161. cmSystemTools::Error(e.str());
  162. return false;
  163. }
  164. std::string line;
  165. while (cmSystemTools::GetLineFromStream(fin, line)) {
  166. if (line.empty()) {
  167. continue;
  168. }
  169. if (cmHasLiteralPrefix(line, "--add-file=")) {
  170. files.push_back(line.substr(11));
  171. } else if (cmHasLiteralPrefix(line, "-")) {
  172. std::ostringstream e;
  173. e << "-E tar --files-from='" << file << "' file invalid line:\n"
  174. << line << "\n";
  175. cmSystemTools::Error(e.str());
  176. return false;
  177. } else {
  178. files.push_back(line);
  179. }
  180. }
  181. return true;
  182. }
  183. void cmCatFile(const std::string& fileToAppend)
  184. {
  185. #ifdef _WIN32
  186. _setmode(fileno(stdout), _O_BINARY);
  187. #endif
  188. cmsys::ifstream source(fileToAppend.c_str(),
  189. (std::ios::binary | std::ios::in));
  190. std::cout << source.rdbuf();
  191. }
  192. bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
  193. {
  194. if (cmSystemTools::FileIsSymlink(dir)) {
  195. if (!cmSystemTools::RemoveFile(dir)) {
  196. std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
  197. return false;
  198. }
  199. } else if (!recursive) {
  200. std::cerr << "Error removing directory \"" << dir
  201. << "\" without recursive option.\n";
  202. return false;
  203. } else if (!cmSystemTools::RemoveADirectory(dir)) {
  204. std::cerr << "Error removing directory \"" << dir << "\".\n";
  205. return false;
  206. }
  207. return true;
  208. }
  209. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  210. class CLIncludeParser : public cmProcessTools::LineParser
  211. {
  212. public:
  213. CLIncludeParser(cm::string_view includePrefix, cmsys::ofstream& depFile,
  214. std::ostream& output)
  215. : IncludePrefix(includePrefix)
  216. , DepFile(depFile)
  217. , Output(output)
  218. {
  219. }
  220. private:
  221. bool ProcessLine() override
  222. {
  223. if (cmHasPrefix(this->Line, this->IncludePrefix)) {
  224. auto path =
  225. cmTrimWhitespace(this->Line.c_str() + this->IncludePrefix.size());
  226. cmSystemTools::ConvertToLongPath(path);
  227. this->DepFile << cmCMakePath(path).GenericString() << std::endl;
  228. } else {
  229. this->Output << this->Line << std::endl << std::flush;
  230. }
  231. return true;
  232. }
  233. cm::string_view IncludePrefix;
  234. cmsys::ofstream& DepFile;
  235. std::ostream& Output;
  236. };
  237. class CLOutputLogger : public cmProcessTools::OutputLogger
  238. {
  239. public:
  240. CLOutputLogger(std::ostream& log)
  241. : cmProcessTools::OutputLogger(log)
  242. {
  243. }
  244. bool ProcessLine() override
  245. {
  246. *this->Log << std::flush;
  247. return true;
  248. }
  249. };
  250. int CLCompileAndDependencies(const std::vector<std::string>& args)
  251. {
  252. std::string depFile;
  253. std::string currentBinaryDir;
  254. std::string filterPrefix;
  255. std::vector<std::string> command;
  256. for (auto it = args.cbegin() + 2; it != args.cend(); it++) {
  257. if (cmHasLiteralPrefix(*it, "--dep-file=")) {
  258. depFile = it->substr(11);
  259. } else if (cmHasLiteralPrefix(*it, "--working-dir=")) {
  260. currentBinaryDir = it->substr(14);
  261. } else if (cmHasLiteralPrefix(*it, "--filter-prefix=")) {
  262. filterPrefix = it->substr(16);
  263. } else if (*it == "--") {
  264. command.insert(command.begin(), ++it, args.cend());
  265. break;
  266. } else {
  267. return 1;
  268. }
  269. }
  270. cmUVProcessChainBuilder builder;
  271. builder.AddCommand(command).SetWorkingDirectory(currentBinaryDir);
  272. cmsys::ofstream fout(depFile.c_str());
  273. if (!fout) {
  274. return 3;
  275. }
  276. CLIncludeParser includeParser(filterPrefix, fout, std::cout);
  277. CLOutputLogger errLogger(std::cerr);
  278. // Start the process.
  279. auto result =
  280. cmProcessTools::RunProcess(builder, &includeParser, &errLogger);
  281. auto const& subStatus = result.front();
  282. int status = 0;
  283. // handle status of process
  284. if (subStatus.SpawnResult != 0) {
  285. status = 2;
  286. } else if (subStatus.TermSignal != 0) {
  287. status = 1;
  288. } else {
  289. status = static_cast<int>(subStatus.ExitStatus);
  290. }
  291. if (status != 0) {
  292. // remove the dependencies file because potentially invalid
  293. fout.close();
  294. cmSystemTools::RemoveFile(depFile);
  295. }
  296. return status;
  297. }
  298. #endif
  299. int HandleIWYU(const std::string& runCmd, const std::string& /* sourceFile */,
  300. const std::vector<std::string>& orig_cmd)
  301. {
  302. // Construct the iwyu command line by taking what was given
  303. // and adding all the arguments we give to the compiler.
  304. cmList iwyu_cmd{ runCmd, cmList::EmptyElements::Yes };
  305. cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
  306. // Run the iwyu command line. Capture its stderr and hide its stdout.
  307. std::string stdErr;
  308. int ret;
  309. if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
  310. nullptr, cmSystemTools::OUTPUT_NONE)) {
  311. std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
  312. return 1;
  313. }
  314. // Warn if iwyu reported anything.
  315. if (stdErr.find("should remove these lines:") != std::string::npos ||
  316. stdErr.find("should add these lines:") != std::string::npos) {
  317. std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
  318. << stdErr << "\n";
  319. }
  320. // Older versions of iwyu always returned a non-zero exit code,
  321. // so ignore it unless the user has enabled errors.
  322. auto has_error_opt = std::find_if(
  323. iwyu_cmd.cbegin(), iwyu_cmd.cend(),
  324. [](std::string const& opt) { return cmHasLiteralPrefix(opt, "--error"); });
  325. bool errors_enabled = has_error_opt != iwyu_cmd.cend() &&
  326. has_error_opt != iwyu_cmd.cbegin() &&
  327. *std::prev(has_error_opt) == "-Xiwyu";
  328. return errors_enabled ? ret : 0;
  329. }
  330. int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
  331. const std::vector<std::string>& orig_cmd)
  332. {
  333. cmList tidy_cmd{ runCmd, cmList::EmptyElements::Yes };
  334. tidy_cmd.push_back(sourceFile);
  335. for (auto const& arg : tidy_cmd) {
  336. if (cmHasLiteralPrefix(arg, "--export-fixes=")) {
  337. cmSystemTools::RemoveFile(arg.substr(cmStrLen("--export-fixes=")));
  338. }
  339. }
  340. // clang-tidy supports working out the compile commands from a
  341. // compile_commands.json file in a directory given by a "-p" option, or by
  342. // passing the compiler command line arguments after --. When the latter
  343. // strategy is used and the build is using a compiler other than the system
  344. // default, clang-tidy may erroneously use the system default compiler's
  345. // headers instead of those from the custom compiler. It doesn't do that if
  346. // given a compile_commands.json to work with instead, so prefer to use the
  347. // compile_commands.json file when "-p" is present.
  348. if (!cm::contains(tidy_cmd.cbegin(), tidy_cmd.cend() - 1, "-p")) {
  349. // Construct the clang-tidy command line by taking what was given
  350. // and adding our compiler command line. The clang-tidy tool will
  351. // automatically skip over the compiler itself and extract the
  352. // options. If the compiler is a custom compiler, clang-tidy might
  353. // not correctly handle that with this approach.
  354. tidy_cmd.emplace_back("--");
  355. cm::append(tidy_cmd, orig_cmd);
  356. }
  357. // Run the tidy command line. Capture its stdout and hide its stderr.
  358. int ret;
  359. std::string stdOut;
  360. std::string stdErr;
  361. if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
  362. nullptr, cmSystemTools::OUTPUT_NONE)) {
  363. std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
  364. return 1;
  365. }
  366. // Output the stdout from clang-tidy to stderr
  367. std::cerr << stdOut;
  368. // If clang-tidy exited with an error do the same.
  369. if (ret != 0) {
  370. std::cerr << stdErr;
  371. }
  372. return ret;
  373. }
  374. int HandleLWYU(const std::string& runCmd, const std::string& sourceFile,
  375. const std::vector<std::string>&)
  376. {
  377. // Construct the ldd -r -u (link what you use lwyu) command line
  378. // ldd -u -r lwuy target
  379. cmList lwyu_cmd{ runCmd, cmList::EmptyElements::Yes };
  380. lwyu_cmd.push_back(sourceFile);
  381. // Run the lwyu check command line, currently ldd is expected.
  382. // Capture its stdout and hide its stderr.
  383. // Ignore its return code because the tool always returns non-zero
  384. // if there are any warnings, but we just want to warn.
  385. std::string stdOut;
  386. std::string stdErr;
  387. int ret;
  388. if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
  389. nullptr, cmSystemTools::OUTPUT_NONE)) {
  390. std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
  391. return 1;
  392. }
  393. // Output the stdout from ldd -r -u to stderr
  394. // Warn if lwyu reported anything.
  395. if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
  396. std::cerr << "Warning: " << stdOut;
  397. }
  398. return 0;
  399. }
  400. int HandleCppLint(const std::string& runCmd, const std::string& sourceFile,
  401. const std::vector<std::string>&)
  402. {
  403. // Construct the cpplint command line.
  404. cmList cpplint_cmd{ runCmd, cmList::EmptyElements::Yes };
  405. cpplint_cmd.push_back(sourceFile);
  406. // Run the cpplint command line. Capture its output.
  407. std::string stdOut;
  408. int ret;
  409. if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
  410. nullptr, cmSystemTools::OUTPUT_NONE)) {
  411. std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
  412. << "\n";
  413. return 1;
  414. }
  415. if (!stdOut.empty()) {
  416. std::cerr << "Warning: cpplint diagnostics:\n";
  417. // Output the output from cpplint to stderr
  418. std::cerr << stdOut;
  419. }
  420. // always return 0 so the build can continue as cpplint returns non-zero
  421. // for any warning
  422. return 0;
  423. }
  424. int HandleCppCheck(const std::string& runCmd, const std::string& sourceFile,
  425. const std::vector<std::string>& orig_cmd)
  426. {
  427. // Construct the cpplint command line.
  428. cmList cppcheck_cmd{ runCmd, cmList::EmptyElements::Yes };
  429. // extract all the -D, -U, and -I options from the compile line
  430. for (auto const& opt : orig_cmd) {
  431. if (opt.size() > 2) {
  432. if ((opt[0] == '-') &&
  433. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  434. cppcheck_cmd.push_back(opt);
  435. // convert cl / options to - options if needed
  436. #if defined(_WIN32)
  437. } else if ((opt[0] == '/') &&
  438. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  439. std::string optcopy = opt;
  440. optcopy[0] = '-';
  441. cppcheck_cmd.push_back(optcopy);
  442. #endif
  443. }
  444. }
  445. }
  446. // add the source file
  447. cppcheck_cmd.push_back(sourceFile);
  448. // Run the cpplint command line. Capture its output.
  449. std::string stdOut;
  450. std::string stdErr;
  451. int ret;
  452. if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
  453. nullptr, cmSystemTools::OUTPUT_NONE)) {
  454. std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
  455. << "\n";
  456. return 1;
  457. }
  458. std::cerr << stdOut;
  459. // Output the output from cpplint to stderr
  460. if (stdErr.find("(error)") != std::string::npos ||
  461. stdErr.find("(warning)") != std::string::npos ||
  462. stdErr.find("(style)") != std::string::npos ||
  463. stdErr.find("(performance)") != std::string::npos ||
  464. stdErr.find("(portability)") != std::string::npos ||
  465. stdErr.find("(information)") != std::string::npos) {
  466. if (ret == 0) {
  467. std::cerr << "Warning: cppcheck reported diagnostics:\n";
  468. } else {
  469. std::cerr << "Error: cppcheck reported failure:\n";
  470. }
  471. }
  472. std::cerr << stdErr;
  473. return ret;
  474. }
  475. using CoCompileHandler = int (*)(const std::string&, const std::string&,
  476. const std::vector<std::string>&);
  477. struct CoCompiler
  478. {
  479. const char* Option;
  480. CoCompileHandler Handler;
  481. bool NoOriginalCommand;
  482. };
  483. const std::array<CoCompiler, 5> CoCompilers = {
  484. { // Table of options and handlers.
  485. { "--cppcheck=", HandleCppCheck, false },
  486. { "--cpplint=", HandleCppLint, false },
  487. { "--iwyu=", HandleIWYU, false },
  488. { "--lwyu=", HandleLWYU, true },
  489. { "--tidy=", HandleTidy, false } }
  490. };
  491. struct CoCompileJob
  492. {
  493. std::string Command;
  494. CoCompileHandler Handler;
  495. };
  496. }
  497. // called when args[0] == "__run_co_compile"
  498. int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
  499. {
  500. std::vector<CoCompileJob> jobs;
  501. std::string sourceFile; // store --source=
  502. cmList launchers; // store --launcher=
  503. // Default is to run the original command found after -- if the option
  504. // does not need to do that, it should be specified here, currently only
  505. // lwyu does that.
  506. bool runOriginalCmd = true;
  507. std::vector<std::string> orig_cmd;
  508. bool doing_options = true;
  509. for (std::string const& arg : cmMakeRange(args).advance(2)) {
  510. // if the arg is -- then the rest of the args after
  511. // go into orig_cmd
  512. if (arg == "--") {
  513. doing_options = false;
  514. } else if (doing_options) {
  515. bool optionFound = false;
  516. for (CoCompiler const& cc : CoCompilers) {
  517. size_t optionLen = strlen(cc.Option);
  518. if (arg.compare(0, optionLen, cc.Option) == 0) {
  519. optionFound = true;
  520. CoCompileJob job;
  521. job.Command = arg.substr(optionLen);
  522. job.Handler = cc.Handler;
  523. jobs.push_back(std::move(job));
  524. if (cc.NoOriginalCommand) {
  525. runOriginalCmd = false;
  526. }
  527. }
  528. }
  529. if (!optionFound) {
  530. if (cmHasLiteralPrefix(arg, "--source=")) {
  531. sourceFile = arg.substr(9);
  532. } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
  533. launchers.append(arg.substr(11), cmList::EmptyElements::Yes);
  534. } else {
  535. // if it was not a co-compiler or --source/--launcher then error
  536. std::cerr << "__run_co_compile given unknown argument: " << arg
  537. << "\n";
  538. return 1;
  539. }
  540. }
  541. } else { // if not doing_options then push to orig_cmd
  542. orig_cmd.push_back(arg);
  543. }
  544. }
  545. if (jobs.empty()) {
  546. std::cerr << "__run_co_compile missing command to run. "
  547. "Looking for one or more of the following:\n";
  548. for (CoCompiler const& cc : CoCompilers) {
  549. std::cerr << cc.Option << "\n";
  550. }
  551. return 1;
  552. }
  553. if (runOriginalCmd && orig_cmd.empty()) {
  554. std::cerr << "__run_co_compile missing compile command after --\n";
  555. return 1;
  556. }
  557. for (CoCompileJob const& job : jobs) {
  558. // call the command handler here
  559. int ret = job.Handler(job.Command, sourceFile, orig_cmd);
  560. // if the command returns non-zero then return and fail.
  561. // for commands that do not want to break the build, they should return
  562. // 0 no matter what.
  563. if (ret != 0) {
  564. return ret;
  565. }
  566. }
  567. // if there is no original command to run return now
  568. if (!runOriginalCmd) {
  569. return 0;
  570. }
  571. // Prepend launcher argument(s), if any
  572. if (!launchers.empty()) {
  573. orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
  574. }
  575. // Now run the real compiler command and return its result value
  576. int ret;
  577. if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
  578. nullptr,
  579. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  580. std::cerr << "Error running '" << orig_cmd[0] << "'\n";
  581. return 1;
  582. }
  583. // return the return value from the original compiler command
  584. return ret;
  585. }
  586. int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args,
  587. std::unique_ptr<cmConsoleBuf> consoleBuf)
  588. {
  589. // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
  590. if (args.size() > 1) {
  591. // Copy file
  592. if (args[1] == "copy" && args.size() > 3) {
  593. using CommandArgument =
  594. cmCommandLineArgument<bool(const std::string& value)>;
  595. cm::optional<std::string> targetArg;
  596. std::vector<CommandArgument> argParsers{
  597. { "-t", CommandArgument::Values::One,
  598. CommandArgument::setToValue(targetArg) },
  599. };
  600. std::vector<std::string> files;
  601. for (decltype(args.size()) i = 2; i < args.size(); i++) {
  602. const std::string& arg = args[i];
  603. bool matched = false;
  604. for (auto const& m : argParsers) {
  605. if (m.matches(arg)) {
  606. matched = true;
  607. if (m.parse(arg, i, args)) {
  608. break;
  609. }
  610. return 1; // failed to parse
  611. }
  612. }
  613. if (!matched) {
  614. files.push_back(arg);
  615. }
  616. }
  617. // If multiple source files specified,
  618. // then destination must be directory
  619. if (files.size() > 2 && !targetArg) {
  620. targetArg = files.back();
  621. files.pop_back();
  622. }
  623. if (targetArg && (!cmSystemTools::FileIsDirectory(*targetArg))) {
  624. std::cerr << "Error: Target (for copy command) \"" << *targetArg
  625. << "\" is not a directory.\n";
  626. return 1;
  627. }
  628. if (!targetArg) {
  629. if (files.size() < 2) {
  630. std::cerr
  631. << "Error: No files or target specified (for copy command).\n";
  632. return 1;
  633. }
  634. targetArg = files.back();
  635. files.pop_back();
  636. }
  637. // If error occurs we want to continue copying next files.
  638. bool return_value = false;
  639. for (auto const& file : files) {
  640. if (!cmsys::SystemTools::CopyFileAlways(file, *targetArg)) {
  641. std::cerr << "Error copying file \"" << file << "\" to \""
  642. << *targetArg << "\".\n";
  643. return_value = true;
  644. }
  645. }
  646. return return_value;
  647. }
  648. // Copy file if different.
  649. if (args[1] == "copy_if_different" && args.size() > 3) {
  650. // If multiple source files specified,
  651. // then destination must be directory
  652. if ((args.size() > 4) &&
  653. (!cmSystemTools::FileIsDirectory(args.back()))) {
  654. std::cerr << "Error: Target (for copy_if_different command) \""
  655. << args.back() << "\" is not a directory.\n";
  656. return 1;
  657. }
  658. // If error occurs we want to continue copying next files.
  659. bool return_value = false;
  660. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  661. if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
  662. std::cerr << "Error copying file (if different) from \"" << arg
  663. << "\" to \"" << args.back() << "\".\n";
  664. return_value = true;
  665. }
  666. }
  667. return return_value;
  668. }
  669. // Copy directory contents
  670. if ((args[1] == "copy_directory" ||
  671. args[1] == "copy_directory_if_different") &&
  672. args.size() > 3) {
  673. // If error occurs we want to continue copying next files.
  674. bool return_value = false;
  675. const bool copy_always = (args[1] == "copy_directory");
  676. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  677. if (!cmSystemTools::CopyADirectory(arg, args.back(), copy_always)) {
  678. std::cerr << "Error copying directory from \"" << arg << "\" to \""
  679. << args.back() << "\".\n";
  680. return_value = true;
  681. }
  682. }
  683. return return_value;
  684. }
  685. // Rename a file or directory
  686. if (args[1] == "rename" && args.size() == 4) {
  687. if (!cmSystemTools::RenameFile(args[2], args[3])) {
  688. std::string e = cmSystemTools::GetLastSystemError();
  689. std::cerr << "Error renaming from \"" << args[2] << "\" to \""
  690. << args[3] << "\": " << e << "\n";
  691. return 1;
  692. }
  693. return 0;
  694. }
  695. // Compare files
  696. if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
  697. bool filesDiffer;
  698. if (args.size() == 4) {
  699. filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
  700. } else if (args[2] == "--ignore-eol") {
  701. filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
  702. } else {
  703. CMakeCommandUsage(args[0]);
  704. return 2;
  705. }
  706. if (filesDiffer) {
  707. return 1;
  708. }
  709. return 0;
  710. }
  711. #if !defined(CMAKE_BOOTSTRAP)
  712. if (args[1] == "__create_def") {
  713. if (args.size() < 4) {
  714. std::cerr << "__create_def Usage: -E __create_def outfile.def "
  715. "objlistfile [--nm=nm-path]\n";
  716. return 1;
  717. }
  718. cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
  719. if (!fin) {
  720. std::cerr << "could not open object list file: " << args[3] << "\n";
  721. return 1;
  722. }
  723. std::vector<std::string> files;
  724. {
  725. std::string file;
  726. cmFileTime outTime;
  727. bool outValid = outTime.Load(args[2]);
  728. while (cmSystemTools::GetLineFromStream(fin, file)) {
  729. files.push_back(file);
  730. if (outValid) {
  731. cmFileTime inTime;
  732. outValid = inTime.Load(file) && inTime.Older(outTime);
  733. }
  734. }
  735. if (outValid) {
  736. // The def file already exists and all input files are older than
  737. // the existing def file.
  738. return 0;
  739. }
  740. }
  741. FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
  742. if (!fout) {
  743. std::cerr << "could not open output .def file: " << args[2] << "\n";
  744. return 1;
  745. }
  746. bindexplib deffile;
  747. if (args.size() >= 5) {
  748. std::string const& a = args[4];
  749. if (cmHasLiteralPrefix(a, "--nm=")) {
  750. deffile.SetNmPath(a.substr(5));
  751. } else {
  752. std::cerr << "unknown argument: " << a << "\n";
  753. }
  754. }
  755. for (std::string const& file : files) {
  756. std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
  757. if (cmSystemTools::LowerCase(ext) == ".def") {
  758. if (!deffile.AddDefinitionFile(file.c_str())) {
  759. return 1;
  760. }
  761. } else {
  762. if (!deffile.AddObjectFile(file.c_str())) {
  763. return 1;
  764. }
  765. }
  766. }
  767. deffile.WriteFile(fout);
  768. fclose(fout);
  769. return 0;
  770. }
  771. #endif
  772. if (args[1] == "__run_co_compile") {
  773. return cmcmd::HandleCoCompileCommands(args);
  774. }
  775. // Echo string
  776. if (args[1] == "echo") {
  777. std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
  778. return 0;
  779. }
  780. // Echo string no new line
  781. if (args[1] == "echo_append") {
  782. std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
  783. return 0;
  784. }
  785. if (args[1] == "env") {
  786. #ifndef CMAKE_BOOTSTRAP
  787. cmSystemTools::EnvDiff env;
  788. #endif
  789. auto ai = args.cbegin() + 2;
  790. auto ae = args.cend();
  791. for (; ai != ae; ++ai) {
  792. std::string const& a = *ai;
  793. if (a == "--") {
  794. // Stop parsing options/environment variables; the next argument
  795. // should be the command.
  796. ++ai;
  797. break;
  798. }
  799. if (cmHasLiteralPrefix(a, "--unset=")) {
  800. // Unset environment variable.
  801. #ifdef CMAKE_BOOTSTRAP
  802. cmSystemTools::UnPutEnv(a.substr(8));
  803. #else
  804. env.UnPutEnv(a.substr(8));
  805. #endif
  806. } else if (a == "--modify") {
  807. #ifdef CMAKE_BOOTSTRAP
  808. std::cerr
  809. << "cmake -E env: --modify not available during bootstrapping\n";
  810. return 1;
  811. #else
  812. if (++ai == ae) {
  813. std::cerr << "cmake -E env: --modify missing a parameter\n";
  814. return 1;
  815. }
  816. std::string const& op = *ai;
  817. if (!env.ParseOperation(op)) {
  818. std::cerr << "cmake -E env: invalid parameter to --modify: " << op
  819. << '\n';
  820. return 1;
  821. }
  822. #endif
  823. } else if (!a.empty() && a[0] == '-') {
  824. // Environment variable and command names cannot start in '-',
  825. // so this must be an unknown option.
  826. std::cerr << "cmake -E env: unknown option '" << a << "'\n";
  827. return 1;
  828. } else if (a.find('=') != std::string::npos) {
  829. // Set environment variable.
  830. #ifdef CMAKE_BOOTSTRAP
  831. cmSystemTools::PutEnv(a);
  832. #else
  833. env.PutEnv(a);
  834. #endif
  835. } else {
  836. // This is the beginning of the command.
  837. break;
  838. }
  839. }
  840. if (ai == ae) {
  841. std::cerr << "cmake -E env: no command given\n";
  842. return 1;
  843. }
  844. #ifndef CMAKE_BOOTSTRAP
  845. env.ApplyToCurrentEnv();
  846. #endif
  847. // Execute command from remaining arguments.
  848. std::vector<std::string> cmd(ai, ae);
  849. int retval;
  850. if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
  851. nullptr,
  852. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  853. return retval;
  854. }
  855. return 1;
  856. }
  857. #if !defined(CMAKE_BOOTSTRAP)
  858. if (args[1] == "environment") {
  859. for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
  860. std::cout << env << std::endl;
  861. }
  862. return 0;
  863. }
  864. #endif
  865. if (args[1] == "make_directory" && args.size() > 2) {
  866. // If an error occurs, we want to continue making directories.
  867. bool return_value = false;
  868. for (auto const& arg : cmMakeRange(args).advance(2)) {
  869. if (!cmSystemTools::MakeDirectory(arg)) {
  870. std::cerr << "Error creating directory \"" << arg << "\".\n";
  871. return_value = true;
  872. }
  873. }
  874. return return_value;
  875. }
  876. if (args[1] == "remove_directory" && args.size() > 2) {
  877. // If an error occurs, we want to continue removing directories.
  878. bool return_value = false;
  879. for (auto const& arg : cmMakeRange(args).advance(2)) {
  880. if (cmSystemTools::FileIsDirectory(arg)) {
  881. if (!cmRemoveDirectory(arg)) {
  882. return_value = true;
  883. }
  884. }
  885. }
  886. return return_value;
  887. }
  888. // Remove file
  889. if (args[1] == "remove" && args.size() > 2) {
  890. bool force = false;
  891. for (auto const& arg : cmMakeRange(args).advance(2)) {
  892. if (arg == "\\-f" || arg == "-f") {
  893. force = true;
  894. } else {
  895. // Complain if the file could not be removed, still exists,
  896. // and the -f option was not given.
  897. if (!cmSystemTools::RemoveFile(arg) && !force &&
  898. cmSystemTools::FileExists(arg)) {
  899. return 1;
  900. }
  901. }
  902. }
  903. return 0;
  904. }
  905. // Remove directories or files with rm
  906. if (args[1] == "rm" && args.size() > 2) {
  907. // If an error occurs, we want to continue removing the remaining
  908. // files/directories.
  909. int return_value = 0;
  910. bool force = false;
  911. bool recursive = false;
  912. bool doing_options = true;
  913. bool at_least_one_file = false;
  914. for (auto const& arg : cmMakeRange(args).advance(2)) {
  915. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  916. if (arg == "--") {
  917. doing_options = false;
  918. }
  919. if (arg.find('f') != std::string::npos) {
  920. force = true;
  921. }
  922. if (arg.find_first_of("rR") != std::string::npos) {
  923. recursive = true;
  924. }
  925. if (arg.find_first_not_of("-frR") != std::string::npos) {
  926. cmSystemTools::Error("Unknown -E rm argument: " + arg);
  927. return 1;
  928. }
  929. } else {
  930. if (arg.empty()) {
  931. continue;
  932. }
  933. at_least_one_file = true;
  934. // Complain if the -f option was not given and
  935. // either file does not exist or
  936. // file could not be removed and still exists
  937. bool file_exists_or_forced_remove =
  938. cmSystemTools::PathExists(arg) || force;
  939. if (cmSystemTools::FileIsDirectory(arg)) {
  940. if (!cmRemoveDirectory(arg, recursive)) {
  941. return_value = 1;
  942. }
  943. } else if ((!file_exists_or_forced_remove) ||
  944. (!cmSystemTools::RemoveFile(arg) &&
  945. cmSystemTools::FileExists(arg))) {
  946. if (!file_exists_or_forced_remove) {
  947. cmSystemTools::Error(
  948. "File to remove does not exist and force is not set: " + arg);
  949. } else {
  950. cmSystemTools::Error("File can't be removed and still exist: " +
  951. arg);
  952. }
  953. return_value = 1;
  954. }
  955. }
  956. }
  957. if (!at_least_one_file) {
  958. cmSystemTools::Error("Missing file/directory to remove");
  959. return 1;
  960. }
  961. return return_value;
  962. }
  963. // Touch file
  964. if (args[1] == "touch" && args.size() > 2) {
  965. for (auto const& arg : cmMakeRange(args).advance(2)) {
  966. if (!cmSystemTools::Touch(arg, true)) {
  967. std::cerr << "cmake -E touch: failed to update \"";
  968. std::cerr << arg << "\".\n";
  969. return 1;
  970. }
  971. }
  972. return 0;
  973. }
  974. // Touch file
  975. if (args[1] == "touch_nocreate" && args.size() > 2) {
  976. for (auto const& arg : cmMakeRange(args).advance(2)) {
  977. if (!cmSystemTools::Touch(arg, false)) {
  978. std::cerr << "cmake -E touch_nocreate: failed to update \"";
  979. std::cerr << arg << "\".\n";
  980. return 1;
  981. }
  982. }
  983. return 0;
  984. }
  985. // capabilities
  986. if (args[1] == "capabilities") {
  987. if (args.size() > 2) {
  988. std::cerr << "-E capabilities accepts no additional arguments\n";
  989. return 1;
  990. }
  991. cmake cm(cmake::RoleInternal, cmState::Unknown);
  992. std::cout << cm.ReportCapabilities();
  993. return 0;
  994. }
  995. // Sleep command
  996. if (args[1] == "sleep" && args.size() > 2) {
  997. double total = 0;
  998. for (auto const& arg : cmMakeRange(args).advance(2)) {
  999. double num = 0.0;
  1000. char unit;
  1001. char extra;
  1002. int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
  1003. if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
  1004. total += num;
  1005. } else {
  1006. std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
  1007. return 1;
  1008. }
  1009. }
  1010. if (total > 0) {
  1011. cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
  1012. }
  1013. return 0;
  1014. }
  1015. // Clock command
  1016. if (args[1] == "time" && args.size() > 2) {
  1017. std::vector<std::string> command(args.begin() + 2, args.end());
  1018. int ret = 0;
  1019. auto time_start = std::chrono::steady_clock::now();
  1020. cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret, nullptr,
  1021. cmSystemTools::OUTPUT_PASSTHROUGH);
  1022. auto time_finish = std::chrono::steady_clock::now();
  1023. std::chrono::duration<double> time_elapsed = time_finish - time_start;
  1024. std::cout << "Elapsed time (seconds): " << time_elapsed.count() << "\n";
  1025. return ret;
  1026. }
  1027. // Command to calculate the md5sum of a file
  1028. if (args[1] == "md5sum" && args.size() >= 3) {
  1029. return HashSumFile(args, cmCryptoHash::AlgoMD5);
  1030. }
  1031. // Command to calculate the sha1sum of a file
  1032. if (args[1] == "sha1sum" && args.size() >= 3) {
  1033. return HashSumFile(args, cmCryptoHash::AlgoSHA1);
  1034. }
  1035. if (args[1] == "sha224sum" && args.size() >= 3) {
  1036. return HashSumFile(args, cmCryptoHash::AlgoSHA224);
  1037. }
  1038. if (args[1] == "sha256sum" && args.size() >= 3) {
  1039. return HashSumFile(args, cmCryptoHash::AlgoSHA256);
  1040. }
  1041. if (args[1] == "sha384sum" && args.size() >= 3) {
  1042. return HashSumFile(args, cmCryptoHash::AlgoSHA384);
  1043. }
  1044. if (args[1] == "sha512sum" && args.size() >= 3) {
  1045. return HashSumFile(args, cmCryptoHash::AlgoSHA512);
  1046. }
  1047. // Command to concat files into one
  1048. if (args[1] == "cat" && args.size() >= 3) {
  1049. int return_value = 0;
  1050. bool doing_options = true;
  1051. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1052. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  1053. if (arg == "--") {
  1054. doing_options = false;
  1055. } else {
  1056. cmSystemTools::Error(arg + ": option not handled");
  1057. return_value = 1;
  1058. }
  1059. } else if (!cmSystemTools::TestFileAccess(arg,
  1060. cmsys::TEST_FILE_READ) &&
  1061. cmSystemTools::TestFileAccess(arg, cmsys::TEST_FILE_OK)) {
  1062. cmSystemTools::Error(arg + ": permission denied (ignoring)");
  1063. return_value = 1;
  1064. } else if (cmSystemTools::FileIsDirectory(arg)) {
  1065. cmSystemTools::Error(arg + ": is a directory (ignoring)");
  1066. return_value = 1;
  1067. } else if (!cmSystemTools::FileExists(arg)) {
  1068. cmSystemTools::Error(arg + ": no such file or directory (ignoring)");
  1069. return_value = 1;
  1070. } else if (cmSystemTools::FileLength(arg) == 0) {
  1071. // Ignore empty files, this is not an error
  1072. } else {
  1073. // Destroy console buffers to drop cout/cerr encoding transform.
  1074. consoleBuf.reset();
  1075. cmCatFile(arg);
  1076. }
  1077. }
  1078. return return_value;
  1079. }
  1080. // Command to change directory and run a program.
  1081. if (args[1] == "chdir" && args.size() >= 4) {
  1082. std::string const& directory = args[2];
  1083. if (!cmSystemTools::FileExists(directory)) {
  1084. cmSystemTools::Error("Directory does not exist for chdir command: " +
  1085. directory);
  1086. return 1;
  1087. }
  1088. std::string command =
  1089. cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
  1090. int retval = 0;
  1091. if (cmSystemTools::RunSingleCommand(
  1092. command, nullptr, nullptr, &retval, directory.c_str(),
  1093. cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
  1094. return retval;
  1095. }
  1096. return 1;
  1097. }
  1098. // Command to start progress for a build
  1099. if (args[1] == "cmake_progress_start" && args.size() == 4) {
  1100. // basically remove the directory
  1101. std::string dirName = cmStrCat(args[2], "/Progress");
  1102. cmSystemTools::RemoveADirectory(dirName);
  1103. // is the last argument a filename that exists?
  1104. FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
  1105. int count;
  1106. if (countFile) {
  1107. if (1 != fscanf(countFile, "%i", &count)) {
  1108. std::cerr << "Could not read from count file.\n";
  1109. }
  1110. fclose(countFile);
  1111. } else {
  1112. count = atoi(args[3].c_str());
  1113. }
  1114. if (count) {
  1115. cmSystemTools::MakeDirectory(dirName);
  1116. // write the count into the directory
  1117. std::string fName = cmStrCat(dirName, "/count.txt");
  1118. FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
  1119. if (progFile) {
  1120. fprintf(progFile, "%i\n", count);
  1121. fclose(progFile);
  1122. }
  1123. }
  1124. return 0;
  1125. }
  1126. // Command to report progress for a build
  1127. if (args[1] == "cmake_progress_report" && args.size() >= 3) {
  1128. // This has been superseded by cmake_echo_color --progress-*
  1129. // options. We leave it here to avoid errors if somehow this
  1130. // is invoked by an existing makefile without regenerating.
  1131. return 0;
  1132. }
  1133. // Command to create a symbolic link. Fails on platforms not
  1134. // supporting them.
  1135. if (args[1] == "create_symlink" && args.size() == 4) {
  1136. std::string const& destinationFileName = args[3];
  1137. if (cmSystemTools::PathExists(destinationFileName) &&
  1138. !cmSystemTools::RemoveFile(destinationFileName)) {
  1139. std::string emsg = cmSystemTools::GetLastSystemError();
  1140. std::cerr << "failed to create symbolic link '" << destinationFileName
  1141. << "' because existing path cannot be removed: " << emsg
  1142. << "\n";
  1143. return 1;
  1144. }
  1145. if (!cmSystemTools::CreateSymlink(args[2], destinationFileName)) {
  1146. return 1;
  1147. }
  1148. return 0;
  1149. }
  1150. // Command to create a hard link. Fails on platforms not
  1151. // supporting them.
  1152. if (args[1] == "create_hardlink" && args.size() == 4) {
  1153. std::string const& sourceFileName = args[2];
  1154. std::string const& destinationFileName = args[3];
  1155. if (!cmSystemTools::FileExists(sourceFileName)) {
  1156. std::cerr << "failed to create hard link because source path '"
  1157. << sourceFileName << "' does not exist \n";
  1158. return 1;
  1159. }
  1160. if (cmSystemTools::PathExists(destinationFileName) &&
  1161. !cmSystemTools::RemoveFile(destinationFileName)) {
  1162. std::string emsg = cmSystemTools::GetLastSystemError();
  1163. std::cerr << "failed to create hard link '" << destinationFileName
  1164. << "' because existing path cannot be removed: " << emsg
  1165. << "\n";
  1166. return 1;
  1167. }
  1168. if (!cmSystemTools::CreateLink(sourceFileName, destinationFileName)) {
  1169. return 1;
  1170. }
  1171. return 0;
  1172. }
  1173. // Command to do nothing with an exit code of 0.
  1174. if (args[1] == "true") {
  1175. return 0;
  1176. }
  1177. // Command to do nothing with an exit code of 1.
  1178. if (args[1] == "false") {
  1179. return 1;
  1180. }
  1181. // Internal CMake shared library support.
  1182. if (args[1] == "cmake_symlink_library" && args.size() == 5) {
  1183. return cmcmd::SymlinkLibrary(args);
  1184. }
  1185. // Internal CMake versioned executable support.
  1186. if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
  1187. return cmcmd::SymlinkExecutable(args);
  1188. }
  1189. // Internal CMake dependency scanning support.
  1190. if (args[1] == "cmake_depends" && args.size() >= 6) {
  1191. const bool verbose = isCMakeVerbose();
  1192. // Create a cmake object instance to process dependencies.
  1193. // All we need is the `set` command.
  1194. cmake cm(cmake::RoleScript, cmState::Unknown);
  1195. std::string gen;
  1196. std::string homeDir;
  1197. std::string startDir;
  1198. std::string homeOutDir;
  1199. std::string startOutDir;
  1200. std::string depInfo;
  1201. bool color = false;
  1202. if (args.size() >= 8) {
  1203. // Full signature:
  1204. //
  1205. // -E cmake_depends <generator>
  1206. // <home-src-dir> <start-src-dir>
  1207. // <home-out-dir> <start-out-dir>
  1208. // <dep-info> [--color=$(COLOR)]
  1209. //
  1210. // All paths are provided.
  1211. gen = args[2];
  1212. homeDir = args[3];
  1213. startDir = args[4];
  1214. homeOutDir = args[5];
  1215. startOutDir = args[6];
  1216. depInfo = args[7];
  1217. if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
  1218. // Enable or disable color based on the switch value.
  1219. color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
  1220. }
  1221. } else {
  1222. // Support older signature for existing makefiles:
  1223. //
  1224. // -E cmake_depends <generator>
  1225. // <home-out-dir> <start-out-dir>
  1226. // <dep-info>
  1227. //
  1228. // Just pretend the source directories are the same as the
  1229. // binary directories so at least scanning will work.
  1230. gen = args[2];
  1231. homeDir = args[3];
  1232. startDir = args[4];
  1233. homeOutDir = args[3];
  1234. startOutDir = args[3];
  1235. depInfo = args[5];
  1236. }
  1237. // Create a local generator configured for the directory in
  1238. // which dependencies will be scanned.
  1239. homeDir = cmSystemTools::CollapseFullPath(homeDir);
  1240. startDir = cmSystemTools::CollapseFullPath(startDir);
  1241. homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
  1242. startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
  1243. cm.SetHomeDirectory(homeDir);
  1244. cm.SetHomeOutputDirectory(homeOutDir);
  1245. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1246. if (auto ggd = cm.CreateGlobalGenerator(gen)) {
  1247. cm.SetGlobalGenerator(std::move(ggd));
  1248. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1249. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1250. snapshot.GetDirectory().SetCurrentSource(startDir);
  1251. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1252. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1253. // FIXME: With advanced add_subdirectory usage, these are
  1254. // not necessarily the same as the generator originally used.
  1255. // We should pass all these directories through an info file.
  1256. lgd->SetRelativePathTop(homeDir, homeOutDir);
  1257. // Actually scan dependencies.
  1258. return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
  1259. }
  1260. return 1;
  1261. }
  1262. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  1263. // Internal CMake compiler dependencies filtering
  1264. if (args[1] == "cmake_cl_compile_depends") {
  1265. return CLCompileAndDependencies(args);
  1266. }
  1267. #endif
  1268. // Internal CMake link script support.
  1269. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1270. return cmcmd::ExecuteLinkScript(args);
  1271. }
  1272. #if !defined(CMAKE_BOOTSTRAP)
  1273. // Internal CMake ninja dependency scanning support.
  1274. if (args[1] == "cmake_ninja_depends") {
  1275. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1276. }
  1277. // Internal CMake ninja dyndep support.
  1278. if (args[1] == "cmake_ninja_dyndep") {
  1279. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1280. }
  1281. #endif
  1282. // Internal CMake unimplemented feature notification.
  1283. if (args[1] == "cmake_unimplemented_variable") {
  1284. std::cerr << "Feature not implemented for this platform.";
  1285. if (args.size() == 3) {
  1286. std::cerr << " Variable " << args[2] << " is not set.";
  1287. }
  1288. std::cerr << std::endl;
  1289. return 1;
  1290. }
  1291. if (args[1] == "vs_link_exe") {
  1292. return cmcmd::VisualStudioLink(args, 1);
  1293. }
  1294. if (args[1] == "vs_link_dll") {
  1295. return cmcmd::VisualStudioLink(args, 2);
  1296. }
  1297. if (args[1] == "cmake_llvm_rc") {
  1298. return cmcmd::RunLLVMRC(args);
  1299. }
  1300. // Internal CMake color makefile support.
  1301. if (args[1] == "cmake_echo_color") {
  1302. return cmcmd::ExecuteEchoColor(args);
  1303. }
  1304. #ifndef CMAKE_BOOTSTRAP
  1305. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1306. cm::string_view const infoFile = args[2];
  1307. cm::string_view const config = args[3];
  1308. cm::string_view const executableConfig =
  1309. (args.size() >= 5) ? cm::string_view(args[4]) : cm::string_view();
  1310. return cmQtAutoMocUic(infoFile, config, executableConfig) ? 0 : 1;
  1311. }
  1312. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1313. cm::string_view const infoFile = args[2];
  1314. cm::string_view const config =
  1315. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1316. cm::string_view const executableConfig =
  1317. (args.size() >= 5) ? cm::string_view(args[4]) : cm::string_view();
  1318. return cmQtAutoRcc(infoFile, config, executableConfig) ? 0 : 1;
  1319. }
  1320. #endif
  1321. // Tar files
  1322. if (args[1] == "tar" && args.size() > 3) {
  1323. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1324. std::string const& flags = args[2];
  1325. std::string const& outFile = args[3];
  1326. std::vector<std::string> files;
  1327. std::string mtime;
  1328. std::string format;
  1329. cmSystemTools::cmTarExtractTimestamps extractTimestamps =
  1330. cmSystemTools::cmTarExtractTimestamps::Yes;
  1331. cmSystemTools::cmTarCompression compress =
  1332. cmSystemTools::TarCompressNone;
  1333. int nCompress = 0;
  1334. bool doing_options = true;
  1335. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1336. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1337. if (arg == "--") {
  1338. doing_options = false;
  1339. } else if (arg == "--zstd") {
  1340. compress = cmSystemTools::TarCompressZstd;
  1341. ++nCompress;
  1342. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1343. mtime = arg.substr(8);
  1344. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1345. std::string const& files_from = arg.substr(13);
  1346. if (!cmTarFilesFrom(files_from, files)) {
  1347. return 1;
  1348. }
  1349. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1350. format = arg.substr(9);
  1351. if (!cm::contains(knownFormats, format)) {
  1352. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1353. format);
  1354. return 1;
  1355. }
  1356. } else if (arg == "--touch") {
  1357. extractTimestamps = cmSystemTools::cmTarExtractTimestamps::No;
  1358. } else {
  1359. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1360. return 1;
  1361. }
  1362. } else {
  1363. files.push_back(arg);
  1364. }
  1365. }
  1366. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1367. bool verbose = false;
  1368. for (auto flag : flags) {
  1369. switch (flag) {
  1370. case '-':
  1371. case 'f': {
  1372. // Keep for backward compatibility. Ignored
  1373. } break;
  1374. case 'j': {
  1375. compress = cmSystemTools::TarCompressBZip2;
  1376. ++nCompress;
  1377. } break;
  1378. case 'J': {
  1379. compress = cmSystemTools::TarCompressXZ;
  1380. ++nCompress;
  1381. } break;
  1382. case 'z': {
  1383. compress = cmSystemTools::TarCompressGZip;
  1384. ++nCompress;
  1385. } break;
  1386. case 'v': {
  1387. verbose = true;
  1388. } break;
  1389. case 't': {
  1390. action = cmSystemTools::TarActionList;
  1391. } break;
  1392. case 'c': {
  1393. action = cmSystemTools::TarActionCreate;
  1394. } break;
  1395. case 'x': {
  1396. action = cmSystemTools::TarActionExtract;
  1397. } break;
  1398. default: {
  1399. std::cerr << "tar: Unknown argument: " << flag << "\n";
  1400. }
  1401. }
  1402. }
  1403. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1404. cmSystemTools::Error("Can not use compression flags with format: " +
  1405. format);
  1406. return 1;
  1407. }
  1408. if (nCompress > 1) {
  1409. cmSystemTools::Error("Can only compress a tar file one way; "
  1410. "at most one flag of z, j, or J may be used");
  1411. return 1;
  1412. }
  1413. if (action == cmSystemTools::TarActionList) {
  1414. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1415. cmSystemTools::Error("Problem listing tar: " + outFile);
  1416. return 1;
  1417. }
  1418. } else if (action == cmSystemTools::TarActionCreate) {
  1419. if (files.empty()) {
  1420. std::cerr << "tar: No files or directories specified\n";
  1421. }
  1422. if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
  1423. format)) {
  1424. cmSystemTools::Error("Problem creating tar: " + outFile);
  1425. return 1;
  1426. }
  1427. } else if (action == cmSystemTools::TarActionExtract) {
  1428. if (!cmSystemTools::ExtractTar(outFile, files, extractTimestamps,
  1429. verbose)) {
  1430. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1431. return 1;
  1432. }
  1433. #ifdef _WIN32
  1434. // OK, on windows 7 after we untar some files,
  1435. // sometimes we can not rename the directory after
  1436. // the untar is done. This breaks the external project
  1437. // untar and rename code. So, by default we will wait
  1438. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1439. // is set in the env, its value will be used instead of 100.
  1440. int delay = 100;
  1441. std::string delayVar;
  1442. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1443. delay = atoi(delayVar.c_str());
  1444. }
  1445. if (delay) {
  1446. cmSystemTools::Delay(delay);
  1447. }
  1448. #endif
  1449. } else {
  1450. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1451. "(list), 'c' (create) or 'x' (extract)");
  1452. return 1;
  1453. }
  1454. return 0;
  1455. }
  1456. if (args[1] == "server") {
  1457. cmSystemTools::Error(
  1458. "CMake server mode has been removed in favor of the file-api.");
  1459. return 1;
  1460. }
  1461. #if !defined(CMAKE_BOOTSTRAP)
  1462. // Internal CMake Fortran module support.
  1463. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1464. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1465. }
  1466. #endif
  1467. #if defined(_WIN32) && !defined(__CYGWIN__)
  1468. // Write registry value
  1469. if (args[1] == "write_regv" && args.size() > 3) {
  1470. return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
  1471. }
  1472. // Delete registry value
  1473. if (args[1] == "delete_regv" && args.size() > 2) {
  1474. return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
  1475. }
  1476. // Remove file
  1477. if (args[1] == "comspec" && args.size() > 2) {
  1478. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1479. return 1;
  1480. }
  1481. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1482. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1483. }
  1484. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1485. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1486. }
  1487. #endif
  1488. // Internal depfile transformation
  1489. if (args[1] == "cmake_transform_depfile" && args.size() == 10) {
  1490. auto format = cmDepfileFormat::GccDepfile;
  1491. if (args[3] == "gccdepfile") {
  1492. format = cmDepfileFormat::GccDepfile;
  1493. } else if (args[3] == "makedepfile") {
  1494. format = cmDepfileFormat::MakeDepfile;
  1495. } else if (args[3] == "MSBuildAdditionalInputs") {
  1496. format = cmDepfileFormat::MSBuildAdditionalInputs;
  1497. } else {
  1498. return 1;
  1499. }
  1500. // Create a cmake object instance to process dependencies.
  1501. // All we need is the `set` command.
  1502. cmake cm(cmake::RoleScript, cmState::Unknown);
  1503. std::string homeDir;
  1504. std::string startDir;
  1505. std::string homeOutDir;
  1506. std::string startOutDir;
  1507. homeDir = cmSystemTools::CollapseFullPath(args[4]);
  1508. startDir = cmSystemTools::CollapseFullPath(args[5]);
  1509. homeOutDir = cmSystemTools::CollapseFullPath(args[6]);
  1510. startOutDir = cmSystemTools::CollapseFullPath(args[7]);
  1511. cm.SetHomeDirectory(homeDir);
  1512. cm.SetHomeOutputDirectory(homeOutDir);
  1513. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1514. if (auto ggd = cm.CreateGlobalGenerator(args[2])) {
  1515. cm.SetGlobalGenerator(std::move(ggd));
  1516. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1517. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1518. snapshot.GetDirectory().SetCurrentSource(startDir);
  1519. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1520. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1521. // FIXME: With advanced add_subdirectory usage, these are
  1522. // not necessarily the same as the generator originally used.
  1523. // We should pass all these directories through an info file.
  1524. lgd->SetRelativePathTop(homeDir, homeOutDir);
  1525. return cmTransformDepfile(format, *lgd, args[8], args[9]) ? 0 : 2;
  1526. }
  1527. return 1;
  1528. }
  1529. }
  1530. CMakeCommandUsage(args[0]);
  1531. return 1;
  1532. }
  1533. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1534. cmCryptoHash::Algo algo)
  1535. {
  1536. if (args.size() < 3) {
  1537. return -1;
  1538. }
  1539. int retval = 0;
  1540. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1541. // Cannot compute sum of a directory
  1542. if (cmSystemTools::FileIsDirectory(filename)) {
  1543. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1544. retval++;
  1545. } else {
  1546. cmCryptoHash hasher(algo);
  1547. std::string value = hasher.HashFile(filename);
  1548. if (value.empty()) {
  1549. // To mimic "md5sum/shasum" behavior in a shell:
  1550. std::cerr << filename << ": No such file or directory" << std::endl;
  1551. retval++;
  1552. } else {
  1553. std::cout << value << " " << filename << std::endl;
  1554. }
  1555. }
  1556. }
  1557. return retval;
  1558. }
  1559. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1560. {
  1561. int result = 0;
  1562. std::string realName = args[2];
  1563. std::string soName = args[3];
  1564. std::string name = args[4];
  1565. cmSystemTools::ConvertToUnixSlashes(realName);
  1566. cmSystemTools::ConvertToUnixSlashes(soName);
  1567. cmSystemTools::ConvertToUnixSlashes(name);
  1568. if (soName != realName) {
  1569. cmsys::Status status = cmcmd::SymlinkInternal(realName, soName);
  1570. if (!status) {
  1571. cmSystemTools::Error(
  1572. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1573. result = 1;
  1574. }
  1575. }
  1576. if (name != soName) {
  1577. cmsys::Status status = cmcmd::SymlinkInternal(soName, name);
  1578. if (!status) {
  1579. cmSystemTools::Error(
  1580. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1581. result = 1;
  1582. }
  1583. }
  1584. return result;
  1585. }
  1586. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1587. {
  1588. int result = 0;
  1589. std::string const& realName = args[2];
  1590. std::string const& name = args[3];
  1591. if (name != realName) {
  1592. cmsys::Status status = cmcmd::SymlinkInternal(realName, name);
  1593. if (!status) {
  1594. cmSystemTools::Error(cmStrCat("cmake_symlink_executable: System Error: ",
  1595. status.GetString()));
  1596. result = 1;
  1597. }
  1598. }
  1599. return result;
  1600. }
  1601. cmsys::Status cmcmd::SymlinkInternal(std::string const& file,
  1602. std::string const& link)
  1603. {
  1604. if (cmSystemTools::PathExists(link)) {
  1605. cmSystemTools::RemoveFile(link);
  1606. }
  1607. std::string linktext = cmSystemTools::GetFilenameName(file);
  1608. #if defined(_WIN32) && !defined(__CYGWIN__)
  1609. cmsys::Status status = cmSystemTools::CreateSymlinkQuietly(linktext, link);
  1610. // Creating a symlink will fail with ERROR_PRIVILEGE_NOT_HELD if the user
  1611. // does not have SeCreateSymbolicLinkPrivilege, or if developer mode is not
  1612. // active. In that case, we try to copy the file.
  1613. if (status.GetWindows() == ERROR_PRIVILEGE_NOT_HELD) {
  1614. status = cmSystemTools::CopyFileAlways(file, link);
  1615. } else if (!status) {
  1616. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", link,
  1617. "': ", status.GetString()));
  1618. }
  1619. return status;
  1620. #else
  1621. return cmSystemTools::CreateSymlink(linktext, link);
  1622. #endif
  1623. }
  1624. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1625. {
  1626. std::string dirName = cmStrCat(dir, "/Progress");
  1627. std::string fName;
  1628. FILE* progFile;
  1629. // read the count
  1630. fName = cmStrCat(dirName, "/count.txt");
  1631. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1632. int count = 0;
  1633. if (!progFile) {
  1634. return;
  1635. }
  1636. if (1 != fscanf(progFile, "%i", &count)) {
  1637. std::cerr << "Could not read from progress file.\n";
  1638. }
  1639. fclose(progFile);
  1640. const char* last = num.c_str();
  1641. for (const char* c = last;; ++c) {
  1642. if (*c == ',' || *c == '\0') {
  1643. if (c != last) {
  1644. fName = cmStrCat(dirName, '/');
  1645. fName.append(last, c - last);
  1646. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1647. if (progFile) {
  1648. fprintf(progFile, "empty");
  1649. fclose(progFile);
  1650. }
  1651. }
  1652. if (*c == '\0') {
  1653. break;
  1654. }
  1655. last = c + 1;
  1656. }
  1657. }
  1658. int fileNum =
  1659. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1660. if (count > 0) {
  1661. // print the progress
  1662. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1663. }
  1664. }
  1665. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1666. {
  1667. // The arguments are
  1668. // args[0] == <cmake-executable>
  1669. // args[1] == cmake_echo_color
  1670. bool enabled = true;
  1671. int color = cmsysTerminal_Color_Normal;
  1672. bool newline = true;
  1673. std::string progressDir;
  1674. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1675. if (cmHasLiteralPrefix(arg, "--switch=")) {
  1676. // Enable or disable color based on the switch value.
  1677. std::string value = arg.substr(9);
  1678. if (!value.empty()) {
  1679. enabled = cmIsOn(value);
  1680. }
  1681. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1682. progressDir = arg.substr(15);
  1683. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1684. if (!progressDir.empty()) {
  1685. std::string const& progressNum = arg.substr(15);
  1686. cmcmdProgressReport(progressDir, progressNum);
  1687. }
  1688. } else if (arg == "--normal") {
  1689. color = cmsysTerminal_Color_Normal;
  1690. } else if (arg == "--black") {
  1691. color = cmsysTerminal_Color_ForegroundBlack;
  1692. } else if (arg == "--red") {
  1693. color = cmsysTerminal_Color_ForegroundRed;
  1694. } else if (arg == "--green") {
  1695. color = cmsysTerminal_Color_ForegroundGreen;
  1696. } else if (arg == "--yellow") {
  1697. color = cmsysTerminal_Color_ForegroundYellow;
  1698. } else if (arg == "--blue") {
  1699. color = cmsysTerminal_Color_ForegroundBlue;
  1700. } else if (arg == "--magenta") {
  1701. color = cmsysTerminal_Color_ForegroundMagenta;
  1702. } else if (arg == "--cyan") {
  1703. color = cmsysTerminal_Color_ForegroundCyan;
  1704. } else if (arg == "--white") {
  1705. color = cmsysTerminal_Color_ForegroundWhite;
  1706. } else if (arg == "--bold") {
  1707. color |= cmsysTerminal_Color_ForegroundBold;
  1708. } else if (arg == "--no-newline") {
  1709. newline = false;
  1710. } else if (arg == "--newline") {
  1711. newline = true;
  1712. } else {
  1713. // Color is enabled. Print with the current color.
  1714. cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
  1715. }
  1716. }
  1717. return 0;
  1718. }
  1719. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1720. {
  1721. // The arguments are
  1722. // args[0] == <cmake-executable>
  1723. // args[1] == cmake_link_script
  1724. // args[2] == <link-script-name>
  1725. // args[3] == --verbose=?
  1726. bool verbose = false;
  1727. if (args.size() >= 4) {
  1728. if (cmHasLiteralPrefix(args[3], "--verbose=")) {
  1729. if (!cmIsOff(args[3].substr(10))) {
  1730. verbose = true;
  1731. }
  1732. }
  1733. }
  1734. // Read command lines from the script.
  1735. cmsys::ifstream fin(args[2].c_str());
  1736. if (!fin) {
  1737. std::cerr << "Error opening link script \"" << args[2] << "\""
  1738. << std::endl;
  1739. return 1;
  1740. }
  1741. // Run one command at a time.
  1742. std::string command;
  1743. int result = 0;
  1744. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1745. // Skip empty command lines.
  1746. if (command.find_first_not_of(" \t") == std::string::npos) {
  1747. continue;
  1748. }
  1749. // Allocate a process instance.
  1750. cmUVProcessChainBuilder builder;
  1751. // Children should share stdout and stderr with this process.
  1752. builder
  1753. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1754. cm_fileno(stdout))
  1755. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR,
  1756. cm_fileno(stderr));
  1757. // Setup this command line.
  1758. std::vector<std::string> args2;
  1759. #ifdef _WIN32
  1760. cmSystemTools::ParseWindowsCommandLine(command.c_str(), args2);
  1761. #else
  1762. cmSystemTools::ParseUnixCommandLine(command.c_str(), args2);
  1763. #endif
  1764. builder.AddCommand(args2);
  1765. // Report the command if verbose output is enabled.
  1766. if (verbose) {
  1767. std::cout << command << std::endl;
  1768. }
  1769. // Run the command and wait for it to exit.
  1770. auto chain = builder.Start();
  1771. chain.Wait();
  1772. // Report failure if any.
  1773. auto const& status = chain.GetStatus(0);
  1774. auto exception = status.GetException();
  1775. switch (exception.first) {
  1776. case cmUVProcessChain::ExceptionCode::None:
  1777. if (status.ExitStatus != 0) {
  1778. result = static_cast<int>(status.ExitStatus);
  1779. }
  1780. break;
  1781. case cmUVProcessChain::ExceptionCode::Spawn:
  1782. std::cerr << "Error running link command: " << exception.second;
  1783. result = 2;
  1784. break;
  1785. default:
  1786. std::cerr << "Error running link command: " << exception.second;
  1787. result = 1;
  1788. break;
  1789. }
  1790. }
  1791. // Return the final resulting return value.
  1792. return result;
  1793. }
  1794. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1795. {
  1796. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1797. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1798. parser.ParseVersion(version);
  1799. if (parser.Found()) {
  1800. /* clang-format off */
  1801. std::cout << "@echo off\n"
  1802. "echo Environment Selection: " << name << "\n"
  1803. "set PATH=" << parser.GetPathDirectories() << "\n"
  1804. "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
  1805. "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1806. /* clang-format on */
  1807. return 0;
  1808. }
  1809. #else
  1810. (void)version;
  1811. #endif
  1812. std::cerr << "Could not find " << name;
  1813. return -1;
  1814. }
  1815. int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
  1816. const std::string& intermediate_file)
  1817. {
  1818. cmUVProcessChainBuilder builder;
  1819. uv_fs_t fs_req;
  1820. int preprocessedFile =
  1821. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1822. 0644, nullptr);
  1823. uv_fs_req_cleanup(&fs_req);
  1824. builder
  1825. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1826. preprocessedFile)
  1827. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1828. .AddCommand(command);
  1829. auto process = builder.Start();
  1830. if (!process.Valid() || process.GetStatus(0).SpawnResult != 0) {
  1831. std::cerr << "Failed to start preprocessor.";
  1832. return 1;
  1833. }
  1834. if (!process.Wait()) {
  1835. std::cerr << "Failed to wait for preprocessor";
  1836. return 1;
  1837. }
  1838. if (process.GetStatus(0).ExitStatus != 0) {
  1839. cmUVPipeIStream errorStream(process.GetLoop(), process.ErrorStream());
  1840. std::cerr << errorStream.rdbuf();
  1841. return 1;
  1842. }
  1843. return 0;
  1844. }
  1845. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1846. {
  1847. // The arguments are
  1848. // args[0] == <cmake-executable>
  1849. // args[1] == cmake_llvm_rc
  1850. // args[2] == source_file_path
  1851. // args[3] == intermediate_file
  1852. // args[4..n] == preprocess+args
  1853. // args[n+1] == ++
  1854. // args[n+2...] == llvm-rc+args
  1855. if (args.size() < 3) {
  1856. std::cerr << "Invalid cmake_llvm_rc arguments";
  1857. return 1;
  1858. }
  1859. const std::string& intermediate_file = args[3];
  1860. const std::string& source_file = args[2];
  1861. std::vector<std::string> preprocess;
  1862. std::vector<std::string> resource_compile;
  1863. std::vector<std::string>* pArgTgt = &preprocess;
  1864. static const cmsys::RegularExpression llvm_rc_only_single_arg("^[-/](N|Y)");
  1865. static const cmsys::RegularExpression llvm_rc_only_double_arg(
  1866. "^[-/](C|LN|L)(.)?");
  1867. static const cmsys::RegularExpression common_double_arg(
  1868. "^[-/](D|U|I|FO|fo|Fo)(.)?");
  1869. bool acceptNextArg = false;
  1870. bool skipNextArg = false;
  1871. for (std::string const& arg : cmMakeRange(args).advance(4)) {
  1872. if (skipNextArg) {
  1873. skipNextArg = false;
  1874. continue;
  1875. }
  1876. // We use ++ as separator between the preprocessing step definition and
  1877. // the rc compilation step because we need to prepend a -- to separate the
  1878. // source file properly from other options when using clang-cl for
  1879. // preprocessing.
  1880. if (arg == "++") {
  1881. pArgTgt = &resource_compile;
  1882. skipNextArg = false;
  1883. acceptNextArg = true;
  1884. } else {
  1885. cmsys::RegularExpressionMatch match;
  1886. if (!acceptNextArg) {
  1887. if (common_double_arg.find(arg.c_str(), match)) {
  1888. acceptNextArg = match.match(2).empty();
  1889. } else {
  1890. if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
  1891. if (pArgTgt == &preprocess) {
  1892. continue;
  1893. }
  1894. } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
  1895. if (pArgTgt == &preprocess) {
  1896. skipNextArg = match.match(2).empty();
  1897. continue;
  1898. }
  1899. acceptNextArg = match.match(2).empty();
  1900. } else if (pArgTgt == &resource_compile) {
  1901. continue;
  1902. }
  1903. }
  1904. } else {
  1905. acceptNextArg = false;
  1906. }
  1907. if (arg.find("SOURCE_DIR") != std::string::npos) {
  1908. std::string sourceDirArg = arg;
  1909. cmSystemTools::ReplaceString(
  1910. sourceDirArg, "SOURCE_DIR",
  1911. cmSystemTools::GetFilenamePath(source_file));
  1912. pArgTgt->push_back(sourceDirArg);
  1913. } else {
  1914. pArgTgt->push_back(arg);
  1915. }
  1916. }
  1917. }
  1918. if (preprocess.empty()) {
  1919. std::cerr << "Empty preprocessing command";
  1920. return 1;
  1921. }
  1922. if (resource_compile.empty()) {
  1923. std::cerr << "Empty resource compilation command";
  1924. return 1;
  1925. }
  1926. // Since we might have skipped the last argument to llvm-rc
  1927. // we need to make sure the llvm-rc source file is present in the
  1928. // commandline
  1929. if (resource_compile.back() != intermediate_file) {
  1930. resource_compile.push_back(intermediate_file);
  1931. }
  1932. auto result = RunPreprocessor(preprocess, intermediate_file);
  1933. if (result != 0) {
  1934. cmSystemTools::RemoveFile(intermediate_file);
  1935. return result;
  1936. }
  1937. cmUVProcessChainBuilder builder;
  1938. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  1939. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1940. .AddCommand(resource_compile);
  1941. auto process = builder.Start();
  1942. result = 0;
  1943. if (!process.Valid() || process.GetStatus(0).SpawnResult != 0) {
  1944. std::cerr << "Failed to start resource compiler.";
  1945. result = 1;
  1946. } else {
  1947. if (!process.Wait()) {
  1948. std::cerr << "Failed to wait for resource compiler";
  1949. result = 1;
  1950. }
  1951. }
  1952. cmSystemTools::RemoveFile(intermediate_file);
  1953. if (result != 0) {
  1954. return result;
  1955. }
  1956. if (process.GetStatus(0).ExitStatus != 0) {
  1957. cmUVPipeIStream errorStream(process.GetLoop(), process.ErrorStream());
  1958. std::cerr << errorStream.rdbuf();
  1959. return 1;
  1960. }
  1961. return 0;
  1962. }
  1963. class cmVSLink
  1964. {
  1965. int Type;
  1966. bool Verbose;
  1967. bool Incremental = false;
  1968. bool LinkGeneratesManifest = true;
  1969. std::vector<std::string> LinkCommand;
  1970. std::vector<std::string> UserManifests;
  1971. std::string LinkerManifestFile;
  1972. std::string ManifestFile;
  1973. std::string ManifestFileRC;
  1974. std::string ManifestFileRes;
  1975. std::string TargetFile;
  1976. std::string MtPath;
  1977. std::string RcPath;
  1978. public:
  1979. cmVSLink(int type, bool verbose)
  1980. : Type(type)
  1981. , Verbose(verbose)
  1982. {
  1983. }
  1984. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1985. std::vector<std::string>::const_iterator argEnd);
  1986. int Link();
  1987. private:
  1988. int LinkIncremental();
  1989. int LinkNonIncremental();
  1990. int RunMT(std::string const& out, bool notify);
  1991. };
  1992. // For visual studio 2005 and newer manifest files need to be embedded into
  1993. // exe and dll's. This code does that in such a way that incremental linking
  1994. // still works.
  1995. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1996. {
  1997. // Replace streambuf so we output in the system codepage. CMake is set up
  1998. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1999. // outputs using the system codepage so we need to change behavior when
  2000. // we run the link command.
  2001. cmConsoleBuf consoleBuf;
  2002. if (args.size() < 2) {
  2003. return -1;
  2004. }
  2005. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  2006. std::vector<std::string> expandedArgs;
  2007. for (std::string const& i : args) {
  2008. // check for nmake temporary files
  2009. if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
  2010. cmsys::ifstream fin(i.substr(1).c_str());
  2011. std::string line;
  2012. while (cmSystemTools::GetLineFromStream(fin, line)) {
  2013. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  2014. }
  2015. } else {
  2016. expandedArgs.push_back(i);
  2017. }
  2018. }
  2019. cmVSLink vsLink(type, verbose);
  2020. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  2021. return -1;
  2022. }
  2023. return vsLink.Link();
  2024. }
  2025. enum NumberFormat
  2026. {
  2027. FORMAT_DECIMAL,
  2028. FORMAT_HEX
  2029. };
  2030. struct NumberFormatter
  2031. {
  2032. NumberFormat Format;
  2033. int Value;
  2034. NumberFormatter(NumberFormat format, int value)
  2035. : Format(format)
  2036. , Value(value)
  2037. {
  2038. }
  2039. };
  2040. static std::ostream& operator<<(std::ostream& stream,
  2041. NumberFormatter const& formatter)
  2042. {
  2043. auto const& flags = stream.flags();
  2044. if (formatter.Format == FORMAT_DECIMAL) {
  2045. stream << std::dec << formatter.Value;
  2046. } else {
  2047. stream << "0x" << std::hex << formatter.Value;
  2048. }
  2049. stream.flags(flags);
  2050. return stream;
  2051. }
  2052. static bool RunCommand(const char* comment,
  2053. std::vector<std::string> const& command, bool verbose,
  2054. NumberFormat exitFormat, int* retCodeOut = nullptr,
  2055. bool (*retCodeOkay)(int) = nullptr)
  2056. {
  2057. if (verbose) {
  2058. std::cout << comment << ":\n";
  2059. std::cout << cmJoin(command, " ") << "\n";
  2060. }
  2061. std::string output;
  2062. int retCode = 0;
  2063. bool commandResult = cmSystemTools::RunSingleCommand(
  2064. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  2065. bool const retCodeSuccess =
  2066. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  2067. bool const success = commandResult && retCodeSuccess;
  2068. if (retCodeOut) {
  2069. if (commandResult || !retCodeSuccess) {
  2070. *retCodeOut = retCode;
  2071. } else {
  2072. *retCodeOut = -1;
  2073. }
  2074. }
  2075. if (!success) {
  2076. std::cout << comment << ": command \"" << cmJoin(command, " ")
  2077. << "\" failed (exit code "
  2078. << NumberFormatter(exitFormat, retCode)
  2079. << ") with the following output:\n"
  2080. << output;
  2081. } else if (verbose) {
  2082. // always print the output of the command, unless
  2083. // it is the dumb rc command banner
  2084. if (output.find("Resource Compiler Version") == std::string::npos) {
  2085. std::cout << output;
  2086. }
  2087. }
  2088. return success;
  2089. }
  2090. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  2091. std::vector<std::string>::const_iterator argEnd)
  2092. {
  2093. // Parse our own arguments.
  2094. std::string intDir;
  2095. auto arg = argBeg;
  2096. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  2097. if (*arg == "--") {
  2098. ++arg;
  2099. break;
  2100. }
  2101. if (*arg == "--manifests") {
  2102. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  2103. this->UserManifests.push_back(*arg);
  2104. }
  2105. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  2106. intDir = arg->substr(9);
  2107. ++arg;
  2108. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  2109. this->RcPath = arg->substr(5);
  2110. ++arg;
  2111. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  2112. this->MtPath = arg->substr(5);
  2113. ++arg;
  2114. } else {
  2115. std::cerr << "unknown argument '" << *arg << "'\n";
  2116. return false;
  2117. }
  2118. }
  2119. if (intDir.empty()) {
  2120. return false;
  2121. }
  2122. // The rest of the arguments form the link command.
  2123. if (arg == argEnd) {
  2124. return false;
  2125. }
  2126. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  2127. // Parse the link command to extract information we need.
  2128. for (; arg != argEnd; ++arg) {
  2129. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
  2130. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL:YES") == 0 ||
  2131. cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0 ||
  2132. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL") == 0) {
  2133. this->Incremental = true;
  2134. } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:NO") == 0 ||
  2135. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL:NO") == 0) {
  2136. this->Incremental = false;
  2137. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0 ||
  2138. cmSystemTools::Strucmp(arg->c_str(), "-MANIFEST:NO") == 0) {
  2139. this->LinkGeneratesManifest = false;
  2140. } else if (cmHasLiteralPrefix(*arg, "/Fe") ||
  2141. cmHasLiteralPrefix(*arg, "-Fe")) {
  2142. this->TargetFile = arg->substr(3);
  2143. } else if (cmHasLiteralPrefix(*arg, "/out:") ||
  2144. cmHasLiteralPrefix(*arg, "-out:")) {
  2145. this->TargetFile = arg->substr(5);
  2146. }
  2147. }
  2148. if (this->TargetFile.empty()) {
  2149. return false;
  2150. }
  2151. this->ManifestFile = intDir + "/embed.manifest";
  2152. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  2153. if (this->Incremental) {
  2154. // We will compile a resource containing the manifest and
  2155. // pass it to the link command.
  2156. this->ManifestFileRC = intDir + "/manifest.rc";
  2157. this->ManifestFileRes = intDir + "/manifest.res";
  2158. if (this->LinkGeneratesManifest) {
  2159. this->LinkCommand.emplace_back("/MANIFEST");
  2160. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  2161. }
  2162. }
  2163. return true;
  2164. }
  2165. int cmVSLink::Link()
  2166. {
  2167. if (this->Incremental &&
  2168. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  2169. if (this->Verbose) {
  2170. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  2171. }
  2172. return this->LinkIncremental();
  2173. }
  2174. if (this->Verbose) {
  2175. if (!this->Incremental) {
  2176. std::cout << "Visual Studio Non-Incremental Link\n";
  2177. } else {
  2178. std::cout << "Visual Studio Incremental Link without manifests\n";
  2179. }
  2180. }
  2181. return this->LinkNonIncremental();
  2182. }
  2183. static bool mtRetIsUpdate(int mtRet)
  2184. {
  2185. // 'mt /notify_update' returns a special value (differing between
  2186. // Windows and POSIX hosts) when it updated the manifest file.
  2187. return mtRet == 0x41020001 || mtRet == 0xbb;
  2188. }
  2189. int cmVSLink::LinkIncremental()
  2190. {
  2191. // This follows the steps listed here:
  2192. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  2193. // 1. Compiler compiles the application and generates the *.obj files.
  2194. // 2. An empty manifest file is generated if this is a clean build and
  2195. // if not the previous one is reused.
  2196. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  2197. // *.res file.
  2198. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  2199. // switch and embeds the dummy manifest file. The linker also generates
  2200. // the real manifest file based on the binaries that your binary depends
  2201. // on.
  2202. // 5. The manifest tool (mt.exe) is then used to generate the final
  2203. // manifest.
  2204. // If the final manifest is changed, then 6 and 7 are run, if not
  2205. // they are skipped, and it is done.
  2206. // 6. The resource compiler is invoked one more time.
  2207. // 7. Finally, the Linker does another incremental link, but since the
  2208. // only thing that has changed is the *.res file that contains the
  2209. // manifest it is a short link.
  2210. // Create a resource file referencing the manifest.
  2211. std::string absManifestFile =
  2212. cmSystemTools::CollapseFullPath(this->ManifestFile);
  2213. if (this->Verbose) {
  2214. std::cout << "Create " << this->ManifestFileRC << "\n";
  2215. }
  2216. {
  2217. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  2218. if (!fout) {
  2219. return -1;
  2220. }
  2221. // Insert a pragma statement to specify utf-8 encoding.
  2222. fout << "#pragma code_page(65001)\n";
  2223. fout << this->Type
  2224. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  2225. "24 /* RT_MANIFEST */ \""
  2226. << absManifestFile << "\"";
  2227. }
  2228. // If we have not previously generated a manifest file,
  2229. // generate a manifest file so the resource compiler succeeds.
  2230. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  2231. if (this->Verbose) {
  2232. std::cout << "Create empty: " << this->ManifestFile << "\n";
  2233. }
  2234. if (this->UserManifests.empty()) {
  2235. // generate an empty manifest because there are no user provided
  2236. // manifest files.
  2237. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  2238. } else {
  2239. this->RunMT("/out:" + this->ManifestFile, false);
  2240. }
  2241. }
  2242. // Compile the resource file.
  2243. std::vector<std::string> rcCommand;
  2244. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  2245. rcCommand.emplace_back("/fo");
  2246. rcCommand.push_back(this->ManifestFileRes);
  2247. rcCommand.push_back(this->ManifestFileRC);
  2248. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2249. return -1;
  2250. }
  2251. // Tell the linker to use our manifest compiled into a resource.
  2252. this->LinkCommand.push_back(this->ManifestFileRes);
  2253. // Run the link command (possibly generates intermediate manifest).
  2254. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  2255. FORMAT_DECIMAL)) {
  2256. return -1;
  2257. }
  2258. // Run the manifest tool to create the final manifest.
  2259. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  2260. // If mt returns a special value then it updated the manifest file so
  2261. // we need to embed it again. Otherwise we are done.
  2262. if (!mtRetIsUpdate(mtRet)) {
  2263. return mtRet;
  2264. }
  2265. // Compile the resource file again.
  2266. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2267. return -1;
  2268. }
  2269. // Link incrementally again to use the updated resource.
  2270. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  2271. FORMAT_DECIMAL)) {
  2272. return -1;
  2273. }
  2274. return 0;
  2275. }
  2276. int cmVSLink::LinkNonIncremental()
  2277. {
  2278. // The MSVC link tool expects 'rc' to be in the PATH if it needs to embed
  2279. // manifests, but the user might explicitly set 'CMAKE_RC_COMPILER' instead.
  2280. // Add its location as a fallback at the end of PATH.
  2281. if (cmSystemTools::FileIsFullPath(this->RcPath)) {
  2282. std::string rcDir = cmSystemTools::GetFilenamePath(this->RcPath);
  2283. #ifdef _WIN32
  2284. std::replace(rcDir.begin(), rcDir.end(), '/', '\\');
  2285. char const pathSep = ';';
  2286. #else
  2287. char const pathSep = ':';
  2288. #endif
  2289. cm::optional<std::string> path = cmSystemTools::GetEnvVar("PATH");
  2290. if (path) {
  2291. path = cmStrCat(*path, pathSep, rcDir);
  2292. } else {
  2293. path = rcDir;
  2294. }
  2295. cmSystemTools::PutEnv(cmStrCat("PATH=", *path));
  2296. }
  2297. // Sort out any manifests.
  2298. if (this->LinkGeneratesManifest || !this->UserManifests.empty()) {
  2299. std::string opt =
  2300. std::string("/MANIFEST:EMBED,ID=") + (this->Type == 1 ? '1' : '2');
  2301. this->LinkCommand.emplace_back(opt);
  2302. for (auto const& m : this->UserManifests) {
  2303. opt = "/MANIFESTINPUT:" + m;
  2304. this->LinkCommand.emplace_back(opt);
  2305. }
  2306. }
  2307. // Run the link command.
  2308. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  2309. return -1;
  2310. }
  2311. return 0;
  2312. }
  2313. int cmVSLink::RunMT(std::string const& out, bool notify)
  2314. {
  2315. std::vector<std::string> mtCommand;
  2316. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  2317. mtCommand.emplace_back("/nologo");
  2318. // add the linker generated manifest if the file exists.
  2319. if (this->LinkGeneratesManifest &&
  2320. cmSystemTools::FileExists(this->LinkerManifestFile)) {
  2321. mtCommand.emplace_back("/manifest");
  2322. mtCommand.push_back(this->LinkerManifestFile);
  2323. }
  2324. for (auto const& m : this->UserManifests) {
  2325. mtCommand.emplace_back("/manifest");
  2326. mtCommand.push_back(m);
  2327. }
  2328. mtCommand.push_back(out);
  2329. if (notify) {
  2330. // Add an undocumented option that enables a special return
  2331. // code to notify us when the manifest is modified.
  2332. mtCommand.emplace_back("/notify_update");
  2333. }
  2334. int mtRet = 0;
  2335. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  2336. mtRetIsUpdate)) {
  2337. return -1;
  2338. }
  2339. return mtRet;
  2340. }