cmcmd.cxx 62 KB

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