cmcmd.cxx 54 KB

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