cmcmd.cxx 82 KB

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