cmcmd.cxx 51 KB

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