cmcmd.cxx 78 KB

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