cmcmd.cxx 52 KB

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