cmcmd.cxx 79 KB

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