cmcmd.cxx 54 KB

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