cmcmd.cxx 72 KB

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