cmcmd.cxx 52 KB

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