cmcmd.cxx 84 KB

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