cmcmd.cxx 51 KB

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