cmcmd.cxx 87 KB

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