cmcmd.cxx 52 KB

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