cmcmd.cxx 55 KB

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