cmcmd.cxx 56 KB

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