cmcmd.cxx 71 KB

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