cmcmd.cxx 63 KB

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