cmcmd.cxx 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390
  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. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1167. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1168. // Actually scan dependencies.
  1169. return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
  1170. }
  1171. return 1;
  1172. }
  1173. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  1174. // Internal CMake compiler dependencies filtering
  1175. if (args[1] == "cmake_cl_compile_depends") {
  1176. return CLCompileAndDependencies(args);
  1177. }
  1178. #endif
  1179. // Internal CMake link script support.
  1180. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1181. return cmcmd::ExecuteLinkScript(args);
  1182. }
  1183. #if !defined(CMAKE_BOOTSTRAP)
  1184. // Internal CMake ninja dependency scanning support.
  1185. if (args[1] == "cmake_ninja_depends") {
  1186. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1187. }
  1188. // Internal CMake ninja dyndep support.
  1189. if (args[1] == "cmake_ninja_dyndep") {
  1190. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1191. }
  1192. #endif
  1193. // Internal CMake unimplemented feature notification.
  1194. if (args[1] == "cmake_unimplemented_variable") {
  1195. std::cerr << "Feature not implemented for this platform.";
  1196. if (args.size() == 3) {
  1197. std::cerr << " Variable " << args[2] << " is not set.";
  1198. }
  1199. std::cerr << std::endl;
  1200. return 1;
  1201. }
  1202. if (args[1] == "vs_link_exe") {
  1203. return cmcmd::VisualStudioLink(args, 1);
  1204. }
  1205. if (args[1] == "vs_link_dll") {
  1206. return cmcmd::VisualStudioLink(args, 2);
  1207. }
  1208. if (args[1] == "cmake_llvm_rc") {
  1209. return cmcmd::RunLLVMRC(args);
  1210. }
  1211. // Internal CMake color makefile support.
  1212. if (args[1] == "cmake_echo_color") {
  1213. return cmcmd::ExecuteEchoColor(args);
  1214. }
  1215. #ifndef CMAKE_BOOTSTRAP
  1216. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1217. cm::string_view const infoFile = args[2];
  1218. cm::string_view const config = args[3];
  1219. return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
  1220. }
  1221. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1222. cm::string_view const infoFile = args[2];
  1223. cm::string_view const config =
  1224. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1225. return cmQtAutoRcc(infoFile, config) ? 0 : 1;
  1226. }
  1227. #endif
  1228. // Tar files
  1229. if (args[1] == "tar" && args.size() > 3) {
  1230. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1231. std::string const& flags = args[2];
  1232. std::string const& outFile = args[3];
  1233. std::vector<std::string> files;
  1234. std::string mtime;
  1235. std::string format;
  1236. cmSystemTools::cmTarCompression compress =
  1237. cmSystemTools::TarCompressNone;
  1238. int nCompress = 0;
  1239. bool doing_options = true;
  1240. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1241. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1242. if (arg == "--") {
  1243. doing_options = false;
  1244. } else if (arg == "--zstd") {
  1245. compress = cmSystemTools::TarCompressZstd;
  1246. ++nCompress;
  1247. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1248. mtime = arg.substr(8);
  1249. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1250. std::string const& files_from = arg.substr(13);
  1251. if (!cmTarFilesFrom(files_from, files)) {
  1252. return 1;
  1253. }
  1254. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1255. format = arg.substr(9);
  1256. if (!cm::contains(knownFormats, format)) {
  1257. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1258. format);
  1259. return 1;
  1260. }
  1261. } else {
  1262. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1263. return 1;
  1264. }
  1265. } else {
  1266. files.push_back(arg);
  1267. }
  1268. }
  1269. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1270. bool verbose = false;
  1271. for (auto flag : flags) {
  1272. switch (flag) {
  1273. case '-':
  1274. case 'f': {
  1275. // Keep for backward compatibility. Ignored
  1276. } break;
  1277. case 'j': {
  1278. compress = cmSystemTools::TarCompressBZip2;
  1279. ++nCompress;
  1280. } break;
  1281. case 'J': {
  1282. compress = cmSystemTools::TarCompressXZ;
  1283. ++nCompress;
  1284. } break;
  1285. case 'z': {
  1286. compress = cmSystemTools::TarCompressGZip;
  1287. ++nCompress;
  1288. } break;
  1289. case 'v': {
  1290. verbose = true;
  1291. } break;
  1292. case 't': {
  1293. action = cmSystemTools::TarActionList;
  1294. } break;
  1295. case 'c': {
  1296. action = cmSystemTools::TarActionCreate;
  1297. } break;
  1298. case 'x': {
  1299. action = cmSystemTools::TarActionExtract;
  1300. } break;
  1301. default: {
  1302. cmSystemTools::Message(
  1303. std::string("tar: Unknown argument: ") + flag, "Warning");
  1304. }
  1305. }
  1306. }
  1307. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1308. cmSystemTools::Error("Can not use compression flags with format: " +
  1309. format);
  1310. return 1;
  1311. }
  1312. if (nCompress > 1) {
  1313. cmSystemTools::Error("Can only compress a tar file one way; "
  1314. "at most one flag of z, j, or J may be used");
  1315. return 1;
  1316. }
  1317. if (action == cmSystemTools::TarActionList) {
  1318. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1319. cmSystemTools::Error("Problem listing tar: " + outFile);
  1320. return 1;
  1321. }
  1322. } else if (action == cmSystemTools::TarActionCreate) {
  1323. if (files.empty()) {
  1324. cmSystemTools::Message("tar: No files or directories specified",
  1325. "Warning");
  1326. }
  1327. if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
  1328. format)) {
  1329. cmSystemTools::Error("Problem creating tar: " + outFile);
  1330. return 1;
  1331. }
  1332. } else if (action == cmSystemTools::TarActionExtract) {
  1333. if (!cmSystemTools::ExtractTar(outFile, files, verbose)) {
  1334. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1335. return 1;
  1336. }
  1337. #ifdef WIN32
  1338. // OK, on windows 7 after we untar some files,
  1339. // sometimes we can not rename the directory after
  1340. // the untar is done. This breaks the external project
  1341. // untar and rename code. So, by default we will wait
  1342. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1343. // is set in the env, its value will be used instead of 100.
  1344. int delay = 100;
  1345. std::string delayVar;
  1346. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1347. delay = atoi(delayVar.c_str());
  1348. }
  1349. if (delay) {
  1350. cmSystemTools::Delay(delay);
  1351. }
  1352. #endif
  1353. } else {
  1354. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1355. "(list), 'c' (create) or 'x' (extract)");
  1356. return 1;
  1357. }
  1358. return 0;
  1359. }
  1360. if (args[1] == "server") {
  1361. cmSystemTools::Error(
  1362. "CMake server mode has been removed in favor of the file-api.");
  1363. return 1;
  1364. }
  1365. #if !defined(CMAKE_BOOTSTRAP)
  1366. // Internal CMake Fortran module support.
  1367. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1368. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1369. }
  1370. #endif
  1371. #if defined(_WIN32) && !defined(__CYGWIN__)
  1372. // Write registry value
  1373. if (args[1] == "write_regv" && args.size() > 3) {
  1374. return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
  1375. }
  1376. // Delete registry value
  1377. if (args[1] == "delete_regv" && args.size() > 2) {
  1378. return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
  1379. }
  1380. // Remove file
  1381. if (args[1] == "comspec" && args.size() > 2) {
  1382. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1383. return 1;
  1384. }
  1385. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1386. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1387. }
  1388. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1389. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1390. }
  1391. #endif
  1392. // Internal depfile transformation
  1393. if (args[1] == "cmake_transform_depfile" && args.size() == 6) {
  1394. auto format = cmDepfileFormat::GccDepfile;
  1395. if (args[2] == "gccdepfile") {
  1396. format = cmDepfileFormat::GccDepfile;
  1397. } else if (args[2] == "vstlog") {
  1398. format = cmDepfileFormat::VsTlog;
  1399. } else {
  1400. return 1;
  1401. }
  1402. std::string prefix = args[3];
  1403. if (prefix == "./") {
  1404. prefix.clear();
  1405. }
  1406. return cmTransformDepfile(format, prefix, args[4], args[5]) ? 0 : 1;
  1407. }
  1408. }
  1409. CMakeCommandUsage(args[0].c_str());
  1410. return 1;
  1411. }
  1412. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1413. cmCryptoHash::Algo algo)
  1414. {
  1415. if (args.size() < 3) {
  1416. return -1;
  1417. }
  1418. int retval = 0;
  1419. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1420. // Cannot compute sum of a directory
  1421. if (cmSystemTools::FileIsDirectory(filename)) {
  1422. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1423. retval++;
  1424. } else {
  1425. std::string value = cmSystemTools::ComputeFileHash(filename, algo);
  1426. if (value.empty()) {
  1427. // To mimic "md5sum/shasum" behavior in a shell:
  1428. std::cerr << filename << ": No such file or directory" << std::endl;
  1429. retval++;
  1430. } else {
  1431. std::cout << value << " " << filename << std::endl;
  1432. }
  1433. }
  1434. }
  1435. return retval;
  1436. }
  1437. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1438. {
  1439. int result = 0;
  1440. std::string realName = args[2];
  1441. std::string soName = args[3];
  1442. std::string name = args[4];
  1443. cmSystemTools::ConvertToUnixSlashes(realName);
  1444. cmSystemTools::ConvertToUnixSlashes(soName);
  1445. cmSystemTools::ConvertToUnixSlashes(name);
  1446. if (soName != realName) {
  1447. if (!cmcmd::SymlinkInternal(realName, soName)) {
  1448. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1449. result = 1;
  1450. }
  1451. }
  1452. if (name != soName) {
  1453. if (!cmcmd::SymlinkInternal(soName, name)) {
  1454. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1455. result = 1;
  1456. }
  1457. }
  1458. return result;
  1459. }
  1460. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1461. {
  1462. int result = 0;
  1463. std::string const& realName = args[2];
  1464. std::string const& name = args[3];
  1465. if (name != realName) {
  1466. if (!cmcmd::SymlinkInternal(realName, name)) {
  1467. cmSystemTools::ReportLastSystemError("cmake_symlink_executable");
  1468. result = 1;
  1469. }
  1470. }
  1471. return result;
  1472. }
  1473. bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link)
  1474. {
  1475. if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
  1476. cmSystemTools::RemoveFile(link);
  1477. }
  1478. #if defined(_WIN32) && !defined(__CYGWIN__)
  1479. return cmSystemTools::CopyFileAlways(file, link);
  1480. #else
  1481. std::string linktext = cmSystemTools::GetFilenameName(file);
  1482. return cmSystemTools::CreateSymlink(linktext, link);
  1483. #endif
  1484. }
  1485. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1486. {
  1487. std::string dirName = cmStrCat(dir, "/Progress");
  1488. std::string fName;
  1489. FILE* progFile;
  1490. // read the count
  1491. fName = cmStrCat(dirName, "/count.txt");
  1492. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1493. int count = 0;
  1494. if (!progFile) {
  1495. return;
  1496. }
  1497. if (1 != fscanf(progFile, "%i", &count)) {
  1498. cmSystemTools::Message("Could not read from progress file.");
  1499. }
  1500. fclose(progFile);
  1501. const char* last = num.c_str();
  1502. for (const char* c = last;; ++c) {
  1503. if (*c == ',' || *c == '\0') {
  1504. if (c != last) {
  1505. fName = cmStrCat(dirName, '/');
  1506. fName.append(last, c - last);
  1507. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1508. if (progFile) {
  1509. fprintf(progFile, "empty");
  1510. fclose(progFile);
  1511. }
  1512. }
  1513. if (*c == '\0') {
  1514. break;
  1515. }
  1516. last = c + 1;
  1517. }
  1518. }
  1519. int fileNum =
  1520. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1521. if (count > 0) {
  1522. // print the progress
  1523. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1524. }
  1525. }
  1526. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1527. {
  1528. // The arguments are
  1529. // args[0] == <cmake-executable>
  1530. // args[1] == cmake_echo_color
  1531. bool enabled = true;
  1532. int color = cmsysTerminal_Color_Normal;
  1533. bool newline = true;
  1534. std::string progressDir;
  1535. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1536. if (cmHasLiteralPrefix(arg, "--switch=")) {
  1537. // Enable or disable color based on the switch value.
  1538. std::string value = arg.substr(9);
  1539. if (!value.empty()) {
  1540. enabled = cmIsOn(value);
  1541. }
  1542. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1543. progressDir = arg.substr(15);
  1544. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1545. if (!progressDir.empty()) {
  1546. std::string const& progressNum = arg.substr(15);
  1547. cmcmdProgressReport(progressDir, progressNum);
  1548. }
  1549. } else if (arg == "--normal") {
  1550. color = cmsysTerminal_Color_Normal;
  1551. } else if (arg == "--black") {
  1552. color = cmsysTerminal_Color_ForegroundBlack;
  1553. } else if (arg == "--red") {
  1554. color = cmsysTerminal_Color_ForegroundRed;
  1555. } else if (arg == "--green") {
  1556. color = cmsysTerminal_Color_ForegroundGreen;
  1557. } else if (arg == "--yellow") {
  1558. color = cmsysTerminal_Color_ForegroundYellow;
  1559. } else if (arg == "--blue") {
  1560. color = cmsysTerminal_Color_ForegroundBlue;
  1561. } else if (arg == "--magenta") {
  1562. color = cmsysTerminal_Color_ForegroundMagenta;
  1563. } else if (arg == "--cyan") {
  1564. color = cmsysTerminal_Color_ForegroundCyan;
  1565. } else if (arg == "--white") {
  1566. color = cmsysTerminal_Color_ForegroundWhite;
  1567. } else if (arg == "--bold") {
  1568. color |= cmsysTerminal_Color_ForegroundBold;
  1569. } else if (arg == "--no-newline") {
  1570. newline = false;
  1571. } else if (arg == "--newline") {
  1572. newline = true;
  1573. } else {
  1574. // Color is enabled. Print with the current color.
  1575. cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
  1576. }
  1577. }
  1578. return 0;
  1579. }
  1580. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1581. {
  1582. // The arguments are
  1583. // args[0] == <cmake-executable>
  1584. // args[1] == cmake_link_script
  1585. // args[2] == <link-script-name>
  1586. // args[3] == --verbose=?
  1587. bool verbose = false;
  1588. if (args.size() >= 4) {
  1589. if (cmHasLiteralPrefix(args[3], "--verbose=")) {
  1590. if (!cmIsOff(args[3].substr(10))) {
  1591. verbose = true;
  1592. }
  1593. }
  1594. }
  1595. // Allocate a process instance.
  1596. cmsysProcess* cp = cmsysProcess_New();
  1597. if (!cp) {
  1598. std::cerr << "Error allocating process instance in link script."
  1599. << std::endl;
  1600. return 1;
  1601. }
  1602. // Children should share stdout and stderr with this process.
  1603. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  1604. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  1605. // Run the command lines verbatim.
  1606. cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
  1607. // Read command lines from the script.
  1608. cmsys::ifstream fin(args[2].c_str());
  1609. if (!fin) {
  1610. std::cerr << "Error opening link script \"" << args[2] << "\""
  1611. << std::endl;
  1612. return 1;
  1613. }
  1614. // Run one command at a time.
  1615. std::string command;
  1616. int result = 0;
  1617. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1618. // Skip empty command lines.
  1619. if (command.find_first_not_of(" \t") == std::string::npos) {
  1620. continue;
  1621. }
  1622. // Setup this command line.
  1623. const char* cmd[2] = { command.c_str(), nullptr };
  1624. cmsysProcess_SetCommand(cp, cmd);
  1625. // Report the command if verbose output is enabled.
  1626. if (verbose) {
  1627. std::cout << command << std::endl;
  1628. }
  1629. // Run the command and wait for it to exit.
  1630. cmsysProcess_Execute(cp);
  1631. cmsysProcess_WaitForExit(cp, nullptr);
  1632. // Report failure if any.
  1633. switch (cmsysProcess_GetState(cp)) {
  1634. case cmsysProcess_State_Exited: {
  1635. int value = cmsysProcess_GetExitValue(cp);
  1636. if (value != 0) {
  1637. result = value;
  1638. }
  1639. } break;
  1640. case cmsysProcess_State_Exception:
  1641. std::cerr << "Error running link command: "
  1642. << cmsysProcess_GetExceptionString(cp) << std::endl;
  1643. result = 1;
  1644. break;
  1645. case cmsysProcess_State_Error:
  1646. std::cerr << "Error running link command: "
  1647. << cmsysProcess_GetErrorString(cp) << std::endl;
  1648. result = 2;
  1649. break;
  1650. default:
  1651. break;
  1652. }
  1653. }
  1654. // Free the process instance.
  1655. cmsysProcess_Delete(cp);
  1656. // Return the final resulting return value.
  1657. return result;
  1658. }
  1659. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1660. {
  1661. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1662. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1663. parser.ParseVersion(version);
  1664. if (parser.Found()) {
  1665. /* clang-format off */
  1666. std::cout << "@echo off\n"
  1667. "echo Environment Selection: " << name << "\n"
  1668. "set PATH=" << parser.GetPathDirectories() << "\n"
  1669. "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
  1670. "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1671. /* clang-format on */
  1672. return 0;
  1673. }
  1674. #else
  1675. (void)version;
  1676. #endif
  1677. std::cerr << "Could not find " << name;
  1678. return -1;
  1679. }
  1680. int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
  1681. const std::string& intermediate_file)
  1682. {
  1683. cmUVProcessChainBuilder builder;
  1684. uv_fs_t fs_req;
  1685. int preprocessedFile =
  1686. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1687. 0644, nullptr);
  1688. uv_fs_req_cleanup(&fs_req);
  1689. builder
  1690. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1691. preprocessedFile)
  1692. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1693. .AddCommand(command);
  1694. auto process = builder.Start();
  1695. if (!process.Valid()) {
  1696. std::cerr << "Failed to start preprocessor.";
  1697. return 1;
  1698. }
  1699. if (!process.Wait()) {
  1700. std::cerr << "Failed to wait for preprocessor";
  1701. return 1;
  1702. }
  1703. auto status = process.GetStatus();
  1704. if (!status[0] || status[0]->ExitStatus != 0) {
  1705. auto errorStream = process.ErrorStream();
  1706. if (errorStream) {
  1707. std::cerr << errorStream->rdbuf();
  1708. }
  1709. return 1;
  1710. }
  1711. return 0;
  1712. }
  1713. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1714. {
  1715. // The arguments are
  1716. // args[0] == <cmake-executable>
  1717. // args[1] == cmake_llvm_rc
  1718. // args[2] == source_file_path
  1719. // args[3] == intermediate_file
  1720. // args[4..n] == preprocess+args
  1721. // args[n+1] == ++
  1722. // args[n+2...] == llvm-rc+args
  1723. if (args.size() < 3) {
  1724. std::cerr << "Invalid cmake_llvm_rc arguments";
  1725. return 1;
  1726. }
  1727. const std::string& intermediate_file = args[3];
  1728. const std::string& source_file = args[2];
  1729. std::vector<std::string> preprocess;
  1730. std::vector<std::string> resource_compile;
  1731. std::vector<std::string>* pArgTgt = &preprocess;
  1732. static const cmsys::RegularExpression llvm_rc_only_single_arg("^[-/](N|Y)");
  1733. static const cmsys::RegularExpression llvm_rc_only_double_arg(
  1734. "^[-/](C|LN|L)(.)?");
  1735. static const cmsys::RegularExpression common_double_arg(
  1736. "^[-/](D|U|I|FO|fo|Fo)(.)?");
  1737. bool acceptNextArg = false;
  1738. bool skipNextArg = false;
  1739. for (std::string const& arg : cmMakeRange(args).advance(4)) {
  1740. if (skipNextArg) {
  1741. skipNextArg = false;
  1742. continue;
  1743. }
  1744. // We use ++ as seperator between the preprocessing step definition and
  1745. // the rc compilation step becase we need to prepend a -- to seperate the
  1746. // source file properly from other options when using clang-cl for
  1747. // preprocessing.
  1748. if (arg == "++") {
  1749. pArgTgt = &resource_compile;
  1750. skipNextArg = false;
  1751. acceptNextArg = true;
  1752. } else {
  1753. cmsys::RegularExpressionMatch match;
  1754. if (!acceptNextArg) {
  1755. if (common_double_arg.find(arg.c_str(), match)) {
  1756. acceptNextArg = match.match(2).empty();
  1757. } else {
  1758. if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
  1759. if (pArgTgt == &preprocess) {
  1760. continue;
  1761. }
  1762. } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
  1763. if (pArgTgt == &preprocess) {
  1764. skipNextArg = match.match(2).empty();
  1765. continue;
  1766. }
  1767. acceptNextArg = match.match(2).empty();
  1768. } else if (pArgTgt == &resource_compile) {
  1769. continue;
  1770. }
  1771. }
  1772. } else {
  1773. acceptNextArg = false;
  1774. }
  1775. if (arg.find("SOURCE_DIR") != std::string::npos) {
  1776. std::string sourceDirArg = arg;
  1777. cmSystemTools::ReplaceString(
  1778. sourceDirArg, "SOURCE_DIR",
  1779. cmSystemTools::GetFilenamePath(source_file));
  1780. pArgTgt->push_back(sourceDirArg);
  1781. } else {
  1782. pArgTgt->push_back(arg);
  1783. }
  1784. }
  1785. }
  1786. if (preprocess.empty()) {
  1787. std::cerr << "Empty preprocessing command";
  1788. return 1;
  1789. }
  1790. if (resource_compile.empty()) {
  1791. std::cerr << "Empty resource compilation command";
  1792. return 1;
  1793. }
  1794. // Since we might have skipped the last argument to llvm-rc
  1795. // we need to make sure the llvm-rc source file is present in the
  1796. // commandline
  1797. if (resource_compile.back() != intermediate_file) {
  1798. resource_compile.push_back(intermediate_file);
  1799. }
  1800. auto result = RunPreprocessor(preprocess, intermediate_file);
  1801. if (result != 0) {
  1802. cmSystemTools::RemoveFile(intermediate_file);
  1803. return result;
  1804. }
  1805. cmUVProcessChainBuilder builder;
  1806. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  1807. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1808. .AddCommand(resource_compile);
  1809. auto process = builder.Start();
  1810. result = 0;
  1811. if (!process.Valid()) {
  1812. std::cerr << "Failed to start resource compiler.";
  1813. result = 1;
  1814. } else {
  1815. if (!process.Wait()) {
  1816. std::cerr << "Failed to wait for resource compiler";
  1817. result = 1;
  1818. }
  1819. }
  1820. cmSystemTools::RemoveFile(intermediate_file);
  1821. if (result != 0) {
  1822. return result;
  1823. }
  1824. auto status = process.GetStatus();
  1825. if (!status[0] || status[0]->ExitStatus != 0) {
  1826. auto errorStream = process.ErrorStream();
  1827. if (errorStream) {
  1828. std::cerr << errorStream->rdbuf();
  1829. }
  1830. return 1;
  1831. }
  1832. return 0;
  1833. }
  1834. class cmVSLink
  1835. {
  1836. int Type;
  1837. bool Verbose;
  1838. bool Incremental;
  1839. bool LinkGeneratesManifest;
  1840. std::vector<std::string> LinkCommand;
  1841. std::vector<std::string> UserManifests;
  1842. std::string LinkerManifestFile;
  1843. std::string ManifestFile;
  1844. std::string ManifestFileRC;
  1845. std::string ManifestFileRes;
  1846. std::string TargetFile;
  1847. std::string MtPath;
  1848. std::string RcPath;
  1849. public:
  1850. cmVSLink(int type, bool verbose)
  1851. : Type(type)
  1852. , Verbose(verbose)
  1853. , Incremental(false)
  1854. , LinkGeneratesManifest(true)
  1855. {
  1856. }
  1857. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1858. std::vector<std::string>::const_iterator argEnd);
  1859. int Link();
  1860. private:
  1861. int LinkIncremental();
  1862. int LinkNonIncremental();
  1863. int RunMT(std::string const& out, bool notify);
  1864. };
  1865. // For visual studio 2005 and newer manifest files need to be embedded into
  1866. // exe and dll's. This code does that in such a way that incremental linking
  1867. // still works.
  1868. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1869. {
  1870. // Replace streambuf so we output in the system codepage. CMake is set up
  1871. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1872. // outputs using the system codepage so we need to change behavior when
  1873. // we run the link command.
  1874. cmConsoleBuf consoleBuf;
  1875. if (args.size() < 2) {
  1876. return -1;
  1877. }
  1878. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  1879. std::vector<std::string> expandedArgs;
  1880. for (std::string const& i : args) {
  1881. // check for nmake temporary files
  1882. if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
  1883. cmsys::ifstream fin(i.substr(1).c_str());
  1884. std::string line;
  1885. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1886. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  1887. }
  1888. } else {
  1889. expandedArgs.push_back(i);
  1890. }
  1891. }
  1892. cmVSLink vsLink(type, verbose);
  1893. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  1894. return -1;
  1895. }
  1896. return vsLink.Link();
  1897. }
  1898. enum NumberFormat
  1899. {
  1900. FORMAT_DECIMAL,
  1901. FORMAT_HEX
  1902. };
  1903. struct NumberFormatter
  1904. {
  1905. NumberFormat Format;
  1906. int Value;
  1907. NumberFormatter(NumberFormat format, int value)
  1908. : Format(format)
  1909. , Value(value)
  1910. {
  1911. }
  1912. };
  1913. std::ostream& operator<<(std::ostream& stream,
  1914. NumberFormatter const& formatter)
  1915. {
  1916. auto const& flags = stream.flags();
  1917. if (formatter.Format == FORMAT_DECIMAL) {
  1918. stream << std::dec << formatter.Value;
  1919. } else {
  1920. stream << "0x" << std::hex << formatter.Value;
  1921. }
  1922. stream.flags(flags);
  1923. return stream;
  1924. }
  1925. static bool RunCommand(const char* comment,
  1926. std::vector<std::string> const& command, bool verbose,
  1927. NumberFormat exitFormat, int* retCodeOut = nullptr,
  1928. bool (*retCodeOkay)(int) = nullptr)
  1929. {
  1930. if (verbose) {
  1931. std::cout << comment << ":\n";
  1932. std::cout << cmJoin(command, " ") << "\n";
  1933. }
  1934. std::string output;
  1935. int retCode = 0;
  1936. bool commandResult = cmSystemTools::RunSingleCommand(
  1937. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  1938. bool const retCodeSuccess =
  1939. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  1940. bool const success = commandResult && retCodeSuccess;
  1941. if (retCodeOut) {
  1942. if (commandResult || !retCodeSuccess) {
  1943. *retCodeOut = retCode;
  1944. } else {
  1945. *retCodeOut = -1;
  1946. }
  1947. }
  1948. if (!success) {
  1949. std::cout << comment << ": command \"" << cmJoin(command, " ")
  1950. << "\" failed (exit code "
  1951. << NumberFormatter(exitFormat, retCode)
  1952. << ") with the following output:\n"
  1953. << output;
  1954. } else if (verbose) {
  1955. // always print the output of the command, unless
  1956. // it is the dumb rc command banner
  1957. if (output.find("Resource Compiler Version") == std::string::npos) {
  1958. std::cout << output;
  1959. }
  1960. }
  1961. return success;
  1962. }
  1963. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  1964. std::vector<std::string>::const_iterator argEnd)
  1965. {
  1966. // Parse our own arguments.
  1967. std::string intDir;
  1968. auto arg = argBeg;
  1969. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  1970. if (*arg == "--") {
  1971. ++arg;
  1972. break;
  1973. }
  1974. if (*arg == "--manifests") {
  1975. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  1976. this->UserManifests.push_back(*arg);
  1977. }
  1978. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  1979. intDir = arg->substr(9);
  1980. ++arg;
  1981. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  1982. this->RcPath = arg->substr(5);
  1983. ++arg;
  1984. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  1985. this->MtPath = arg->substr(5);
  1986. ++arg;
  1987. } else {
  1988. std::cerr << "unknown argument '" << *arg << "'\n";
  1989. return false;
  1990. }
  1991. }
  1992. if (intDir.empty()) {
  1993. return false;
  1994. }
  1995. // The rest of the arguments form the link command.
  1996. if (arg == argEnd) {
  1997. return false;
  1998. }
  1999. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  2000. // Parse the link command to extract information we need.
  2001. for (; arg != argEnd; ++arg) {
  2002. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
  2003. cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
  2004. this->Incremental = true;
  2005. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
  2006. this->LinkGeneratesManifest = false;
  2007. } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
  2008. this->TargetFile = arg->substr(3);
  2009. } else if (cmHasLiteralPrefix(*arg, "/out:")) {
  2010. this->TargetFile = arg->substr(5);
  2011. }
  2012. }
  2013. if (this->TargetFile.empty()) {
  2014. return false;
  2015. }
  2016. this->ManifestFile = intDir + "/embed.manifest";
  2017. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  2018. if (this->Incremental) {
  2019. // We will compile a resource containing the manifest and
  2020. // pass it to the link command.
  2021. this->ManifestFileRC = intDir + "/manifest.rc";
  2022. this->ManifestFileRes = intDir + "/manifest.res";
  2023. } else if (this->UserManifests.empty()) {
  2024. // Prior to support for user-specified manifests CMake placed the
  2025. // linker-generated manifest next to the binary (as if it were not to be
  2026. // embedded) when not linking incrementally. Preserve this behavior.
  2027. this->ManifestFile = this->TargetFile + ".manifest";
  2028. this->LinkerManifestFile = this->ManifestFile;
  2029. }
  2030. if (this->LinkGeneratesManifest) {
  2031. this->LinkCommand.emplace_back("/MANIFEST");
  2032. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  2033. }
  2034. return true;
  2035. }
  2036. int cmVSLink::Link()
  2037. {
  2038. if (this->Incremental &&
  2039. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  2040. if (this->Verbose) {
  2041. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  2042. }
  2043. return LinkIncremental();
  2044. }
  2045. if (this->Verbose) {
  2046. if (!this->Incremental) {
  2047. std::cout << "Visual Studio Non-Incremental Link\n";
  2048. } else {
  2049. std::cout << "Visual Studio Incremental Link without manifests\n";
  2050. }
  2051. }
  2052. return LinkNonIncremental();
  2053. }
  2054. static bool mtRetIsUpdate(int mtRet)
  2055. {
  2056. // 'mt /notify_update' returns a special value (differing between
  2057. // Windows and POSIX hosts) when it updated the manifest file.
  2058. return mtRet == 0x41020001 || mtRet == 0xbb;
  2059. }
  2060. int cmVSLink::LinkIncremental()
  2061. {
  2062. // This follows the steps listed here:
  2063. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  2064. // 1. Compiler compiles the application and generates the *.obj files.
  2065. // 2. An empty manifest file is generated if this is a clean build and
  2066. // if not the previous one is reused.
  2067. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  2068. // *.res file.
  2069. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  2070. // switch and embeds the dummy manifest file. The linker also generates
  2071. // the real manifest file based on the binaries that your binary depends
  2072. // on.
  2073. // 5. The manifest tool (mt.exe) is then used to generate the final
  2074. // manifest.
  2075. // If the final manifest is changed, then 6 and 7 are run, if not
  2076. // they are skipped, and it is done.
  2077. // 6. The resource compiler is invoked one more time.
  2078. // 7. Finally, the Linker does another incremental link, but since the
  2079. // only thing that has changed is the *.res file that contains the
  2080. // manifest it is a short link.
  2081. // Create a resource file referencing the manifest.
  2082. std::string absManifestFile =
  2083. cmSystemTools::CollapseFullPath(this->ManifestFile);
  2084. if (this->Verbose) {
  2085. std::cout << "Create " << this->ManifestFileRC << "\n";
  2086. }
  2087. {
  2088. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  2089. if (!fout) {
  2090. return -1;
  2091. }
  2092. // Insert a pragma statement to specify utf-8 encoding.
  2093. fout << "#pragma code_page(65001)\n";
  2094. fout << this->Type
  2095. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  2096. "24 /* RT_MANIFEST */ \""
  2097. << absManifestFile << "\"";
  2098. }
  2099. // If we have not previously generated a manifest file,
  2100. // generate a manifest file so the resource compiler succeeds.
  2101. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  2102. if (this->Verbose) {
  2103. std::cout << "Create empty: " << this->ManifestFile << "\n";
  2104. }
  2105. if (this->UserManifests.empty()) {
  2106. // generate an empty manifest because there are no user provided
  2107. // manifest files.
  2108. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  2109. } else {
  2110. this->RunMT("/out:" + this->ManifestFile, false);
  2111. }
  2112. }
  2113. // Compile the resource file.
  2114. std::vector<std::string> rcCommand;
  2115. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  2116. rcCommand.emplace_back("/fo");
  2117. rcCommand.push_back(this->ManifestFileRes);
  2118. rcCommand.push_back(this->ManifestFileRC);
  2119. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2120. return -1;
  2121. }
  2122. // Tell the linker to use our manifest compiled into a resource.
  2123. this->LinkCommand.push_back(this->ManifestFileRes);
  2124. // Run the link command (possibly generates intermediate manifest).
  2125. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  2126. FORMAT_DECIMAL)) {
  2127. return -1;
  2128. }
  2129. // Run the manifest tool to create the final manifest.
  2130. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  2131. // If mt returns a special value then it updated the manifest file so
  2132. // we need to embed it again. Otherwise we are done.
  2133. if (!mtRetIsUpdate(mtRet)) {
  2134. return mtRet;
  2135. }
  2136. // Compile the resource file again.
  2137. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2138. return -1;
  2139. }
  2140. // Link incrementally again to use the updated resource.
  2141. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  2142. FORMAT_DECIMAL)) {
  2143. return -1;
  2144. }
  2145. return 0;
  2146. }
  2147. int cmVSLink::LinkNonIncremental()
  2148. {
  2149. // Run the link command (possibly generates intermediate manifest).
  2150. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  2151. return -1;
  2152. }
  2153. // If we have no manifest files we are done.
  2154. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  2155. return 0;
  2156. }
  2157. // Run the manifest tool to embed the final manifest in the binary.
  2158. std::string mtOut =
  2159. "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
  2160. return this->RunMT(mtOut, false);
  2161. }
  2162. int cmVSLink::RunMT(std::string const& out, bool notify)
  2163. {
  2164. std::vector<std::string> mtCommand;
  2165. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  2166. mtCommand.emplace_back("/nologo");
  2167. mtCommand.emplace_back("/manifest");
  2168. // add the linker generated manifest if the file exists.
  2169. if (this->LinkGeneratesManifest &&
  2170. cmSystemTools::FileExists(this->LinkerManifestFile)) {
  2171. mtCommand.push_back(this->LinkerManifestFile);
  2172. }
  2173. cm::append(mtCommand, this->UserManifests);
  2174. mtCommand.push_back(out);
  2175. if (notify) {
  2176. // Add an undocumented option that enables a special return
  2177. // code to notify us when the manifest is modified.
  2178. mtCommand.emplace_back("/notify_update");
  2179. }
  2180. int mtRet = 0;
  2181. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  2182. mtRetIsUpdate)) {
  2183. return -1;
  2184. }
  2185. return mtRet;
  2186. }