cmcmd.cxx 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705
  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 (cmHasLiteralPrefix(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. if (!cmsys::SystemTools::CopyFileAlways(file, *targetArg)) {
  683. std::cerr << "Error copying file \"" << file << "\" to \""
  684. << *targetArg << "\".\n";
  685. return_value = true;
  686. }
  687. }
  688. return return_value;
  689. }
  690. // Copy file if different.
  691. if (args[1] == "copy_if_different" && args.size() > 3) {
  692. // If multiple source files specified,
  693. // then destination must be directory
  694. if ((args.size() > 4) &&
  695. (!cmSystemTools::FileIsDirectory(args.back()))) {
  696. std::cerr << "Error: Target (for copy_if_different command) \""
  697. << args.back() << "\" is not a directory.\n";
  698. return 1;
  699. }
  700. // If error occurs we want to continue copying next files.
  701. bool return_value = false;
  702. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  703. if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
  704. std::cerr << "Error copying file (if different) from \"" << arg
  705. << "\" to \"" << args.back() << "\".\n";
  706. return_value = true;
  707. }
  708. }
  709. return return_value;
  710. }
  711. // Copy file if newer.
  712. if (args[1] == "copy_if_newer" && args.size() > 3) {
  713. // If multiple source files specified,
  714. // then destination must be directory
  715. if ((args.size() > 4) &&
  716. (!cmSystemTools::FileIsDirectory(args.back()))) {
  717. std::cerr << "Error: Target (for copy_if_newer command) \""
  718. << args.back() << "\" is not a directory.\n";
  719. return 1;
  720. }
  721. // If error occurs we want to continue copying next files.
  722. bool return_value = false;
  723. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  724. if (!cmSystemTools::CopyFileIfNewer(arg, args.back())) {
  725. std::cerr << "Error copying file (if newer) from \"" << arg
  726. << "\" to \"" << args.back() << "\".\n";
  727. return_value = true;
  728. }
  729. }
  730. return return_value;
  731. }
  732. // Copy directory contents
  733. if ((args[1] == "copy_directory" ||
  734. args[1] == "copy_directory_if_different" ||
  735. args[1] == "copy_directory_if_newer") &&
  736. args.size() > 3) {
  737. // If error occurs we want to continue copying next files.
  738. bool return_value = false;
  739. cmsys::SystemTools::CopyWhen when = cmsys::SystemTools::CopyWhen::Always;
  740. if (args[1] == "copy_directory_if_different") {
  741. when = cmsys::SystemTools::CopyWhen::OnlyIfDifferent;
  742. } else if (args[1] == "copy_directory_if_newer") {
  743. when = cmsys::SystemTools::CopyWhen::OnlyIfNewer;
  744. }
  745. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  746. if (!cmSystemTools::CopyADirectory(arg, args.back(), when)) {
  747. std::cerr << "Error copying directory from \"" << arg << "\" to \""
  748. << args.back() << "\".\n";
  749. return_value = true;
  750. }
  751. }
  752. return return_value;
  753. }
  754. // Rename a file or directory
  755. if (args[1] == "rename" && args.size() == 4) {
  756. if (!cmSystemTools::RenameFile(args[2], args[3])) {
  757. std::string e = cmSystemTools::GetLastSystemError();
  758. std::cerr << "Error renaming from \"" << args[2] << "\" to \""
  759. << args[3] << "\": " << e << "\n";
  760. return 1;
  761. }
  762. return 0;
  763. }
  764. // Compare files
  765. if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
  766. bool filesDiffer;
  767. if (args.size() == 4) {
  768. filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
  769. } else if (args[2] == "--ignore-eol") {
  770. filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
  771. } else {
  772. CMakeCommandUsage(args[0]);
  773. return 2;
  774. }
  775. if (filesDiffer) {
  776. return 1;
  777. }
  778. return 0;
  779. }
  780. #if !defined(CMAKE_BOOTSTRAP)
  781. if (args[1] == "__create_def") {
  782. if (args.size() < 4) {
  783. std::cerr << "__create_def Usage: -E __create_def outfile.def "
  784. "objlistfile [--nm=nm-path]\n";
  785. return 1;
  786. }
  787. cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
  788. if (!fin) {
  789. std::cerr << "could not open object list file: " << args[3] << '\n';
  790. return 1;
  791. }
  792. std::vector<std::string> files;
  793. {
  794. std::string file;
  795. cmFileTime outTime;
  796. bool outValid = outTime.Load(args[2]);
  797. while (cmSystemTools::GetLineFromStream(fin, file)) {
  798. files.push_back(file);
  799. if (outValid) {
  800. cmFileTime inTime;
  801. outValid = inTime.Load(file) && inTime.Older(outTime);
  802. }
  803. }
  804. if (outValid) {
  805. // The def file already exists and all input files are older than
  806. // the existing def file.
  807. return 0;
  808. }
  809. }
  810. FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
  811. if (!fout) {
  812. std::cerr << "could not open output .def file: " << args[2] << '\n';
  813. return 1;
  814. }
  815. bindexplib deffile;
  816. if (args.size() >= 5) {
  817. std::string const& a = args[4];
  818. if (cmHasLiteralPrefix(a, "--nm=")) {
  819. deffile.SetNmPath(a.substr(5));
  820. } else {
  821. std::cerr << "unknown argument: " << a << '\n';
  822. }
  823. }
  824. for (std::string const& file : files) {
  825. std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
  826. if (cmSystemTools::LowerCase(ext) == ".def") {
  827. if (!deffile.AddDefinitionFile(file.c_str())) {
  828. return 1;
  829. }
  830. } else {
  831. if (!deffile.AddObjectFile(file.c_str())) {
  832. return 1;
  833. }
  834. }
  835. }
  836. deffile.WriteFile(fout);
  837. fclose(fout);
  838. return 0;
  839. }
  840. #endif
  841. if (args[1] == "__run_co_compile") {
  842. return cmcmd::HandleCoCompileCommands(args);
  843. }
  844. // Echo string
  845. if (args[1] == "echo") {
  846. std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
  847. return 0;
  848. }
  849. // Echo string no new line
  850. if (args[1] == "echo_append") {
  851. std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
  852. return 0;
  853. }
  854. if (args[1] == "env") {
  855. #ifndef CMAKE_BOOTSTRAP
  856. cmSystemTools::EnvDiff env;
  857. #endif
  858. auto ai = args.cbegin() + 2;
  859. auto ae = args.cend();
  860. for (; ai != ae; ++ai) {
  861. std::string const& a = *ai;
  862. if (a == "--") {
  863. // Stop parsing options/environment variables; the next argument
  864. // should be the command.
  865. ++ai;
  866. break;
  867. }
  868. if (cmHasLiteralPrefix(a, "--unset=")) {
  869. // Unset environment variable.
  870. #ifdef CMAKE_BOOTSTRAP
  871. cmSystemTools::UnPutEnv(a.substr(8));
  872. #else
  873. env.UnPutEnv(a.substr(8));
  874. #endif
  875. } else if (a == "--modify") {
  876. #ifdef CMAKE_BOOTSTRAP
  877. std::cerr
  878. << "cmake -E env: --modify not available during bootstrapping\n";
  879. return 1;
  880. #else
  881. if (++ai == ae) {
  882. std::cerr << "cmake -E env: --modify missing a parameter\n";
  883. return 1;
  884. }
  885. std::string const& op = *ai;
  886. if (!env.ParseOperation(op)) {
  887. std::cerr << "cmake -E env: invalid parameter to --modify: " << op
  888. << '\n';
  889. return 1;
  890. }
  891. #endif
  892. } else if (!a.empty() && a[0] == '-') {
  893. // Environment variable and command names cannot start in '-',
  894. // so this must be an unknown option.
  895. std::cerr << "cmake -E env: unknown option '" << a << "'\n";
  896. return 1;
  897. } else if (a.find('=') != std::string::npos) {
  898. // Set environment variable.
  899. #ifdef CMAKE_BOOTSTRAP
  900. cmSystemTools::PutEnv(a);
  901. #else
  902. env.PutEnv(a);
  903. #endif
  904. } else {
  905. // This is the beginning of the command.
  906. break;
  907. }
  908. }
  909. if (ai == ae) {
  910. std::cerr << "cmake -E env: no command given\n";
  911. return 1;
  912. }
  913. #ifndef CMAKE_BOOTSTRAP
  914. env.ApplyToCurrentEnv();
  915. #endif
  916. // Execute command from remaining arguments.
  917. std::vector<std::string> cmd(ai, ae);
  918. int retval;
  919. if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
  920. nullptr,
  921. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  922. return retval;
  923. }
  924. return 1;
  925. }
  926. #if !defined(CMAKE_BOOTSTRAP)
  927. if (args[1] == "environment") {
  928. for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
  929. std::cout << env << std::endl;
  930. }
  931. return 0;
  932. }
  933. #endif
  934. if (args[1] == "make_directory" && args.size() > 2) {
  935. // If an error occurs, we want to continue making directories.
  936. bool return_value = false;
  937. for (auto const& arg : cmMakeRange(args).advance(2)) {
  938. if (!cmSystemTools::MakeDirectory(arg)) {
  939. std::cerr << "Error creating directory \"" << arg << "\".\n";
  940. return_value = true;
  941. }
  942. }
  943. return return_value;
  944. }
  945. if (args[1] == "remove_directory" && args.size() > 2) {
  946. // If an error occurs, we want to continue removing directories.
  947. bool return_value = false;
  948. for (auto const& arg : cmMakeRange(args).advance(2)) {
  949. if (cmSystemTools::FileIsDirectory(arg)) {
  950. if (!cmRemoveDirectory(arg)) {
  951. return_value = true;
  952. }
  953. }
  954. }
  955. return return_value;
  956. }
  957. // Remove file
  958. if (args[1] == "remove" && args.size() > 2) {
  959. bool force = false;
  960. for (auto const& arg : cmMakeRange(args).advance(2)) {
  961. if (arg == "\\-f" || arg == "-f") {
  962. force = true;
  963. } else {
  964. // Complain if the file could not be removed, still exists,
  965. // and the -f option was not given.
  966. if (!cmSystemTools::RemoveFile(arg) && !force &&
  967. cmSystemTools::FileExists(arg)) {
  968. return 1;
  969. }
  970. }
  971. }
  972. return 0;
  973. }
  974. // Remove directories or files with rm
  975. if (args[1] == "rm" && args.size() > 2) {
  976. // If an error occurs, we want to continue removing the remaining
  977. // files/directories.
  978. int return_value = 0;
  979. bool force = false;
  980. bool recursive = false;
  981. bool doing_options = true;
  982. bool at_least_one_file = false;
  983. for (auto const& arg : cmMakeRange(args).advance(2)) {
  984. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  985. if (arg == "--") {
  986. doing_options = false;
  987. }
  988. if (arg.find('f') != std::string::npos) {
  989. force = true;
  990. }
  991. if (arg.find_first_of("rR") != std::string::npos) {
  992. recursive = true;
  993. }
  994. if (arg.find_first_not_of("-frR") != std::string::npos) {
  995. cmSystemTools::Error("Unknown -E rm argument: " + arg);
  996. return 1;
  997. }
  998. } else {
  999. if (arg.empty()) {
  1000. continue;
  1001. }
  1002. at_least_one_file = true;
  1003. // Complain if the -f option was not given and
  1004. // either file does not exist or
  1005. // file could not be removed and still exists
  1006. bool file_exists_or_forced_remove =
  1007. cmSystemTools::PathExists(arg) || force;
  1008. if (cmSystemTools::FileIsDirectory(arg)) {
  1009. if (!cmRemoveDirectory(arg, recursive)) {
  1010. return_value = 1;
  1011. }
  1012. } else if ((!file_exists_or_forced_remove) ||
  1013. (!cmSystemTools::RemoveFile(arg) &&
  1014. cmSystemTools::FileExists(arg))) {
  1015. if (!file_exists_or_forced_remove) {
  1016. cmSystemTools::Error(
  1017. "File to remove does not exist and force is not set: " + arg);
  1018. } else {
  1019. cmSystemTools::Error("File can't be removed and still exist: " +
  1020. arg);
  1021. }
  1022. return_value = 1;
  1023. }
  1024. }
  1025. }
  1026. if (!at_least_one_file) {
  1027. cmSystemTools::Error("Missing file/directory to remove");
  1028. return 1;
  1029. }
  1030. return return_value;
  1031. }
  1032. // Touch file
  1033. if (args[1] == "touch" && args.size() > 2) {
  1034. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1035. if (!cmSystemTools::Touch(arg, true)) {
  1036. std::cerr << "cmake -E touch: failed to update \"" << arg << "\".\n";
  1037. return 1;
  1038. }
  1039. }
  1040. return 0;
  1041. }
  1042. // Touch file
  1043. if (args[1] == "touch_nocreate" && args.size() > 2) {
  1044. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1045. if (!cmSystemTools::Touch(arg, false)) {
  1046. std::cerr << "cmake -E touch_nocreate: failed to update \"" << arg
  1047. << "\".\n";
  1048. return 1;
  1049. }
  1050. }
  1051. return 0;
  1052. }
  1053. // capabilities
  1054. if (args[1] == "capabilities") {
  1055. if (args.size() > 2) {
  1056. std::cerr << "-E capabilities accepts no additional arguments\n";
  1057. return 1;
  1058. }
  1059. cmake cm(cmake::RoleInternal, cmState::Unknown);
  1060. std::cout << cm.ReportCapabilities();
  1061. return 0;
  1062. }
  1063. // Sleep command
  1064. if (args[1] == "sleep" && args.size() > 2) {
  1065. double total = 0;
  1066. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1067. double num = 0.0;
  1068. char unit;
  1069. char extra;
  1070. int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
  1071. if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
  1072. total += num;
  1073. } else {
  1074. std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
  1075. return 1;
  1076. }
  1077. }
  1078. if (total > 0) {
  1079. cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
  1080. }
  1081. return 0;
  1082. }
  1083. // Clock command
  1084. if (args[1] == "time" && args.size() > 2) {
  1085. std::vector<std::string> command(args.begin() + 2, args.end());
  1086. int ret = 0;
  1087. auto time_start = std::chrono::steady_clock::now();
  1088. cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret, nullptr,
  1089. cmSystemTools::OUTPUT_PASSTHROUGH);
  1090. auto time_finish = std::chrono::steady_clock::now();
  1091. std::chrono::duration<double> time_elapsed = time_finish - time_start;
  1092. std::cout << "Elapsed time (seconds): " << time_elapsed.count() << '\n';
  1093. return ret;
  1094. }
  1095. // Command to calculate the md5sum of a file
  1096. if (args[1] == "md5sum" && args.size() >= 3) {
  1097. return HashSumFile(args, cmCryptoHash::AlgoMD5);
  1098. }
  1099. // Command to calculate the sha1sum of a file
  1100. if (args[1] == "sha1sum" && args.size() >= 3) {
  1101. return HashSumFile(args, cmCryptoHash::AlgoSHA1);
  1102. }
  1103. if (args[1] == "sha224sum" && args.size() >= 3) {
  1104. return HashSumFile(args, cmCryptoHash::AlgoSHA224);
  1105. }
  1106. if (args[1] == "sha256sum" && args.size() >= 3) {
  1107. return HashSumFile(args, cmCryptoHash::AlgoSHA256);
  1108. }
  1109. if (args[1] == "sha384sum" && args.size() >= 3) {
  1110. return HashSumFile(args, cmCryptoHash::AlgoSHA384);
  1111. }
  1112. if (args[1] == "sha512sum" && args.size() >= 3) {
  1113. return HashSumFile(args, cmCryptoHash::AlgoSHA512);
  1114. }
  1115. // Command to concat files into one
  1116. if (args[1] == "cat" && args.size() >= 3) {
  1117. int return_value = 0;
  1118. bool doing_options = true;
  1119. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1120. if (arg == "-") {
  1121. doing_options = false;
  1122. // Destroy console buffers to drop cout/cerr encoding transform.
  1123. console.reset();
  1124. cmCatFile(arg);
  1125. } else if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  1126. if (arg == "--") {
  1127. doing_options = false;
  1128. } else {
  1129. cmSystemTools::Error(arg + ": option not handled");
  1130. return_value = 1;
  1131. }
  1132. } else if (!cmSystemTools::TestFileAccess(arg,
  1133. cmsys::TEST_FILE_READ) &&
  1134. cmSystemTools::TestFileAccess(arg, cmsys::TEST_FILE_OK)) {
  1135. cmSystemTools::Error(arg + ": permission denied (ignoring)");
  1136. return_value = 1;
  1137. } else if (cmSystemTools::FileIsDirectory(arg)) {
  1138. cmSystemTools::Error(arg + ": is a directory (ignoring)");
  1139. return_value = 1;
  1140. } else if (!cmSystemTools::FileExists(arg)) {
  1141. cmSystemTools::Error(arg + ": no such file or directory (ignoring)");
  1142. return_value = 1;
  1143. } else if (cmSystemTools::FileLength(arg) == 0) {
  1144. // Ignore empty files, this is not an error
  1145. } else {
  1146. // Destroy console buffers to drop cout/cerr encoding transform.
  1147. console.reset();
  1148. cmCatFile(arg);
  1149. }
  1150. }
  1151. return return_value;
  1152. }
  1153. // Command to change directory and run a program.
  1154. if (args[1] == "chdir" && args.size() >= 4) {
  1155. std::string const& directory = args[2];
  1156. if (!cmSystemTools::FileExists(directory)) {
  1157. cmSystemTools::Error("Directory does not exist for chdir command: " +
  1158. directory);
  1159. return 1;
  1160. }
  1161. std::string command =
  1162. cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
  1163. int retval = 0;
  1164. if (cmSystemTools::RunSingleCommand(
  1165. command, nullptr, nullptr, &retval, directory.c_str(),
  1166. cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
  1167. return retval;
  1168. }
  1169. return 1;
  1170. }
  1171. // Command to start progress for a build
  1172. if (args[1] == "cmake_progress_start" && args.size() == 4) {
  1173. // basically remove the directory
  1174. std::string dirName = cmStrCat(args[2], "/Progress");
  1175. cmSystemTools::RemoveADirectory(dirName);
  1176. // is the last argument a filename that exists?
  1177. FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
  1178. int count;
  1179. if (countFile) {
  1180. if (1 != fscanf(countFile, "%i", &count)) {
  1181. std::cerr << "Could not read from count file.\n";
  1182. }
  1183. fclose(countFile);
  1184. } else {
  1185. count = atoi(args[3].c_str());
  1186. }
  1187. if (count) {
  1188. cmSystemTools::MakeDirectory(dirName);
  1189. // write the count into the directory
  1190. std::string fName = cmStrCat(dirName, "/count.txt");
  1191. FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
  1192. if (progFile) {
  1193. fprintf(progFile, "%i\n", count);
  1194. fclose(progFile);
  1195. }
  1196. }
  1197. return 0;
  1198. }
  1199. // Command to report progress for a build
  1200. if (args[1] == "cmake_progress_report" && args.size() >= 3) {
  1201. // This has been superseded by cmake_echo_color --progress-*
  1202. // options. We leave it here to avoid errors if somehow this
  1203. // is invoked by an existing makefile without regenerating.
  1204. return 0;
  1205. }
  1206. // Command to create a symbolic link. Fails on platforms not
  1207. // supporting them.
  1208. if (args[1] == "create_symlink" && args.size() == 4) {
  1209. std::string const& destinationFileName = args[3];
  1210. if (cmSystemTools::PathExists(destinationFileName) &&
  1211. !cmSystemTools::RemoveFile(destinationFileName)) {
  1212. std::string emsg = cmSystemTools::GetLastSystemError();
  1213. std::cerr << "failed to create symbolic link '" << destinationFileName
  1214. << "' because existing path cannot be removed: " << emsg
  1215. << '\n';
  1216. return 1;
  1217. }
  1218. if (!cmSystemTools::CreateSymlink(args[2], destinationFileName)) {
  1219. return 1;
  1220. }
  1221. return 0;
  1222. }
  1223. // Command to create a hard link. Fails on platforms not
  1224. // supporting them.
  1225. if (args[1] == "create_hardlink" && args.size() == 4) {
  1226. std::string const& sourceFileName = args[2];
  1227. std::string const& destinationFileName = args[3];
  1228. if (!cmSystemTools::FileExists(sourceFileName)) {
  1229. std::cerr << "failed to create hard link because source path '"
  1230. << sourceFileName << "' does not exist\n";
  1231. return 1;
  1232. }
  1233. if (cmSystemTools::PathExists(destinationFileName) &&
  1234. !cmSystemTools::RemoveFile(destinationFileName)) {
  1235. std::string emsg = cmSystemTools::GetLastSystemError();
  1236. std::cerr << "failed to create hard link '" << destinationFileName
  1237. << "' because existing path cannot be removed: " << emsg
  1238. << '\n';
  1239. return 1;
  1240. }
  1241. if (!cmSystemTools::CreateLink(sourceFileName, destinationFileName)) {
  1242. return 1;
  1243. }
  1244. return 0;
  1245. }
  1246. // Command to do nothing with an exit code of 0.
  1247. if (args[1] == "true") {
  1248. return 0;
  1249. }
  1250. // Command to do nothing with an exit code of 1.
  1251. if (args[1] == "false") {
  1252. return 1;
  1253. }
  1254. // Internal CMake shared library support.
  1255. if (args[1] == "cmake_symlink_library" && args.size() == 5) {
  1256. return cmcmd::SymlinkLibrary(args);
  1257. }
  1258. // Internal CMake versioned executable support.
  1259. if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
  1260. return cmcmd::SymlinkExecutable(args);
  1261. }
  1262. // Internal CMake dependency scanning support.
  1263. // The format is: -E cmake_fastbuild_check_depends <dummy_file>
  1264. // <space_separated_list_of_real_outputs>
  1265. if (args[1] == "cmake_fastbuild_check_depends" && args.size() >= 3) {
  1266. auto const dummyFile = args[2];
  1267. for (auto const& arg : cmMakeRange(args).advance(3)) {
  1268. if (!cmSystemTools::FileExists(arg)) {
  1269. cmSystemTools::RemoveFile(dummyFile);
  1270. return 0;
  1271. }
  1272. }
  1273. return 0;
  1274. }
  1275. if (args[1] == "cmake_depends" && args.size() >= 6) {
  1276. bool const verbose = isCMakeVerbose();
  1277. // Create a cmake object instance to process dependencies.
  1278. // All we need is the `set` command.
  1279. cmake cm(cmake::RoleScript, cmState::Unknown);
  1280. std::string gen;
  1281. std::string homeDir;
  1282. std::string startDir;
  1283. std::string homeOutDir;
  1284. std::string startOutDir;
  1285. std::string depInfo;
  1286. std::string targetName;
  1287. bool color = false;
  1288. if (args.size() >= 8) {
  1289. // Full signature:
  1290. //
  1291. // -E cmake_depends <generator>
  1292. // <home-src-dir> <start-src-dir>
  1293. // <home-out-dir> <start-out-dir>
  1294. // <dep-info> [--color=$(COLOR)]
  1295. // <target-name>
  1296. //
  1297. // All paths are provided.
  1298. gen = args[2];
  1299. homeDir = args[3];
  1300. startDir = args[4];
  1301. homeOutDir = args[5];
  1302. startOutDir = args[6];
  1303. depInfo = args[7];
  1304. size_t targetNameIdx = 8;
  1305. if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
  1306. // Enable or disable color based on the switch value.
  1307. targetNameIdx = 9;
  1308. color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
  1309. }
  1310. if (args.size() > targetNameIdx) {
  1311. targetName = args[targetNameIdx];
  1312. } else {
  1313. std::string targetDir = cmSystemTools::GetFilenamePath(depInfo);
  1314. targetDir = cmSystemTools::GetFilenameName(targetDir);
  1315. targetName = targetDir.substr(0, targetDir.size() - 4);
  1316. }
  1317. } else {
  1318. // Support older signature for existing makefiles:
  1319. //
  1320. // -E cmake_depends <generator>
  1321. // <home-out-dir> <start-out-dir>
  1322. // <dep-info>
  1323. //
  1324. // Just pretend the source directories are the same as the
  1325. // binary directories so at least scanning will work.
  1326. gen = args[2];
  1327. homeDir = args[3];
  1328. startDir = args[4];
  1329. homeOutDir = args[3];
  1330. startOutDir = args[3];
  1331. depInfo = args[5];
  1332. // Strip the `.dir` suffix. Old CMake always uses this pattern.
  1333. std::string targetDir = cmSystemTools::GetFilenamePath(depInfo);
  1334. targetDir = cmSystemTools::GetFilenameName(targetDir);
  1335. targetName = targetDir.substr(0, targetDir.size() - 4);
  1336. }
  1337. // Create a local generator configured for the directory in
  1338. // which dependencies will be scanned.
  1339. homeDir = cmSystemTools::ToNormalizedPathOnDisk(homeDir);
  1340. startDir = cmSystemTools::ToNormalizedPathOnDisk(startDir);
  1341. homeOutDir = cmSystemTools::ToNormalizedPathOnDisk(homeOutDir);
  1342. startOutDir = cmSystemTools::ToNormalizedPathOnDisk(startOutDir);
  1343. cm.SetHomeDirectory(homeDir);
  1344. cm.SetHomeOutputDirectory(homeOutDir);
  1345. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1346. if (auto ggd = cm.CreateGlobalGenerator(gen)) {
  1347. cm.SetGlobalGenerator(std::move(ggd));
  1348. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1349. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1350. snapshot.GetDirectory().SetCurrentSource(startDir);
  1351. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1352. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1353. // FIXME: With advanced add_subdirectory usage, these are
  1354. // not necessarily the same as the generator originally used.
  1355. // We should pass all these directories through an info file.
  1356. lgd->SetRelativePathTop(homeDir, homeOutDir);
  1357. // Actually scan dependencies.
  1358. return lgd->UpdateDependencies(depInfo, targetName, verbose, color)
  1359. ? 0
  1360. : 2;
  1361. }
  1362. return 1;
  1363. }
  1364. #if !defined(CMAKE_BOOTSTRAP) || defined(CMAKE_BOOTSTRAP_MAKEFILES)
  1365. // Internal CMake compiler dependencies filtering
  1366. if (args[1] == "cmake_cl_compile_depends") {
  1367. return CLCompileAndDependencies(args);
  1368. }
  1369. #endif
  1370. // Internal CMake link script support.
  1371. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1372. return cmcmd::ExecuteLinkScript(args);
  1373. }
  1374. #if !defined(CMAKE_BOOTSTRAP)
  1375. // Internal CMake ninja dependency scanning support.
  1376. if (args[1] == "cmake_ninja_depends") {
  1377. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1378. }
  1379. // Internal CMake ninja dyndep support.
  1380. if (args[1] == "cmake_ninja_dyndep") {
  1381. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1382. }
  1383. #endif
  1384. // Internal CMake C++ module compilation database support.
  1385. if (args[1] == "cmake_module_compile_db") {
  1386. return cmcmd_cmake_module_compile_db(args.begin() + 2, args.end());
  1387. }
  1388. // Internal CMake unimplemented feature notification.
  1389. if (args[1] == "cmake_unimplemented_variable") {
  1390. std::cerr << "Feature not implemented for this platform.";
  1391. if (args.size() == 3) {
  1392. std::cerr << " Variable " << args[2] << " is not set.";
  1393. }
  1394. std::cerr << '\n';
  1395. return 1;
  1396. }
  1397. if (args[1] == "vs_link_exe") {
  1398. return cmcmd::VisualStudioLink(args, 1, std::move(console));
  1399. }
  1400. if (args[1] == "vs_link_dll") {
  1401. return cmcmd::VisualStudioLink(args, 2, std::move(console));
  1402. }
  1403. if (args[1] == "cmake_llvm_rc") {
  1404. return cmcmd::RunLLVMRC(args);
  1405. }
  1406. // Internal CMake color makefile support.
  1407. if (args[1] == "cmake_echo_color") {
  1408. return cmcmd::ExecuteEchoColor(args);
  1409. }
  1410. #ifndef CMAKE_BOOTSTRAP
  1411. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1412. cm::string_view const infoFile = args[2];
  1413. cm::string_view const config = args[3];
  1414. cm::string_view const executableConfig =
  1415. (args.size() >= 5) ? cm::string_view(args[4]) : cm::string_view();
  1416. return cmQtAutoMocUic(infoFile, config, executableConfig) ? 0 : 1;
  1417. }
  1418. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1419. cm::string_view const infoFile = args[2];
  1420. cm::string_view const config =
  1421. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1422. cm::string_view const executableConfig =
  1423. (args.size() >= 5) ? cm::string_view(args[4]) : cm::string_view();
  1424. return cmQtAutoRcc(infoFile, config, executableConfig) ? 0 : 1;
  1425. }
  1426. #endif
  1427. // Tar files
  1428. if (args[1] == "tar" && args.size() > 3) {
  1429. char const* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1430. std::string const& flags = args[2];
  1431. std::string const& outFile = args[3];
  1432. std::vector<std::string> files;
  1433. std::string mtime;
  1434. std::string format;
  1435. cmSystemTools::cmTarExtractTimestamps extractTimestamps =
  1436. cmSystemTools::cmTarExtractTimestamps::Yes;
  1437. cmSystemTools::cmTarCompression compress =
  1438. cmSystemTools::TarCompressNone;
  1439. int nCompress = 0;
  1440. bool doing_options = true;
  1441. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1442. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1443. if (arg == "--") {
  1444. doing_options = false;
  1445. } else if (arg == "--zstd") {
  1446. compress = cmSystemTools::TarCompressZstd;
  1447. ++nCompress;
  1448. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1449. mtime = arg.substr(8);
  1450. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1451. std::string const& files_from = arg.substr(13);
  1452. if (!cmTarFilesFrom(files_from, files)) {
  1453. return 1;
  1454. }
  1455. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1456. format = arg.substr(9);
  1457. if (!cm::contains(knownFormats, format)) {
  1458. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1459. format);
  1460. return 1;
  1461. }
  1462. } else if (arg == "--touch") {
  1463. extractTimestamps = cmSystemTools::cmTarExtractTimestamps::No;
  1464. } else {
  1465. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1466. return 1;
  1467. }
  1468. } else {
  1469. files.push_back(arg);
  1470. }
  1471. }
  1472. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1473. bool verbose = false;
  1474. for (auto flag : flags) {
  1475. switch (flag) {
  1476. case '-':
  1477. case 'f': {
  1478. // Keep for backward compatibility. Ignored
  1479. } break;
  1480. case 'j': {
  1481. compress = cmSystemTools::TarCompressBZip2;
  1482. ++nCompress;
  1483. } break;
  1484. case 'J': {
  1485. compress = cmSystemTools::TarCompressXZ;
  1486. ++nCompress;
  1487. } break;
  1488. case 'z': {
  1489. compress = cmSystemTools::TarCompressGZip;
  1490. ++nCompress;
  1491. } break;
  1492. case 'v': {
  1493. verbose = true;
  1494. } break;
  1495. case 't': {
  1496. action = cmSystemTools::TarActionList;
  1497. } break;
  1498. case 'c': {
  1499. action = cmSystemTools::TarActionCreate;
  1500. } break;
  1501. case 'x': {
  1502. action = cmSystemTools::TarActionExtract;
  1503. } break;
  1504. default: {
  1505. std::cerr << "tar: Unknown argument: " << flag << '\n';
  1506. }
  1507. }
  1508. }
  1509. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1510. cmSystemTools::Error("Can not use compression flags with format: " +
  1511. format);
  1512. return 1;
  1513. }
  1514. if (nCompress > 1) {
  1515. cmSystemTools::Error("Can only compress a tar file one way; "
  1516. "at most one flag of z, j, or J may be used");
  1517. return 1;
  1518. }
  1519. if (action == cmSystemTools::TarActionList) {
  1520. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1521. cmSystemTools::Error("Problem listing tar: " + outFile);
  1522. return 1;
  1523. }
  1524. } else if (action == cmSystemTools::TarActionCreate) {
  1525. if (files.empty()) {
  1526. std::cerr << "tar: No files or directories specified\n";
  1527. }
  1528. if (!cmSystemTools::CreateTar(outFile, files, {}, compress, verbose,
  1529. mtime, format)) {
  1530. cmSystemTools::Error("Problem creating tar: " + outFile);
  1531. return 1;
  1532. }
  1533. } else if (action == cmSystemTools::TarActionExtract) {
  1534. if (!cmSystemTools::ExtractTar(outFile, files, extractTimestamps,
  1535. verbose)) {
  1536. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1537. return 1;
  1538. }
  1539. #ifdef _WIN32
  1540. // OK, on windows 7 after we untar some files,
  1541. // sometimes we can not rename the directory after
  1542. // the untar is done. This breaks the external project
  1543. // untar and rename code. So, by default we will wait
  1544. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1545. // is set in the env, its value will be used instead of 100.
  1546. int delay = 100;
  1547. std::string delayVar;
  1548. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1549. delay = atoi(delayVar.c_str());
  1550. }
  1551. if (delay) {
  1552. cmSystemTools::Delay(delay);
  1553. }
  1554. #endif
  1555. } else {
  1556. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1557. "(list), 'c' (create) or 'x' (extract)");
  1558. return 1;
  1559. }
  1560. return 0;
  1561. }
  1562. if (args[1] == "server") {
  1563. cmSystemTools::Error(
  1564. "CMake server mode has been removed in favor of the file-api.");
  1565. return 1;
  1566. }
  1567. #if !defined(CMAKE_BOOTSTRAP)
  1568. // Internal CMake Fortran module support.
  1569. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1570. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1571. }
  1572. #endif
  1573. #if defined(_WIN32) && !defined(__CYGWIN__)
  1574. // Write registry value
  1575. if (args[1] == "write_regv" && args.size() > 3) {
  1576. return cmSystemTools::WriteRegistryValue(args[2], args[3]) ? 0 : 1;
  1577. }
  1578. // Delete registry value
  1579. if (args[1] == "delete_regv" && args.size() > 2) {
  1580. return cmSystemTools::DeleteRegistryValue(args[2]) ? 0 : 1;
  1581. }
  1582. // Remove file
  1583. if (args[1] == "comspec" && args.size() > 2) {
  1584. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1585. return 1;
  1586. }
  1587. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1588. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1589. }
  1590. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1591. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1592. }
  1593. #endif
  1594. // Internal depfile transformation
  1595. if (args[1] == "cmake_transform_depfile" && args.size() == 10) {
  1596. auto format = cmDepfileFormat::GccDepfile;
  1597. if (args[3] == "gccdepfile") {
  1598. format = cmDepfileFormat::GccDepfile;
  1599. } else if (args[3] == "makedepfile") {
  1600. format = cmDepfileFormat::MakeDepfile;
  1601. } else if (args[3] == "MSBuildAdditionalInputs") {
  1602. format = cmDepfileFormat::MSBuildAdditionalInputs;
  1603. } else {
  1604. return 1;
  1605. }
  1606. // Create a cmake object instance to process dependencies.
  1607. // All we need is the `set` command.
  1608. cmake cm(cmake::RoleScript, cmState::Unknown);
  1609. std::string homeDir;
  1610. std::string startDir;
  1611. std::string homeOutDir;
  1612. std::string startOutDir;
  1613. homeDir = cmSystemTools::ToNormalizedPathOnDisk(args[4]);
  1614. startDir = cmSystemTools::ToNormalizedPathOnDisk(args[5]);
  1615. homeOutDir = cmSystemTools::ToNormalizedPathOnDisk(args[6]);
  1616. startOutDir = cmSystemTools::ToNormalizedPathOnDisk(args[7]);
  1617. cm.SetHomeDirectory(homeDir);
  1618. cm.SetHomeOutputDirectory(homeOutDir);
  1619. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  1620. if (auto ggd = cm.CreateGlobalGenerator(args[2])) {
  1621. cm.SetGlobalGenerator(std::move(ggd));
  1622. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1623. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1624. snapshot.GetDirectory().SetCurrentSource(startDir);
  1625. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1626. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1627. // FIXME: With advanced add_subdirectory usage, these are
  1628. // not necessarily the same as the generator originally used.
  1629. // We should pass all these directories through an info file.
  1630. lgd->SetRelativePathTop(homeDir, homeOutDir);
  1631. return cmTransformDepfile(format, *lgd, args[8], args[9]) ? 0 : 2;
  1632. }
  1633. return 1;
  1634. }
  1635. }
  1636. CMakeCommandUsage(args[0]);
  1637. return 1;
  1638. }
  1639. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1640. cmCryptoHash::Algo algo)
  1641. {
  1642. if (args.size() < 3) {
  1643. return -1;
  1644. }
  1645. int retval = 0;
  1646. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1647. // Cannot compute sum of a directory
  1648. if (cmSystemTools::FileIsDirectory(filename)) {
  1649. std::cerr << "Error: " << filename << " is a directory\n";
  1650. retval++;
  1651. } else {
  1652. cmCryptoHash hasher(algo);
  1653. std::string value = hasher.HashFile(filename);
  1654. if (value.empty()) {
  1655. // To mimic "md5sum/shasum" behavior in a shell:
  1656. std::cerr << filename << ": No such file or directory\n";
  1657. retval++;
  1658. } else {
  1659. std::cout << value << " " << filename << '\n';
  1660. }
  1661. }
  1662. }
  1663. return retval;
  1664. }
  1665. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1666. {
  1667. int result = 0;
  1668. std::string realName = args[2];
  1669. std::string soName = args[3];
  1670. std::string name = args[4];
  1671. cmSystemTools::ConvertToUnixSlashes(realName);
  1672. cmSystemTools::ConvertToUnixSlashes(soName);
  1673. cmSystemTools::ConvertToUnixSlashes(name);
  1674. if (soName != realName) {
  1675. cmsys::Status status = cmcmd::SymlinkInternal(realName, soName);
  1676. if (!status) {
  1677. cmSystemTools::Error(
  1678. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1679. result = 1;
  1680. }
  1681. }
  1682. if (name != soName) {
  1683. cmsys::Status status = cmcmd::SymlinkInternal(soName, name);
  1684. if (!status) {
  1685. cmSystemTools::Error(
  1686. cmStrCat("cmake_symlink_library: System Error: ", status.GetString()));
  1687. result = 1;
  1688. }
  1689. }
  1690. return result;
  1691. }
  1692. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1693. {
  1694. int result = 0;
  1695. std::string const& realName = args[2];
  1696. std::string const& name = args[3];
  1697. if (name != realName) {
  1698. cmsys::Status status = cmcmd::SymlinkInternal(realName, name);
  1699. if (!status) {
  1700. cmSystemTools::Error(cmStrCat("cmake_symlink_executable: System Error: ",
  1701. status.GetString()));
  1702. result = 1;
  1703. }
  1704. }
  1705. return result;
  1706. }
  1707. cmsys::Status cmcmd::SymlinkInternal(std::string const& file,
  1708. std::string const& link)
  1709. {
  1710. if (cmSystemTools::PathExists(link)) {
  1711. cmSystemTools::RemoveFile(link);
  1712. }
  1713. std::string linktext = cmSystemTools::GetFilenameName(file);
  1714. #if defined(_WIN32) && !defined(__CYGWIN__)
  1715. cmsys::Status status = cmSystemTools::CreateSymlinkQuietly(linktext, link);
  1716. // Creating a symlink will fail with ERROR_PRIVILEGE_NOT_HELD if the user
  1717. // does not have SeCreateSymbolicLinkPrivilege, or if developer mode is not
  1718. // active. In that case, we try to copy the file.
  1719. if (status.GetWindows() == ERROR_PRIVILEGE_NOT_HELD) {
  1720. status = cmSystemTools::CopyFileAlways(file, link);
  1721. } else if (!status) {
  1722. cmSystemTools::Error(cmStrCat("failed to create symbolic link '", link,
  1723. "': ", status.GetString()));
  1724. }
  1725. return status;
  1726. #else
  1727. return cmSystemTools::CreateSymlink(linktext, link);
  1728. #endif
  1729. }
  1730. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1731. {
  1732. std::string dirName = cmStrCat(dir, "/Progress");
  1733. std::string fName;
  1734. FILE* progFile;
  1735. // read the count
  1736. fName = cmStrCat(dirName, "/count.txt");
  1737. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1738. int count = 0;
  1739. if (!progFile) {
  1740. return;
  1741. }
  1742. if (1 != fscanf(progFile, "%i", &count)) {
  1743. std::cerr << "Could not read from progress file.\n";
  1744. }
  1745. fclose(progFile);
  1746. char const* last = num.c_str();
  1747. for (char const* c = last;; ++c) {
  1748. if (*c == ',' || *c == '\0') {
  1749. if (c != last) {
  1750. fName = cmStrCat(dirName, '/');
  1751. fName.append(last, c - last);
  1752. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1753. if (progFile) {
  1754. fprintf(progFile, "empty");
  1755. fclose(progFile);
  1756. }
  1757. }
  1758. if (*c == '\0') {
  1759. break;
  1760. }
  1761. last = c + 1;
  1762. }
  1763. }
  1764. int fileNum =
  1765. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1766. if (count > 0) {
  1767. int const percent = ((fileNum - 3) * 100) / count;
  1768. std::cout << '[' << std::setw(3) << percent << "%] ";
  1769. }
  1770. }
  1771. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1772. {
  1773. // The arguments are
  1774. // args[0] == <cmake-executable>
  1775. // args[1] == cmake_echo_color
  1776. bool enabled = true;
  1777. static cm::StdIo::TermAttrSet const noAttrs;
  1778. cm::StdIo::TermAttrSet attrs;
  1779. bool newline = true;
  1780. std::string progressDir;
  1781. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1782. if (cmHasLiteralPrefix(arg, "--switch=")) {
  1783. // Enable or disable color based on the switch value.
  1784. std::string value = arg.substr(9);
  1785. if (!value.empty()) {
  1786. enabled = cmIsOn(value);
  1787. }
  1788. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1789. progressDir = arg.substr(15);
  1790. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1791. if (!progressDir.empty()) {
  1792. std::string const& progressNum = arg.substr(15);
  1793. cmcmdProgressReport(progressDir, progressNum);
  1794. }
  1795. } else if (arg == "--normal") {
  1796. attrs = cm::StdIo::TermAttr::Normal;
  1797. } else if (arg == "--black") {
  1798. attrs = cm::StdIo::TermAttr::ForegroundBlack;
  1799. } else if (arg == "--red") {
  1800. attrs = cm::StdIo::TermAttr::ForegroundRed;
  1801. } else if (arg == "--green") {
  1802. attrs = cm::StdIo::TermAttr::ForegroundGreen;
  1803. } else if (arg == "--yellow") {
  1804. attrs = cm::StdIo::TermAttr::ForegroundYellow;
  1805. } else if (arg == "--blue") {
  1806. attrs = cm::StdIo::TermAttr::ForegroundBlue;
  1807. } else if (arg == "--magenta") {
  1808. attrs = cm::StdIo::TermAttr::ForegroundMagenta;
  1809. } else if (arg == "--cyan") {
  1810. attrs = cm::StdIo::TermAttr::ForegroundCyan;
  1811. } else if (arg == "--white") {
  1812. attrs = cm::StdIo::TermAttr::ForegroundWhite;
  1813. } else if (arg == "--bold") {
  1814. if (attrs.empty()) {
  1815. attrs = cm::StdIo::TermAttr::Normal;
  1816. }
  1817. attrs |= cm::StdIo::TermAttr::ForegroundBold;
  1818. } else if (arg == "--no-newline") {
  1819. newline = false;
  1820. } else if (arg == "--newline") {
  1821. newline = true;
  1822. } else {
  1823. Print(cm::StdIo::Out(), enabled ? attrs : noAttrs, arg);
  1824. if (newline) {
  1825. std::cout << std::endl;
  1826. }
  1827. }
  1828. }
  1829. return 0;
  1830. }
  1831. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1832. {
  1833. // The arguments are
  1834. // args[0] == <cmake-executable>
  1835. // args[1] == cmake_link_script
  1836. // args[2] == <link-script-name>
  1837. // args[3] == --verbose=?
  1838. bool verbose = false;
  1839. if (args.size() >= 4) {
  1840. if (cmHasLiteralPrefix(args[3], "--verbose=")) {
  1841. if (!cmIsOff(args[3].substr(10))) {
  1842. verbose = true;
  1843. }
  1844. }
  1845. }
  1846. // Read command lines from the script.
  1847. cmsys::ifstream fin(args[2].c_str());
  1848. if (!fin) {
  1849. std::cerr << "Error opening link script \"" << args[2] << "\"\n";
  1850. return 1;
  1851. }
  1852. // Run one command at a time.
  1853. std::string command;
  1854. int result = 0;
  1855. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1856. // Skip empty command lines.
  1857. if (command.find_first_not_of(" \t") == std::string::npos) {
  1858. continue;
  1859. }
  1860. // Allocate a process instance.
  1861. cmUVProcessChainBuilder builder;
  1862. // Children should share stdout and stderr with this process.
  1863. builder.SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT, stdout)
  1864. .SetExternalStream(cmUVProcessChainBuilder::Stream_ERROR, stderr);
  1865. // Setup this command line.
  1866. std::vector<std::string> args2;
  1867. #ifdef _WIN32
  1868. cmSystemTools::ParseWindowsCommandLine(command.c_str(), args2);
  1869. #else
  1870. cmSystemTools::ParseUnixCommandLine(command.c_str(), args2);
  1871. #endif
  1872. builder.AddCommand(args2);
  1873. // Report the command if verbose output is enabled.
  1874. if (verbose) {
  1875. std::cout << command << '\n';
  1876. }
  1877. // Run the command and wait for it to exit.
  1878. auto chain = builder.Start();
  1879. chain.Wait();
  1880. // Report failure if any.
  1881. auto const& status = chain.GetStatus(0);
  1882. auto exception = status.GetException();
  1883. switch (exception.first) {
  1884. case cmUVProcessChain::ExceptionCode::None:
  1885. if (status.ExitStatus != 0) {
  1886. result = static_cast<int>(status.ExitStatus);
  1887. }
  1888. break;
  1889. case cmUVProcessChain::ExceptionCode::Spawn:
  1890. std::cerr << "Error running link command: " << exception.second;
  1891. result = 2;
  1892. break;
  1893. default:
  1894. std::cerr << "Error running link command: " << exception.second;
  1895. result = 1;
  1896. break;
  1897. }
  1898. }
  1899. // Return the final resulting return value.
  1900. return result;
  1901. }
  1902. int cmcmd::WindowsCEEnvironment(char const* version, std::string const& name)
  1903. {
  1904. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1905. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1906. parser.ParseVersion(version);
  1907. if (parser.Found()) {
  1908. /* clang-format off */
  1909. std::cout << "@echo off\n"
  1910. "echo Environment Selection: " << name << "\n"
  1911. "set PATH=" << parser.GetPathDirectories() << "\n"
  1912. "set INCLUDE=" << parser.GetIncludeDirectories() << "\n"
  1913. "set LIB=" << parser.GetLibraryDirectories() << '\n';
  1914. /* clang-format on */
  1915. return 0;
  1916. }
  1917. #else
  1918. (void)version;
  1919. #endif
  1920. std::cerr << "Could not find " << name;
  1921. return -1;
  1922. }
  1923. int cmcmd::RunPreprocessor(std::vector<std::string> const& command,
  1924. std::string const& intermediate_file)
  1925. {
  1926. cmUVProcessChainBuilder builder;
  1927. uv_fs_t fs_req;
  1928. int preprocessedFile =
  1929. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1930. 0644, nullptr);
  1931. uv_fs_req_cleanup(&fs_req);
  1932. builder
  1933. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1934. preprocessedFile)
  1935. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1936. .AddCommand(command);
  1937. auto process = builder.Start();
  1938. if (!process.Valid() || process.GetStatus(0).SpawnResult != 0) {
  1939. std::cerr << "Failed to start preprocessor.";
  1940. return 1;
  1941. }
  1942. if (!process.Wait()) {
  1943. std::cerr << "Failed to wait for preprocessor";
  1944. return 1;
  1945. }
  1946. if (process.GetStatus(0).ExitStatus != 0) {
  1947. cmUVPipeIStream errorStream(process.GetLoop(), process.ErrorStream());
  1948. std::cerr << errorStream.rdbuf();
  1949. return 1;
  1950. }
  1951. return 0;
  1952. }
  1953. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1954. {
  1955. // The arguments are
  1956. // args[0] == <cmake-executable>
  1957. // args[1] == cmake_llvm_rc
  1958. // args[2] == source_file_path
  1959. // args[3] == intermediate_file
  1960. // args[4..n] == preprocess+args
  1961. // args[n+1] == ++
  1962. // args[n+2...] == llvm-rc+args
  1963. if (args.size() < 3) {
  1964. std::cerr << "Invalid cmake_llvm_rc arguments";
  1965. return 1;
  1966. }
  1967. std::string const& intermediate_file = args[3];
  1968. std::string const& source_file = args[2];
  1969. std::vector<std::string> preprocess;
  1970. std::vector<std::string> resource_compile;
  1971. std::vector<std::string>* pArgTgt = &preprocess;
  1972. static cmsys::RegularExpression const llvm_rc_only_single_arg("^[-/](N|Y)");
  1973. static cmsys::RegularExpression const llvm_rc_only_double_arg(
  1974. "^[-/](C|LN|L)(.)?");
  1975. static cmsys::RegularExpression const common_double_arg(
  1976. "^[-/](D|U|I|FO|fo|Fo)(.)?"); // noqa: spellcheck disable-line
  1977. bool acceptNextArg = false;
  1978. bool skipNextArg = false;
  1979. for (std::string const& arg : cmMakeRange(args).advance(4)) {
  1980. if (skipNextArg) {
  1981. skipNextArg = false;
  1982. continue;
  1983. }
  1984. // We use ++ as separator between the preprocessing step definition and
  1985. // the rc compilation step because we need to prepend a -- to separate the
  1986. // source file properly from other options when using clang-cl for
  1987. // preprocessing.
  1988. if (arg == "++") {
  1989. pArgTgt = &resource_compile;
  1990. skipNextArg = false;
  1991. acceptNextArg = true;
  1992. } else {
  1993. cmsys::RegularExpressionMatch match;
  1994. if (!acceptNextArg) {
  1995. if (common_double_arg.find(arg.c_str(), match)) {
  1996. acceptNextArg = match.match(2).empty();
  1997. } else {
  1998. if (llvm_rc_only_single_arg.find(arg.c_str(), match)) {
  1999. if (pArgTgt == &preprocess) {
  2000. continue;
  2001. }
  2002. } else if (llvm_rc_only_double_arg.find(arg.c_str(), match)) {
  2003. if (pArgTgt == &preprocess) {
  2004. skipNextArg = match.match(2).empty();
  2005. continue;
  2006. }
  2007. acceptNextArg = match.match(2).empty();
  2008. } else if (pArgTgt == &resource_compile) {
  2009. continue;
  2010. }
  2011. }
  2012. } else {
  2013. acceptNextArg = false;
  2014. }
  2015. if (arg.find("SOURCE_DIR") != std::string::npos) {
  2016. std::string sourceDirArg = arg;
  2017. cmSystemTools::ReplaceString(
  2018. sourceDirArg, "SOURCE_DIR",
  2019. cmSystemTools::GetFilenamePath(source_file));
  2020. pArgTgt->push_back(sourceDirArg);
  2021. } else {
  2022. pArgTgt->push_back(arg);
  2023. }
  2024. }
  2025. }
  2026. if (preprocess.empty()) {
  2027. std::cerr << "Empty preprocessing command";
  2028. return 1;
  2029. }
  2030. if (resource_compile.empty()) {
  2031. std::cerr << "Empty resource compilation command";
  2032. return 1;
  2033. }
  2034. // Since we might have skipped the last argument to llvm-rc
  2035. // we need to make sure the llvm-rc source file is present in the
  2036. // commandline
  2037. if (resource_compile.back() != intermediate_file) {
  2038. resource_compile.push_back(intermediate_file);
  2039. }
  2040. auto result = RunPreprocessor(preprocess, intermediate_file);
  2041. if (result != 0) {
  2042. cmSystemTools::RemoveFile(intermediate_file);
  2043. return result;
  2044. }
  2045. cmUVProcessChainBuilder builder;
  2046. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  2047. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  2048. .AddCommand(resource_compile);
  2049. auto process = builder.Start();
  2050. result = 0;
  2051. if (!process.Valid() || process.GetStatus(0).SpawnResult != 0) {
  2052. std::cerr << "Failed to start resource compiler.";
  2053. result = 1;
  2054. } else {
  2055. if (!process.Wait()) {
  2056. std::cerr << "Failed to wait for resource compiler";
  2057. result = 1;
  2058. }
  2059. }
  2060. cmSystemTools::RemoveFile(intermediate_file);
  2061. if (result != 0) {
  2062. return result;
  2063. }
  2064. if (process.GetStatus(0).ExitStatus != 0) {
  2065. cmUVPipeIStream errorStream(process.GetLoop(), process.ErrorStream());
  2066. std::cerr << errorStream.rdbuf();
  2067. return 1;
  2068. }
  2069. return 0;
  2070. }
  2071. class cmVSLink
  2072. {
  2073. int Type;
  2074. bool Verbose;
  2075. bool Incremental = false;
  2076. bool LinkEmbedsManifest = true;
  2077. bool LinkGeneratesManifest = true;
  2078. std::vector<std::string> LinkCommand;
  2079. std::vector<std::string> UserManifests;
  2080. std::string LinkerManifestFile;
  2081. std::string ManifestFile;
  2082. std::string ManifestFileRC;
  2083. std::string ManifestFileRes;
  2084. std::string TargetFile;
  2085. std::string MtPath;
  2086. std::string RcPath;
  2087. public:
  2088. cmVSLink(int type, bool verbose)
  2089. : Type(type)
  2090. , Verbose(verbose)
  2091. {
  2092. }
  2093. bool Parse(std::vector<std::string>::const_iterator argBeg,
  2094. std::vector<std::string>::const_iterator argEnd);
  2095. int Link();
  2096. private:
  2097. int LinkIncremental();
  2098. int LinkNonIncremental();
  2099. int RunMT(std::string const& out, bool notify);
  2100. };
  2101. // For visual studio 2005 and newer manifest files need to be embedded into
  2102. // exe and dll's. This code does that in such a way that incremental linking
  2103. // still works.
  2104. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type,
  2105. cm::optional<cm::StdIo::Console> console)
  2106. {
  2107. // MSVC tools print output in the language specified by the VSLANG
  2108. // environment variable, and encoded in the console output code page.
  2109. // Since vs_link_{exe,dll} just wraps these, pass through that encoding.
  2110. // RunCommand tells RunSingleCommand to *not* convert encoding, so
  2111. // we buffer the output in its original encoding instead of UTF-8.
  2112. // Drop our output encoding conversion so we print with original encoding.
  2113. console.reset();
  2114. if (args.size() < 2) {
  2115. return -1;
  2116. }
  2117. bool const verbose = cmSystemTools::HasEnv("VERBOSE");
  2118. std::vector<std::string> expandedArgs;
  2119. for (std::string const& i : args) {
  2120. // check for nmake temporary files
  2121. if (i[0] == '@' &&
  2122. !(cmHasLiteralPrefix(i, "@CMakeFiles") ||
  2123. cmHasLiteralPrefix(i, "@.o/") || cmHasLiteralPrefix(i, "@.o\\"))) {
  2124. cmsys::ifstream fin(i.substr(1).c_str());
  2125. std::string line;
  2126. while (cmSystemTools::GetLineFromStream(fin, line)) {
  2127. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  2128. }
  2129. } else {
  2130. expandedArgs.push_back(i);
  2131. }
  2132. }
  2133. cmVSLink vsLink(type, verbose);
  2134. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  2135. return -1;
  2136. }
  2137. return vsLink.Link();
  2138. }
  2139. enum NumberFormat
  2140. {
  2141. FORMAT_DECIMAL,
  2142. FORMAT_HEX
  2143. };
  2144. struct NumberFormatter
  2145. {
  2146. NumberFormat Format;
  2147. int Value;
  2148. NumberFormatter(NumberFormat format, int value)
  2149. : Format(format)
  2150. , Value(value)
  2151. {
  2152. }
  2153. };
  2154. static std::ostream& operator<<(std::ostream& stream,
  2155. NumberFormatter const& formatter)
  2156. {
  2157. auto const& flags = stream.flags();
  2158. if (formatter.Format == FORMAT_DECIMAL) {
  2159. stream << std::dec << formatter.Value;
  2160. } else {
  2161. stream << "0x" << std::hex << formatter.Value;
  2162. }
  2163. stream.flags(flags);
  2164. return stream;
  2165. }
  2166. static bool RunCommand(char const* comment,
  2167. std::vector<std::string> const& command, bool verbose,
  2168. NumberFormat exitFormat, int* retCodeOut = nullptr,
  2169. bool (*retCodeOkay)(int) = nullptr)
  2170. {
  2171. // See comment in VisualStudioLink for why we suppress encoding conversion.
  2172. cmProcessOutput::Encoding const encoding = cmProcessOutput::None;
  2173. if (verbose) {
  2174. std::cout << comment << ":\n";
  2175. std::cout << cmJoin(command, " ") << '\n';
  2176. }
  2177. std::string output;
  2178. int retCode = 0;
  2179. bool commandResult = cmSystemTools::RunSingleCommand(
  2180. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE,
  2181. cmDuration::zero(), encoding);
  2182. bool const retCodeSuccess =
  2183. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  2184. bool const success = commandResult && retCodeSuccess;
  2185. if (retCodeOut) {
  2186. if (commandResult || !retCodeSuccess) {
  2187. *retCodeOut = retCode;
  2188. } else {
  2189. *retCodeOut = -1;
  2190. }
  2191. }
  2192. if (!success) {
  2193. std::cout << comment << ": command \"" << cmJoin(command, " ")
  2194. << "\" failed (exit code "
  2195. << NumberFormatter(exitFormat, retCode)
  2196. << ") with the following output:\n"
  2197. << output;
  2198. } else if (verbose) {
  2199. // always print the output of the command, unless
  2200. // it is the dumb rc command banner
  2201. if (output.find("Resource Compiler Version") == std::string::npos) {
  2202. std::cout << output;
  2203. }
  2204. }
  2205. return success;
  2206. }
  2207. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  2208. std::vector<std::string>::const_iterator argEnd)
  2209. {
  2210. // Parse our own arguments.
  2211. std::string intDir;
  2212. auto arg = argBeg;
  2213. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  2214. if (*arg == "--") {
  2215. ++arg;
  2216. break;
  2217. }
  2218. if (*arg == "--manifests") {
  2219. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  2220. this->UserManifests.push_back(*arg);
  2221. }
  2222. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  2223. intDir = arg->substr(9);
  2224. ++arg;
  2225. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  2226. this->RcPath = arg->substr(5);
  2227. ++arg;
  2228. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  2229. this->MtPath = arg->substr(5);
  2230. ++arg;
  2231. } else if (cmHasLiteralPrefix(*arg, "--msvc-ver=")) {
  2232. unsigned long msvc_ver = 0;
  2233. if (cmStrToULong(arg->c_str() + 11, &msvc_ver)) {
  2234. this->LinkEmbedsManifest = msvc_ver > 1600;
  2235. }
  2236. ++arg;
  2237. } else {
  2238. std::cerr << "unknown argument '" << *arg << "'\n";
  2239. return false;
  2240. }
  2241. }
  2242. if (intDir.empty()) {
  2243. return false;
  2244. }
  2245. // The rest of the arguments form the link command.
  2246. if (arg == argEnd) {
  2247. return false;
  2248. }
  2249. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  2250. // Parse the link command to extract information we need.
  2251. for (; arg != argEnd; ++arg) {
  2252. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0 ||
  2253. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL:YES") == 0 ||
  2254. cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0 ||
  2255. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL") == 0) {
  2256. this->Incremental = true;
  2257. } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:NO") == 0 ||
  2258. cmSystemTools::Strucmp(arg->c_str(), "-INCREMENTAL:NO") == 0) {
  2259. this->Incremental = false;
  2260. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0 ||
  2261. cmSystemTools::Strucmp(arg->c_str(), "-MANIFEST:NO") == 0) {
  2262. this->LinkGeneratesManifest = false;
  2263. } else if (cmHasLiteralPrefix(*arg, "/Fe") ||
  2264. cmHasLiteralPrefix(*arg, "-Fe")) {
  2265. this->TargetFile = arg->substr(3);
  2266. } else if (cmHasLiteralPrefix(*arg, "/out:") ||
  2267. cmHasLiteralPrefix(*arg, "-out:")) {
  2268. this->TargetFile = arg->substr(5);
  2269. }
  2270. }
  2271. if (this->TargetFile.empty()) {
  2272. return false;
  2273. }
  2274. this->ManifestFile = intDir + "/embed.manifest";
  2275. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  2276. if (this->Incremental) {
  2277. // We will compile a resource containing the manifest and
  2278. // pass it to the link command.
  2279. this->ManifestFileRC = intDir + "/manifest.rc";
  2280. this->ManifestFileRes = intDir + "/manifest.res";
  2281. }
  2282. if (this->LinkGeneratesManifest &&
  2283. (this->Incremental || !this->LinkEmbedsManifest)) {
  2284. this->LinkCommand.emplace_back("/MANIFEST");
  2285. this->LinkCommand.emplace_back("/MANIFESTFILE:" +
  2286. this->LinkerManifestFile);
  2287. }
  2288. return true;
  2289. }
  2290. int cmVSLink::Link()
  2291. {
  2292. if (this->Incremental &&
  2293. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  2294. if (this->Verbose) {
  2295. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  2296. }
  2297. return this->LinkIncremental();
  2298. }
  2299. if (this->Verbose) {
  2300. if (!this->Incremental) {
  2301. std::cout << "Visual Studio Non-Incremental Link\n";
  2302. } else {
  2303. std::cout << "Visual Studio Incremental Link without manifests\n";
  2304. }
  2305. }
  2306. return this->LinkNonIncremental();
  2307. }
  2308. static bool mtRetIsUpdate(int mtRet)
  2309. {
  2310. // 'mt /notify_update' returns a special value (differing between
  2311. // Windows and POSIX hosts) when it updated the manifest file.
  2312. return mtRet == 0x41020001 || mtRet == 0xbb;
  2313. }
  2314. int cmVSLink::LinkIncremental()
  2315. {
  2316. // This follows the steps listed here:
  2317. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  2318. // 1. Compiler compiles the application and generates the *.obj files.
  2319. // 2. An empty manifest file is generated if this is a clean build and
  2320. // if not the previous one is reused.
  2321. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  2322. // *.res file.
  2323. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  2324. // switch and embeds the dummy manifest file. The linker also generates
  2325. // the real manifest file based on the binaries that your binary depends
  2326. // on.
  2327. // 5. The manifest tool (mt.exe) is then used to generate the final
  2328. // manifest.
  2329. // If the final manifest is changed, then 6 and 7 are run, if not
  2330. // they are skipped, and it is done.
  2331. // 6. The resource compiler is invoked one more time.
  2332. // 7. Finally, the Linker does another incremental link, but since the
  2333. // only thing that has changed is the *.res file that contains the
  2334. // manifest it is a short link.
  2335. // Create a resource file referencing the manifest.
  2336. std::string absManifestFile =
  2337. cmSystemTools::ToNormalizedPathOnDisk(this->ManifestFile);
  2338. if (this->Verbose) {
  2339. std::cout << "Create " << this->ManifestFileRC << '\n';
  2340. }
  2341. {
  2342. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  2343. if (!fout) {
  2344. return -1;
  2345. }
  2346. // Insert a pragma statement to specify utf-8 encoding.
  2347. fout << "#pragma code_page(65001)\n"
  2348. << this->Type
  2349. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  2350. "24 /* RT_MANIFEST */ \""
  2351. << absManifestFile << "\"";
  2352. }
  2353. // If we have not previously generated a manifest file,
  2354. // generate a manifest file so the resource compiler succeeds.
  2355. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  2356. if (this->Verbose) {
  2357. std::cout << "Create empty: " << this->ManifestFile << '\n';
  2358. }
  2359. if (this->UserManifests.empty()) {
  2360. // generate an empty manifest because there are no user provided
  2361. // manifest files.
  2362. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  2363. } else {
  2364. this->RunMT("/out:" + this->ManifestFile, false);
  2365. }
  2366. }
  2367. // Compile the resource file.
  2368. std::vector<std::string> rcCommand;
  2369. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  2370. rcCommand.emplace_back("/fo"); // noqa: spellcheck disable-line
  2371. rcCommand.push_back(this->ManifestFileRes);
  2372. rcCommand.push_back(this->ManifestFileRC);
  2373. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2374. return -1;
  2375. }
  2376. // Tell the linker to use our manifest compiled into a resource.
  2377. this->LinkCommand.push_back(this->ManifestFileRes);
  2378. // Run the link command (possibly generates intermediate manifest).
  2379. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  2380. FORMAT_DECIMAL)) {
  2381. return -1;
  2382. }
  2383. // Run the manifest tool to create the final manifest.
  2384. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  2385. // If mt returns a special value then it updated the manifest file so
  2386. // we need to embed it again. Otherwise we are done.
  2387. if (!mtRetIsUpdate(mtRet)) {
  2388. return mtRet;
  2389. }
  2390. // Compile the resource file again.
  2391. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  2392. return -1;
  2393. }
  2394. // Link incrementally again to use the updated resource.
  2395. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  2396. FORMAT_DECIMAL)) {
  2397. return -1;
  2398. }
  2399. return 0;
  2400. }
  2401. int cmVSLink::LinkNonIncremental()
  2402. {
  2403. if (!this->LinkEmbedsManifest) {
  2404. // Run the link command (possibly generates intermediate manifest).
  2405. if (!RunCommand("LINK", this->LinkCommand, this->Verbose,
  2406. FORMAT_DECIMAL)) {
  2407. return -1;
  2408. }
  2409. // If we have no manifest files we are done.
  2410. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  2411. return 0;
  2412. }
  2413. // Run the manifest tool to embed the final manifest in the binary.
  2414. std::string mtOut = "/outputresource:" + this->TargetFile +
  2415. (this->Type == 1 ? ";#1" : ";#2");
  2416. return this->RunMT(mtOut, false);
  2417. }
  2418. // The MSVC link tool expects 'rc' to be in the PATH if it needs to embed
  2419. // manifests, but the user might explicitly set 'CMAKE_RC_COMPILER' instead.
  2420. // Add its location as a fallback at the end of PATH.
  2421. if (cmSystemTools::FileIsFullPath(this->RcPath)) {
  2422. std::string rcDir = cmSystemTools::GetFilenamePath(this->RcPath);
  2423. #ifdef _WIN32
  2424. std::replace(rcDir.begin(), rcDir.end(), '/', '\\');
  2425. char const pathSep = ';';
  2426. #else
  2427. char const pathSep = ':';
  2428. #endif
  2429. cm::optional<std::string> path = cmSystemTools::GetEnvVar("PATH");
  2430. if (path) {
  2431. path = cmStrCat(*path, pathSep, rcDir);
  2432. } else {
  2433. path = rcDir;
  2434. }
  2435. cmSystemTools::PutEnv(cmStrCat("PATH=", *path));
  2436. }
  2437. // Sort out any manifests.
  2438. if (this->LinkGeneratesManifest || !this->UserManifests.empty()) {
  2439. std::string opt =
  2440. std::string("/MANIFEST:EMBED,ID=") + (this->Type == 1 ? '1' : '2');
  2441. this->LinkCommand.emplace_back(opt);
  2442. for (auto const& m : this->UserManifests) {
  2443. opt = "/MANIFESTINPUT:" + m;
  2444. this->LinkCommand.emplace_back(opt);
  2445. }
  2446. }
  2447. // Run the link command.
  2448. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  2449. return -1;
  2450. }
  2451. return 0;
  2452. }
  2453. int cmVSLink::RunMT(std::string const& out, bool notify)
  2454. {
  2455. std::vector<std::string> mtCommand;
  2456. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  2457. mtCommand.emplace_back("/nologo");
  2458. // add the linker generated manifest if the file exists.
  2459. if (this->LinkGeneratesManifest &&
  2460. cmSystemTools::FileExists(this->LinkerManifestFile)) {
  2461. mtCommand.emplace_back("/manifest");
  2462. mtCommand.push_back(this->LinkerManifestFile);
  2463. }
  2464. for (auto const& m : this->UserManifests) {
  2465. mtCommand.emplace_back("/manifest");
  2466. mtCommand.push_back(m);
  2467. }
  2468. mtCommand.push_back(out);
  2469. if (notify) {
  2470. // Add an undocumented option that enables a special return
  2471. // code to notify us when the manifest is modified.
  2472. mtCommand.emplace_back("/notify_update");
  2473. }
  2474. int mtRet = 0;
  2475. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  2476. mtRetIsUpdate)) {
  2477. return -1;
  2478. }
  2479. return mtRet;
  2480. }