cmcmd.cxx 83 KB

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