cmcmd.cxx 82 KB

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