cmcmd.cxx 66 KB

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