cmcmd.cxx 54 KB

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