cmcmd.cxx 79 KB

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