cmcmd.cxx 76 KB

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