cmcmd.cxx 61 KB

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