cmcmd.cxx 50 KB

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