cmcmd.cxx 79 KB

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