cmcmd.cxx 89 KB

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