cmcmd.cxx 86 KB

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