cmcmd.cxx 60 KB

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