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