cmcmd.cxx 79 KB

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