cmcmd.cxx 50 KB

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