cmcmd.cxx 86 KB

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