cmcmd.cxx 52 KB

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