cmcmd.cxx 83 KB

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