cmcmd.cxx 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155
  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 <cmext/algorithm>
  5. #include <fcntl.h>
  6. #include "cm_uv.h"
  7. #include "cmAlgorithms.h"
  8. #include "cmDuration.h"
  9. #include "cmGlobalGenerator.h"
  10. #include "cmLocalGenerator.h"
  11. #include "cmMakefile.h"
  12. #include "cmQtAutoMocUic.h"
  13. #include "cmQtAutoRcc.h"
  14. #include "cmRange.h"
  15. #include "cmState.h"
  16. #include "cmStateDirectory.h"
  17. #include "cmStateSnapshot.h"
  18. #include "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. #include "cmUVProcessChain.h"
  21. #include "cmUtils.hxx"
  22. #include "cmVersion.h"
  23. #include "cmake.h"
  24. #if !defined(CMAKE_BOOTSTRAP)
  25. # include "cmDependsFortran.h" // For -E cmake_copy_f90_mod callback.
  26. # include "cmFileTime.h"
  27. # include "cmServer.h"
  28. # include "cmServerConnection.h"
  29. # include "bindexplib.h"
  30. #endif
  31. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32)
  32. # include "cmsys/ConsoleBuf.hxx"
  33. #endif
  34. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  35. # include "cmVisualStudioWCEPlatformParser.h"
  36. #endif
  37. #include <array>
  38. #include <cstdio>
  39. #include <cstdlib>
  40. #include <cstring>
  41. #include <ctime>
  42. #include <iostream>
  43. #include <memory>
  44. #include <sstream>
  45. #include <utility>
  46. #include <cm/string_view>
  47. #include "cmsys/Directory.hxx"
  48. #include "cmsys/FStream.hxx"
  49. #include "cmsys/Process.h"
  50. #include "cmsys/Terminal.h"
  51. class cmConnection;
  52. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  53. std::vector<std::string>::const_iterator argEnd);
  54. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  55. std::vector<std::string>::const_iterator argEnd);
  56. void CMakeCommandUsage(const char* program)
  57. {
  58. std::ostringstream errorStream;
  59. #ifndef CMAKE_BOOTSTRAP
  60. /* clang-format off */
  61. errorStream
  62. << "cmake version " << cmVersion::GetCMakeVersion() << "\n";
  63. /* clang-format on */
  64. #else
  65. /* clang-format off */
  66. errorStream
  67. << "cmake bootstrap\n";
  68. /* clang-format on */
  69. #endif
  70. // If you add new commands, change here,
  71. // and in cmakemain.cxx in the options table
  72. /* clang-format off */
  73. errorStream
  74. << "Usage: " << program << " -E <command> [arguments...]\n"
  75. << "Available commands: \n"
  76. << " capabilities - Report capabilities built into cmake "
  77. "in JSON format\n"
  78. << " chdir dir cmd [args...] - run command in a given directory\n"
  79. << " compare_files [--ignore-eol] file1 file2\n"
  80. << " - check if file1 is same as file2\n"
  81. << " copy <file>... destination - copy files to destination "
  82. "(either file or directory)\n"
  83. << " copy_directory <dir>... destination - copy content of <dir>... "
  84. "directories to 'destination' directory\n"
  85. << " copy_if_different <file>... destination - copy files if it has "
  86. "changed\n"
  87. << " echo [<string>...] - displays arguments as text\n"
  88. << " echo_append [<string>...] - displays arguments as text but no new "
  89. "line\n"
  90. << " env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...\n"
  91. << " - run command in a modified environment\n"
  92. << " environment - display the current environment\n"
  93. << " make_directory <dir>... - create parent and <dir> directories\n"
  94. << " md5sum <file>... - create MD5 checksum of files\n"
  95. << " sha1sum <file>... - create SHA1 checksum of files\n"
  96. << " sha224sum <file>... - create SHA224 checksum of files\n"
  97. << " sha256sum <file>... - create SHA256 checksum of files\n"
  98. << " sha384sum <file>... - create SHA384 checksum of files\n"
  99. << " sha512sum <file>... - create SHA512 checksum of files\n"
  100. << " remove [-f] <file>... - remove the file(s), use -f to force "
  101. "it (deprecated: use rm instead)\n"
  102. << " remove_directory <dir>... - remove directories and their contents (deprecated: use rm instead)\n"
  103. << " rename oldname newname - rename a file or directory "
  104. "(on one volume)\n"
  105. << " rm [-rRf] <file/dir>... - remove files or directories, use -f to "
  106. "force it, r or R to remove directories and their contents recursively\n"
  107. << " server - start cmake in server mode\n"
  108. << " sleep <number>... - sleep for given number of seconds\n"
  109. << " tar [cxt][vf][zjJ] file.tar [file/dir1 file/dir2 ...]\n"
  110. << " - create or extract a tar or zip archive\n"
  111. << " time command [args...] - run command and display elapsed time\n"
  112. << " touch <file>... - touch a <file>.\n"
  113. << " touch_nocreate <file>... - touch a <file> but do not create it.\n"
  114. << " create_symlink old new - create a symbolic link new -> old\n"
  115. << " true - do nothing with an exit code of 0\n"
  116. << " false - do nothing with an exit code of 1\n"
  117. #if defined(_WIN32) && !defined(__CYGWIN__)
  118. << "Available on Windows only:\n"
  119. << " delete_regv key - delete registry value\n"
  120. << " env_vs8_wince sdkname - displays a batch file which sets the "
  121. "environment for the provided Windows CE SDK installed in VS2005\n"
  122. << " env_vs9_wince sdkname - displays a batch file which sets the "
  123. "environment for the provided Windows CE SDK installed in VS2008\n"
  124. << " write_regv key value - write registry value\n"
  125. #endif
  126. ;
  127. /* clang-format on */
  128. cmSystemTools::Error(errorStream.str());
  129. }
  130. static bool cmTarFilesFrom(std::string const& file,
  131. std::vector<std::string>& files)
  132. {
  133. if (cmSystemTools::FileIsDirectory(file)) {
  134. std::ostringstream e;
  135. e << "-E tar --files-from= file '" << file << "' is a directory";
  136. cmSystemTools::Error(e.str());
  137. return false;
  138. }
  139. cmsys::ifstream fin(file.c_str());
  140. if (!fin) {
  141. std::ostringstream e;
  142. e << "-E tar --files-from= file '" << file << "' not found";
  143. cmSystemTools::Error(e.str());
  144. return false;
  145. }
  146. std::string line;
  147. while (cmSystemTools::GetLineFromStream(fin, line)) {
  148. if (line.empty()) {
  149. continue;
  150. }
  151. if (cmHasLiteralPrefix(line, "--add-file=")) {
  152. files.push_back(line.substr(11));
  153. } else if (cmHasLiteralPrefix(line, "-")) {
  154. std::ostringstream e;
  155. e << "-E tar --files-from='" << file << "' file invalid line:\n"
  156. << line << "\n";
  157. cmSystemTools::Error(e.str());
  158. return false;
  159. } else {
  160. files.push_back(line);
  161. }
  162. }
  163. return true;
  164. }
  165. static bool cmRemoveDirectory(const std::string& dir, bool recursive = true)
  166. {
  167. if (cmSystemTools::FileIsSymlink(dir)) {
  168. if (!cmSystemTools::RemoveFile(dir)) {
  169. std::cerr << "Error removing directory symlink \"" << dir << "\".\n";
  170. return false;
  171. }
  172. } else if (!recursive) {
  173. std::cerr << "Error removing directory \"" << dir
  174. << "\" without recursive option.\n";
  175. return false;
  176. } else if (!cmSystemTools::RemoveADirectory(dir)) {
  177. std::cerr << "Error removing directory \"" << dir << "\".\n";
  178. return false;
  179. }
  180. return true;
  181. }
  182. static int HandleIWYU(const std::string& runCmd,
  183. const std::string& /* sourceFile */,
  184. const std::vector<std::string>& orig_cmd)
  185. {
  186. // Construct the iwyu command line by taking what was given
  187. // and adding all the arguments we give to the compiler.
  188. std::vector<std::string> iwyu_cmd = cmExpandedList(runCmd, true);
  189. cm::append(iwyu_cmd, orig_cmd.begin() + 1, orig_cmd.end());
  190. // Run the iwyu command line. Capture its stderr and hide its stdout.
  191. // Ignore its return code because the tool always returns non-zero.
  192. std::string stdErr;
  193. int ret;
  194. if (!cmSystemTools::RunSingleCommand(iwyu_cmd, nullptr, &stdErr, &ret,
  195. nullptr, cmSystemTools::OUTPUT_NONE)) {
  196. std::cerr << "Error running '" << iwyu_cmd[0] << "': " << stdErr << "\n";
  197. return 1;
  198. }
  199. // Warn if iwyu reported anything.
  200. if (stdErr.find("should remove these lines:") != std::string::npos ||
  201. stdErr.find("should add these lines:") != std::string::npos) {
  202. std::cerr << "Warning: include-what-you-use reported diagnostics:\n"
  203. << stdErr << "\n";
  204. }
  205. // always return 0 we don't want to break the compile
  206. return 0;
  207. }
  208. static int HandleTidy(const std::string& runCmd, const std::string& sourceFile,
  209. const std::vector<std::string>& orig_cmd)
  210. {
  211. // Construct the clang-tidy command line by taking what was given
  212. // and adding our compiler command line. The clang-tidy tool will
  213. // automatically skip over the compiler itself and extract the
  214. // options.
  215. int ret;
  216. std::vector<std::string> tidy_cmd = cmExpandedList(runCmd, true);
  217. tidy_cmd.push_back(sourceFile);
  218. tidy_cmd.emplace_back("--");
  219. cm::append(tidy_cmd, orig_cmd);
  220. // Run the tidy command line. Capture its stdout and hide its stderr.
  221. std::string stdOut;
  222. std::string stdErr;
  223. if (!cmSystemTools::RunSingleCommand(tidy_cmd, &stdOut, &stdErr, &ret,
  224. nullptr, cmSystemTools::OUTPUT_NONE)) {
  225. std::cerr << "Error running '" << tidy_cmd[0] << "': " << stdErr << "\n";
  226. return 1;
  227. }
  228. // Output the stdout from clang-tidy to stderr
  229. std::cerr << stdOut;
  230. // If clang-tidy exited with an error do the same.
  231. if (ret != 0) {
  232. std::cerr << stdErr;
  233. }
  234. return ret;
  235. }
  236. static int HandleLWYU(const std::string& runCmd,
  237. const std::string& /* sourceFile */,
  238. const std::vector<std::string>&)
  239. {
  240. // Construct the ldd -r -u (link what you use lwyu) command line
  241. // ldd -u -r lwuy target
  242. std::vector<std::string> lwyu_cmd;
  243. lwyu_cmd.emplace_back("ldd");
  244. lwyu_cmd.emplace_back("-u");
  245. lwyu_cmd.emplace_back("-r");
  246. lwyu_cmd.push_back(runCmd);
  247. // Run the ldd -u -r command line.
  248. // Capture its stdout and hide its stderr.
  249. // Ignore its return code because the tool always returns non-zero
  250. // if there are any warnings, but we just want to warn.
  251. std::string stdOut;
  252. std::string stdErr;
  253. int ret;
  254. if (!cmSystemTools::RunSingleCommand(lwyu_cmd, &stdOut, &stdErr, &ret,
  255. nullptr, cmSystemTools::OUTPUT_NONE)) {
  256. std::cerr << "Error running '" << lwyu_cmd[0] << "': " << stdErr << "\n";
  257. return 1;
  258. }
  259. // Output the stdout from ldd -r -u to stderr
  260. // Warn if lwyu reported anything.
  261. if (stdOut.find("Unused direct dependencies:") != std::string::npos) {
  262. std::cerr << "Warning: " << stdOut;
  263. }
  264. return 0;
  265. }
  266. static int HandleCppLint(const std::string& runCmd,
  267. const std::string& sourceFile,
  268. const std::vector<std::string>&)
  269. {
  270. // Construct the cpplint command line.
  271. std::vector<std::string> cpplint_cmd = cmExpandedList(runCmd, true);
  272. cpplint_cmd.push_back(sourceFile);
  273. // Run the cpplint command line. Capture its output.
  274. std::string stdOut;
  275. int ret;
  276. if (!cmSystemTools::RunSingleCommand(cpplint_cmd, &stdOut, &stdOut, &ret,
  277. nullptr, cmSystemTools::OUTPUT_NONE)) {
  278. std::cerr << "Error running '" << cpplint_cmd[0] << "': " << stdOut
  279. << "\n";
  280. return 1;
  281. }
  282. if (!stdOut.empty()) {
  283. std::cerr << "Warning: cpplint diagnostics:\n";
  284. // Output the output from cpplint to stderr
  285. std::cerr << stdOut;
  286. }
  287. // always return 0 so the build can continue as cpplint returns non-zero
  288. // for any warning
  289. return 0;
  290. }
  291. static int HandleCppCheck(const std::string& runCmd,
  292. const std::string& sourceFile,
  293. const std::vector<std::string>& orig_cmd)
  294. {
  295. // Construct the cpplint command line.
  296. std::vector<std::string> cppcheck_cmd = cmExpandedList(runCmd, true);
  297. // extract all the -D, -U, and -I options from the compile line
  298. for (auto const& opt : orig_cmd) {
  299. if (opt.size() > 2) {
  300. if ((opt[0] == '-') &&
  301. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  302. cppcheck_cmd.push_back(opt);
  303. // convert cl / options to - options if needed
  304. #if defined(_WIN32)
  305. } else if ((opt[0] == '/') &&
  306. ((opt[1] == 'D') || (opt[1] == 'I') || (opt[1] == 'U'))) {
  307. std::string optcopy = opt;
  308. optcopy[0] = '-';
  309. cppcheck_cmd.push_back(optcopy);
  310. #endif
  311. }
  312. }
  313. }
  314. // add the source file
  315. cppcheck_cmd.push_back(sourceFile);
  316. // Run the cpplint command line. Capture its output.
  317. std::string stdOut;
  318. std::string stdErr;
  319. int ret;
  320. if (!cmSystemTools::RunSingleCommand(cppcheck_cmd, &stdOut, &stdErr, &ret,
  321. nullptr, cmSystemTools::OUTPUT_NONE)) {
  322. std::cerr << "Error running '" << cppcheck_cmd[0] << "': " << stdOut
  323. << "\n";
  324. return 1;
  325. }
  326. std::cerr << stdOut;
  327. // Output the output from cpplint to stderr
  328. if (stdErr.find("(error)") != std::string::npos ||
  329. stdErr.find("(warning)") != std::string::npos ||
  330. stdErr.find("(style)") != std::string::npos ||
  331. stdErr.find("(performance)") != std::string::npos ||
  332. stdErr.find("(portability)") != std::string::npos ||
  333. stdErr.find("(information)") != std::string::npos) {
  334. if (ret == 0) {
  335. std::cerr << "Warning: cppcheck reported diagnostics:\n";
  336. } else {
  337. std::cerr << "Error: cppcheck reported failure:\n";
  338. }
  339. }
  340. std::cerr << stdErr;
  341. return ret;
  342. }
  343. using CoCompileHandler = int (*)(const std::string&, const std::string&,
  344. const std::vector<std::string>&);
  345. struct CoCompiler
  346. {
  347. const char* Option;
  348. CoCompileHandler Handler;
  349. bool NoOriginalCommand;
  350. };
  351. static const std::array<CoCompiler, 5> CoCompilers = {
  352. { // Table of options and handlers.
  353. { "--cppcheck=", HandleCppCheck, false },
  354. { "--cpplint=", HandleCppLint, false },
  355. { "--iwyu=", HandleIWYU, false },
  356. { "--lwyu=", HandleLWYU, true },
  357. { "--tidy=", HandleTidy, false } }
  358. };
  359. struct CoCompileJob
  360. {
  361. std::string Command;
  362. CoCompileHandler Handler;
  363. };
  364. // called when args[0] == "__run_co_compile"
  365. int cmcmd::HandleCoCompileCommands(std::vector<std::string> const& args)
  366. {
  367. std::vector<CoCompileJob> jobs;
  368. std::string sourceFile; // store --source=
  369. std::vector<std::string> launchers; // store --launcher=
  370. // Default is to run the original command found after -- if the option
  371. // does not need to do that, it should be specified here, currently only
  372. // lwyu does that.
  373. bool runOriginalCmd = true;
  374. std::vector<std::string> orig_cmd;
  375. bool doing_options = true;
  376. for (std::string const& arg : cmMakeRange(args).advance(2)) {
  377. // if the arg is -- then the rest of the args after
  378. // go into orig_cmd
  379. if (arg == "--") {
  380. doing_options = false;
  381. } else if (doing_options) {
  382. bool optionFound = false;
  383. for (CoCompiler const& cc : CoCompilers) {
  384. size_t optionLen = strlen(cc.Option);
  385. if (arg.compare(0, optionLen, cc.Option) == 0) {
  386. optionFound = true;
  387. CoCompileJob job;
  388. job.Command = arg.substr(optionLen);
  389. job.Handler = cc.Handler;
  390. jobs.push_back(std::move(job));
  391. if (cc.NoOriginalCommand) {
  392. runOriginalCmd = false;
  393. }
  394. }
  395. }
  396. if (!optionFound) {
  397. if (cmHasLiteralPrefix(arg, "--source=")) {
  398. sourceFile = arg.substr(9);
  399. } else if (cmHasLiteralPrefix(arg, "--launcher=")) {
  400. cmExpandList(arg.substr(11), launchers, true);
  401. } else {
  402. // if it was not a co-compiler or --source/--launcher then error
  403. std::cerr << "__run_co_compile given unknown argument: " << arg
  404. << "\n";
  405. return 1;
  406. }
  407. }
  408. } else { // if not doing_options then push to orig_cmd
  409. orig_cmd.push_back(arg);
  410. }
  411. }
  412. if (jobs.empty()) {
  413. std::cerr << "__run_co_compile missing command to run. "
  414. "Looking for one or more of the following:\n";
  415. for (CoCompiler const& cc : CoCompilers) {
  416. std::cerr << cc.Option << "\n";
  417. }
  418. return 1;
  419. }
  420. if (runOriginalCmd && orig_cmd.empty()) {
  421. std::cerr << "__run_co_compile missing compile command after --\n";
  422. return 1;
  423. }
  424. for (CoCompileJob const& job : jobs) {
  425. // call the command handler here
  426. int ret = job.Handler(job.Command, sourceFile, orig_cmd);
  427. // if the command returns non-zero then return and fail.
  428. // for commands that do not want to break the build, they should return
  429. // 0 no matter what.
  430. if (ret != 0) {
  431. return ret;
  432. }
  433. }
  434. // if there is no original command to run return now
  435. if (!runOriginalCmd) {
  436. return 0;
  437. }
  438. // Prepend launcher argument(s), if any
  439. if (!launchers.empty()) {
  440. orig_cmd.insert(orig_cmd.begin(), launchers.begin(), launchers.end());
  441. }
  442. // Now run the real compiler command and return its result value
  443. int ret;
  444. if (!cmSystemTools::RunSingleCommand(orig_cmd, nullptr, nullptr, &ret,
  445. nullptr,
  446. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  447. std::cerr << "Error running '" << orig_cmd[0] << "'\n";
  448. return 1;
  449. }
  450. // return the return value from the original compiler command
  451. return ret;
  452. }
  453. int cmcmd::ExecuteCMakeCommand(std::vector<std::string> const& args)
  454. {
  455. // IF YOU ADD A NEW COMMAND, DOCUMENT IT ABOVE and in cmakemain.cxx
  456. if (args.size() > 1) {
  457. // Copy file
  458. if (args[1] == "copy" && args.size() > 3) {
  459. // If multiple source files specified,
  460. // then destination must be directory
  461. if ((args.size() > 4) &&
  462. (!cmSystemTools::FileIsDirectory(args.back()))) {
  463. std::cerr << "Error: Target (for copy command) \"" << args.back()
  464. << "\" is not a directory.\n";
  465. return 1;
  466. }
  467. // If error occurs we want to continue copying next files.
  468. bool return_value = false;
  469. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  470. if (!cmsys::SystemTools::CopyFileAlways(arg, args.back())) {
  471. std::cerr << "Error copying file \"" << arg << "\" to \""
  472. << args.back() << "\".\n";
  473. return_value = true;
  474. }
  475. }
  476. return return_value;
  477. }
  478. // Copy file if different.
  479. if (args[1] == "copy_if_different" && args.size() > 3) {
  480. // If multiple source files specified,
  481. // then destination must be directory
  482. if ((args.size() > 4) &&
  483. (!cmSystemTools::FileIsDirectory(args.back()))) {
  484. std::cerr << "Error: Target (for copy_if_different command) \""
  485. << args.back() << "\" is not a directory.\n";
  486. return 1;
  487. }
  488. // If error occurs we want to continue copying next files.
  489. bool return_value = false;
  490. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  491. if (!cmSystemTools::CopyFileIfDifferent(arg, args.back())) {
  492. std::cerr << "Error copying file (if different) from \"" << arg
  493. << "\" to \"" << args.back() << "\".\n";
  494. return_value = true;
  495. }
  496. }
  497. return return_value;
  498. }
  499. // Copy directory content
  500. if (args[1] == "copy_directory" && args.size() > 3) {
  501. // If error occurs we want to continue copying next files.
  502. bool return_value = false;
  503. for (auto const& arg : cmMakeRange(args).advance(2).retreat(1)) {
  504. if (!cmSystemTools::CopyADirectory(arg, args.back())) {
  505. std::cerr << "Error copying directory from \"" << arg << "\" to \""
  506. << args.back() << "\".\n";
  507. return_value = true;
  508. }
  509. }
  510. return return_value;
  511. }
  512. // Rename a file or directory
  513. if (args[1] == "rename" && args.size() == 4) {
  514. if (!cmSystemTools::RenameFile(args[2], args[3])) {
  515. std::string e = cmSystemTools::GetLastSystemError();
  516. std::cerr << "Error renaming from \"" << args[2] << "\" to \""
  517. << args[3] << "\": " << e << "\n";
  518. return 1;
  519. }
  520. return 0;
  521. }
  522. // Compare files
  523. if (args[1] == "compare_files" && (args.size() == 4 || args.size() == 5)) {
  524. bool filesDiffer;
  525. if (args.size() == 4) {
  526. filesDiffer = cmSystemTools::FilesDiffer(args[2], args[3]);
  527. } else if (args[2] == "--ignore-eol") {
  528. filesDiffer = cmsys::SystemTools::TextFilesDiffer(args[3], args[4]);
  529. } else {
  530. ::CMakeCommandUsage(args[0].c_str());
  531. return 1;
  532. }
  533. if (filesDiffer) {
  534. std::cerr << "Files \"" << args[args.size() - 2] << "\" to \""
  535. << args[args.size() - 1] << "\" are different.\n";
  536. return 1;
  537. }
  538. return 0;
  539. }
  540. #if !defined(CMAKE_BOOTSTRAP)
  541. if (args[1] == "__create_def") {
  542. if (args.size() < 4) {
  543. std::cerr << "__create_def Usage: -E __create_def outfile.def "
  544. "objlistfile [--nm=nm-path]\n";
  545. return 1;
  546. }
  547. cmsys::ifstream fin(args[3].c_str(), std::ios::in | std::ios::binary);
  548. if (!fin) {
  549. std::cerr << "could not open object list file: " << args[3].c_str()
  550. << "\n";
  551. return 1;
  552. }
  553. std::vector<std::string> files;
  554. {
  555. std::string file;
  556. cmFileTime outTime;
  557. bool outValid = outTime.Load(args[2]);
  558. while (cmSystemTools::GetLineFromStream(fin, file)) {
  559. files.push_back(file);
  560. if (outValid) {
  561. cmFileTime inTime;
  562. outValid = inTime.Load(file) && inTime.Older(outTime);
  563. }
  564. }
  565. if (outValid) {
  566. // The def file already exists and all input files are older than the
  567. // existing def file.
  568. return 0;
  569. }
  570. }
  571. FILE* fout = cmsys::SystemTools::Fopen(args[2], "w+");
  572. if (!fout) {
  573. std::cerr << "could not open output .def file: " << args[2].c_str()
  574. << "\n";
  575. return 1;
  576. }
  577. bindexplib deffile;
  578. if (args.size() >= 5) {
  579. auto a = args[4];
  580. if (cmHasLiteralPrefix(a, "--nm=")) {
  581. deffile.SetNmPath(a.substr(5));
  582. std::cerr << a.substr(5) << "\n";
  583. } else {
  584. std::cerr << "unknown argument: " << a << "\n";
  585. }
  586. }
  587. for (auto const& file : files) {
  588. std::string const& ext = cmSystemTools::GetFilenameLastExtension(file);
  589. if (cmSystemTools::LowerCase(ext) == ".def") {
  590. if (!deffile.AddDefinitionFile(file.c_str())) {
  591. return 1;
  592. }
  593. } else {
  594. if (!deffile.AddObjectFile(file.c_str())) {
  595. return 1;
  596. }
  597. }
  598. }
  599. deffile.WriteFile(fout);
  600. fclose(fout);
  601. return 0;
  602. }
  603. #endif
  604. if (args[1] == "__run_co_compile") {
  605. return cmcmd::HandleCoCompileCommands(args);
  606. }
  607. // Echo string
  608. if (args[1] == "echo") {
  609. std::cout << cmJoin(cmMakeRange(args).advance(2), " ") << std::endl;
  610. return 0;
  611. }
  612. // Echo string no new line
  613. if (args[1] == "echo_append") {
  614. std::cout << cmJoin(cmMakeRange(args).advance(2), " ");
  615. return 0;
  616. }
  617. if (args[1] == "env") {
  618. auto ai = args.cbegin() + 2;
  619. auto ae = args.cend();
  620. for (; ai != ae; ++ai) {
  621. std::string const& a = *ai;
  622. if (cmHasLiteralPrefix(a, "--unset=")) {
  623. // Unset environment variable.
  624. cmSystemTools::UnPutEnv(a.substr(8));
  625. } else if (!a.empty() && a[0] == '-') {
  626. // Environment variable and command names cannot start in '-',
  627. // so this must be an unknown option.
  628. std::cerr << "cmake -E env: unknown option '" << a << "'"
  629. << std::endl;
  630. return 1;
  631. } else if (a.find('=') != std::string::npos) {
  632. // Set environment variable.
  633. cmSystemTools::PutEnv(a);
  634. } else {
  635. // This is the beginning of the command.
  636. break;
  637. }
  638. }
  639. if (ai == ae) {
  640. std::cerr << "cmake -E env: no command given" << std::endl;
  641. return 1;
  642. }
  643. // Execute command from remaining arguments.
  644. std::vector<std::string> cmd(ai, ae);
  645. int retval;
  646. if (cmSystemTools::RunSingleCommand(cmd, nullptr, nullptr, &retval,
  647. nullptr,
  648. cmSystemTools::OUTPUT_PASSTHROUGH)) {
  649. return retval;
  650. }
  651. return 1;
  652. }
  653. #if !defined(CMAKE_BOOTSTRAP)
  654. if (args[1] == "environment") {
  655. for (auto const& env : cmSystemTools::GetEnvironmentVariables()) {
  656. std::cout << env << std::endl;
  657. }
  658. return 0;
  659. }
  660. #endif
  661. if (args[1] == "make_directory" && args.size() > 2) {
  662. // If an error occurs, we want to continue making directories.
  663. bool return_value = false;
  664. for (auto const& arg : cmMakeRange(args).advance(2)) {
  665. if (!cmSystemTools::MakeDirectory(arg)) {
  666. std::cerr << "Error creating directory \"" << arg << "\".\n";
  667. return_value = true;
  668. }
  669. }
  670. return return_value;
  671. }
  672. if (args[1] == "remove_directory" && args.size() > 2) {
  673. // If an error occurs, we want to continue removing directories.
  674. bool return_value = false;
  675. for (auto const& arg : cmMakeRange(args).advance(2)) {
  676. if (cmSystemTools::FileIsDirectory(arg)) {
  677. if (!cmRemoveDirectory(arg)) {
  678. return_value = true;
  679. }
  680. }
  681. }
  682. return return_value;
  683. }
  684. // Remove file
  685. if (args[1] == "remove" && args.size() > 2) {
  686. bool force = false;
  687. for (auto const& arg : cmMakeRange(args).advance(2)) {
  688. if (arg == "\\-f" || arg == "-f") {
  689. force = true;
  690. } else {
  691. // Complain if the file could not be removed, still exists,
  692. // and the -f option was not given.
  693. if (!cmSystemTools::RemoveFile(arg) && !force &&
  694. cmSystemTools::FileExists(arg)) {
  695. return 1;
  696. }
  697. }
  698. }
  699. return 0;
  700. }
  701. // Remove directories or files with rm
  702. if (args[1] == "rm" && args.size() > 2) {
  703. // If an error occurs, we want to continue removing the remaining
  704. // files/directories.
  705. int return_value = 0;
  706. bool force = false;
  707. bool recursive = false;
  708. bool doing_options = true;
  709. bool at_least_one_file = false;
  710. for (auto const& arg : cmMakeRange(args).advance(2)) {
  711. if (doing_options && cmHasLiteralPrefix(arg, "-")) {
  712. if (arg == "--") {
  713. doing_options = false;
  714. }
  715. if (arg.find('f') != std::string::npos) {
  716. force = true;
  717. }
  718. if (arg.find_first_of("rR") != std::string::npos) {
  719. recursive = true;
  720. }
  721. if (arg.find_first_not_of("-frR") != std::string::npos) {
  722. cmSystemTools::Error("Unknown -E rm argument: " + arg);
  723. return 1;
  724. }
  725. } else {
  726. if (arg.empty()) {
  727. continue;
  728. }
  729. at_least_one_file = true;
  730. // Complain if the -f option was not given and
  731. // either file does not exist or
  732. // file could not be removed and still exists
  733. bool file_exists_or_forced_remove = cmSystemTools::FileExists(arg) ||
  734. cmSystemTools::FileIsSymlink(arg) || force;
  735. if (cmSystemTools::FileIsDirectory(arg)) {
  736. if (!cmRemoveDirectory(arg, recursive)) {
  737. return_value = 1;
  738. }
  739. } else if ((!file_exists_or_forced_remove) ||
  740. (!cmSystemTools::RemoveFile(arg) &&
  741. cmSystemTools::FileExists(arg))) {
  742. if (!file_exists_or_forced_remove) {
  743. cmSystemTools::Error(
  744. "File to remove does not exist and force is not set: " + arg);
  745. } else {
  746. cmSystemTools::Error("File can't be removed and still exist: " +
  747. arg);
  748. }
  749. return_value = 1;
  750. }
  751. }
  752. }
  753. if (!at_least_one_file) {
  754. cmSystemTools::Error("Missing file/directory to remove");
  755. return 1;
  756. }
  757. return return_value;
  758. }
  759. // Touch file
  760. if (args[1] == "touch" && args.size() > 2) {
  761. for (auto const& arg : cmMakeRange(args).advance(2)) {
  762. if (!cmSystemTools::Touch(arg, true)) {
  763. std::cerr << "cmake -E touch: failed to update \"";
  764. std::cerr << arg << "\".\n";
  765. return 1;
  766. }
  767. }
  768. return 0;
  769. }
  770. // Touch file
  771. if (args[1] == "touch_nocreate" && args.size() > 2) {
  772. for (auto const& arg : cmMakeRange(args).advance(2)) {
  773. if (!cmSystemTools::Touch(arg, false)) {
  774. std::cerr << "cmake -E touch_nocreate: failed to update \"";
  775. std::cerr << arg << "\".\n";
  776. return 1;
  777. }
  778. }
  779. return 0;
  780. }
  781. // capabilities
  782. if (args[1] == "capabilities") {
  783. if (args.size() > 2) {
  784. std::cerr << "-E capabilities accepts no additional arguments\n";
  785. return 1;
  786. }
  787. cmake cm(cmake::RoleInternal, cmState::Unknown);
  788. std::cout << cm.ReportCapabilities();
  789. return 0;
  790. }
  791. // Sleep command
  792. if (args[1] == "sleep" && args.size() > 2) {
  793. double total = 0;
  794. for (auto const& arg : cmMakeRange(args).advance(2)) {
  795. double num = 0.0;
  796. char unit;
  797. char extra;
  798. int n = sscanf(arg.c_str(), "%lg%c%c", &num, &unit, &extra);
  799. if ((n == 1 || (n == 2 && unit == 's')) && num >= 0) {
  800. total += num;
  801. } else {
  802. std::cerr << "Unknown sleep time format \"" << arg << "\".\n";
  803. return 1;
  804. }
  805. }
  806. if (total > 0) {
  807. cmSystemTools::Delay(static_cast<unsigned int>(total * 1000));
  808. }
  809. return 0;
  810. }
  811. // Clock command
  812. if (args[1] == "time" && args.size() > 2) {
  813. std::vector<std::string> command(args.begin() + 2, args.end());
  814. clock_t clock_start;
  815. clock_t clock_finish;
  816. time_t time_start;
  817. time_t time_finish;
  818. time(&time_start);
  819. clock_start = clock();
  820. int ret = 0;
  821. cmSystemTools::RunSingleCommand(command, nullptr, nullptr, &ret);
  822. clock_finish = clock();
  823. time(&time_finish);
  824. double clocks_per_sec = static_cast<double>(CLOCKS_PER_SEC);
  825. std::cout << "Elapsed time: "
  826. << static_cast<long>(time_finish - time_start) << " s. (time)"
  827. << ", "
  828. << static_cast<double>(clock_finish - clock_start) /
  829. clocks_per_sec
  830. << " s. (clock)"
  831. << "\n";
  832. return ret;
  833. }
  834. // Command to calculate the md5sum of a file
  835. if (args[1] == "md5sum" && args.size() >= 3) {
  836. return HashSumFile(args, cmCryptoHash::AlgoMD5);
  837. }
  838. // Command to calculate the sha1sum of a file
  839. if (args[1] == "sha1sum" && args.size() >= 3) {
  840. return HashSumFile(args, cmCryptoHash::AlgoSHA1);
  841. }
  842. if (args[1] == "sha224sum" && args.size() >= 3) {
  843. return HashSumFile(args, cmCryptoHash::AlgoSHA224);
  844. }
  845. if (args[1] == "sha256sum" && args.size() >= 3) {
  846. return HashSumFile(args, cmCryptoHash::AlgoSHA256);
  847. }
  848. if (args[1] == "sha384sum" && args.size() >= 3) {
  849. return HashSumFile(args, cmCryptoHash::AlgoSHA384);
  850. }
  851. if (args[1] == "sha512sum" && args.size() >= 3) {
  852. return HashSumFile(args, cmCryptoHash::AlgoSHA512);
  853. }
  854. // Command to change directory and run a program.
  855. if (args[1] == "chdir" && args.size() >= 4) {
  856. std::string const& directory = args[2];
  857. if (!cmSystemTools::FileExists(directory)) {
  858. cmSystemTools::Error("Directory does not exist for chdir command: " +
  859. args[2]);
  860. return 1;
  861. }
  862. std::string command =
  863. cmWrap('"', cmMakeRange(args).advance(3), '"', " ");
  864. int retval = 0;
  865. if (cmSystemTools::RunSingleCommand(
  866. command, nullptr, nullptr, &retval, directory.c_str(),
  867. cmSystemTools::OUTPUT_PASSTHROUGH, cmDuration::zero())) {
  868. return retval;
  869. }
  870. return 1;
  871. }
  872. // Command to start progress for a build
  873. if (args[1] == "cmake_progress_start" && args.size() == 4) {
  874. // basically remove the directory
  875. std::string dirName = cmStrCat(args[2], "/Progress");
  876. cmSystemTools::RemoveADirectory(dirName);
  877. // is the last argument a filename that exists?
  878. FILE* countFile = cmsys::SystemTools::Fopen(args[3], "r");
  879. int count;
  880. if (countFile) {
  881. if (1 != fscanf(countFile, "%i", &count)) {
  882. cmSystemTools::Message("Could not read from count file.");
  883. }
  884. fclose(countFile);
  885. } else {
  886. count = atoi(args[3].c_str());
  887. }
  888. if (count) {
  889. cmSystemTools::MakeDirectory(dirName);
  890. // write the count into the directory
  891. std::string fName = cmStrCat(dirName, "/count.txt");
  892. FILE* progFile = cmsys::SystemTools::Fopen(fName, "w");
  893. if (progFile) {
  894. fprintf(progFile, "%i\n", count);
  895. fclose(progFile);
  896. }
  897. }
  898. return 0;
  899. }
  900. // Command to report progress for a build
  901. if (args[1] == "cmake_progress_report" && args.size() >= 3) {
  902. // This has been superseded by cmake_echo_color --progress-*
  903. // options. We leave it here to avoid errors if somehow this
  904. // is invoked by an existing makefile without regenerating.
  905. return 0;
  906. }
  907. // Command to create a symbolic link. Fails on platforms not
  908. // supporting them.
  909. if (args[1] == "create_symlink" && args.size() == 4) {
  910. const char* destinationFileName = args[3].c_str();
  911. if ((cmSystemTools::FileExists(destinationFileName) ||
  912. cmSystemTools::FileIsSymlink(destinationFileName)) &&
  913. !cmSystemTools::RemoveFile(destinationFileName)) {
  914. std::string emsg = cmSystemTools::GetLastSystemError();
  915. std::cerr << "failed to create symbolic link '" << destinationFileName
  916. << "' because existing path cannot be removed: " << emsg
  917. << "\n";
  918. return 1;
  919. }
  920. if (!cmSystemTools::CreateSymlink(args[2], args[3])) {
  921. return 1;
  922. }
  923. return 0;
  924. }
  925. // Command to do nothing with an exit code of 0.
  926. if (args[1] == "true") {
  927. return 0;
  928. }
  929. // Command to do nothing with an exit code of 1.
  930. if (args[1] == "false") {
  931. return 1;
  932. }
  933. // Internal CMake shared library support.
  934. if (args[1] == "cmake_symlink_library" && args.size() == 5) {
  935. return cmcmd::SymlinkLibrary(args);
  936. }
  937. // Internal CMake versioned executable support.
  938. if (args[1] == "cmake_symlink_executable" && args.size() == 4) {
  939. return cmcmd::SymlinkExecutable(args);
  940. }
  941. // Internal CMake dependency scanning support.
  942. if (args[1] == "cmake_depends" && args.size() >= 6) {
  943. const bool verbose = isCMakeVerbose();
  944. // Create a cmake object instance to process dependencies.
  945. // All we need is the `set` command.
  946. cmake cm(cmake::RoleScript, cmState::Unknown);
  947. std::string gen;
  948. std::string homeDir;
  949. std::string startDir;
  950. std::string homeOutDir;
  951. std::string startOutDir;
  952. std::string depInfo;
  953. bool color = false;
  954. if (args.size() >= 8) {
  955. // Full signature:
  956. //
  957. // -E cmake_depends <generator>
  958. // <home-src-dir> <start-src-dir>
  959. // <home-out-dir> <start-out-dir>
  960. // <dep-info> [--color=$(COLOR)]
  961. //
  962. // All paths are provided.
  963. gen = args[2];
  964. homeDir = args[3];
  965. startDir = args[4];
  966. homeOutDir = args[5];
  967. startOutDir = args[6];
  968. depInfo = args[7];
  969. if (args.size() >= 9 && cmHasLiteralPrefix(args[8], "--color=")) {
  970. // Enable or disable color based on the switch value.
  971. color = (args[8].size() == 8 || cmIsOn(args[8].substr(8)));
  972. }
  973. } else {
  974. // Support older signature for existing makefiles:
  975. //
  976. // -E cmake_depends <generator>
  977. // <home-out-dir> <start-out-dir>
  978. // <dep-info>
  979. //
  980. // Just pretend the source directories are the same as the
  981. // binary directories so at least scanning will work.
  982. gen = args[2];
  983. homeDir = args[3];
  984. startDir = args[4];
  985. homeOutDir = args[3];
  986. startOutDir = args[3];
  987. depInfo = args[5];
  988. }
  989. // Create a local generator configured for the directory in
  990. // which dependencies will be scanned.
  991. homeDir = cmSystemTools::CollapseFullPath(homeDir);
  992. startDir = cmSystemTools::CollapseFullPath(startDir);
  993. homeOutDir = cmSystemTools::CollapseFullPath(homeOutDir);
  994. startOutDir = cmSystemTools::CollapseFullPath(startOutDir);
  995. cm.SetHomeDirectory(homeDir);
  996. cm.SetHomeOutputDirectory(homeOutDir);
  997. cm.GetCurrentSnapshot().SetDefaultDefinitions();
  998. if (auto ggd = cm.CreateGlobalGenerator(gen)) {
  999. cm.SetGlobalGenerator(std::move(ggd));
  1000. cmStateSnapshot snapshot = cm.GetCurrentSnapshot();
  1001. snapshot.GetDirectory().SetCurrentBinary(startOutDir);
  1002. snapshot.GetDirectory().SetCurrentSource(startDir);
  1003. cmMakefile mf(cm.GetGlobalGenerator(), snapshot);
  1004. auto lgd = cm.GetGlobalGenerator()->CreateLocalGenerator(&mf);
  1005. // Actually scan dependencies.
  1006. return lgd->UpdateDependencies(depInfo, verbose, color) ? 0 : 2;
  1007. }
  1008. return 1;
  1009. }
  1010. // Internal CMake link script support.
  1011. if (args[1] == "cmake_link_script" && args.size() >= 3) {
  1012. return cmcmd::ExecuteLinkScript(args);
  1013. }
  1014. #ifndef CMAKE_BOOTSTRAP
  1015. // Internal CMake ninja dependency scanning support.
  1016. if (args[1] == "cmake_ninja_depends") {
  1017. return cmcmd_cmake_ninja_depends(args.begin() + 2, args.end());
  1018. }
  1019. // Internal CMake ninja dyndep support.
  1020. if (args[1] == "cmake_ninja_dyndep") {
  1021. return cmcmd_cmake_ninja_dyndep(args.begin() + 2, args.end());
  1022. }
  1023. #endif
  1024. // Internal CMake unimplemented feature notification.
  1025. if (args[1] == "cmake_unimplemented_variable") {
  1026. std::cerr << "Feature not implemented for this platform.";
  1027. if (args.size() == 3) {
  1028. std::cerr << " Variable " << args[2] << " is not set.";
  1029. }
  1030. std::cerr << std::endl;
  1031. return 1;
  1032. }
  1033. if (args[1] == "vs_link_exe") {
  1034. return cmcmd::VisualStudioLink(args, 1);
  1035. }
  1036. if (args[1] == "vs_link_dll") {
  1037. return cmcmd::VisualStudioLink(args, 2);
  1038. }
  1039. if (args[1] == "cmake_llvm_rc") {
  1040. return cmcmd::RunLLVMRC(args);
  1041. }
  1042. // Internal CMake color makefile support.
  1043. if (args[1] == "cmake_echo_color") {
  1044. return cmcmd::ExecuteEchoColor(args);
  1045. }
  1046. #ifndef CMAKE_BOOTSTRAP
  1047. if ((args[1] == "cmake_autogen") && (args.size() >= 4)) {
  1048. cm::string_view const infoFile = args[2];
  1049. cm::string_view const config = args[3];
  1050. return cmQtAutoMocUic(infoFile, config) ? 0 : 1;
  1051. }
  1052. if ((args[1] == "cmake_autorcc") && (args.size() >= 3)) {
  1053. cm::string_view const infoFile = args[2];
  1054. cm::string_view const config =
  1055. (args.size() > 3) ? cm::string_view(args[3]) : cm::string_view();
  1056. return cmQtAutoRcc(infoFile, config) ? 0 : 1;
  1057. }
  1058. #endif
  1059. // Tar files
  1060. if (args[1] == "tar" && args.size() > 3) {
  1061. const char* knownFormats[] = { "7zip", "gnutar", "pax", "paxr", "zip" };
  1062. std::string const& flags = args[2];
  1063. std::string const& outFile = args[3];
  1064. std::vector<std::string> files;
  1065. std::string mtime;
  1066. std::string format;
  1067. cmSystemTools::cmTarCompression compress =
  1068. cmSystemTools::TarCompressNone;
  1069. int nCompress = 0;
  1070. bool doing_options = true;
  1071. for (auto const& arg : cmMakeRange(args).advance(4)) {
  1072. if (doing_options && cmHasLiteralPrefix(arg, "--")) {
  1073. if (arg == "--") {
  1074. doing_options = false;
  1075. } else if (arg == "--zstd") {
  1076. compress = cmSystemTools::TarCompressZstd;
  1077. ++nCompress;
  1078. } else if (cmHasLiteralPrefix(arg, "--mtime=")) {
  1079. mtime = arg.substr(8);
  1080. } else if (cmHasLiteralPrefix(arg, "--files-from=")) {
  1081. std::string const& files_from = arg.substr(13);
  1082. if (!cmTarFilesFrom(files_from, files)) {
  1083. return 1;
  1084. }
  1085. } else if (cmHasLiteralPrefix(arg, "--format=")) {
  1086. format = arg.substr(9);
  1087. if (!cmContains(knownFormats, format)) {
  1088. cmSystemTools::Error("Unknown -E tar --format= argument: " +
  1089. format);
  1090. return 1;
  1091. }
  1092. } else {
  1093. cmSystemTools::Error("Unknown option to -E tar: " + arg);
  1094. return 1;
  1095. }
  1096. } else {
  1097. files.push_back(arg);
  1098. }
  1099. }
  1100. cmSystemTools::cmTarAction action = cmSystemTools::TarActionNone;
  1101. bool verbose = false;
  1102. for (auto flag : flags) {
  1103. switch (flag) {
  1104. case '-':
  1105. case 'f': {
  1106. // Keep for backward compatibility. Ignored
  1107. } break;
  1108. case 'j': {
  1109. compress = cmSystemTools::TarCompressBZip2;
  1110. ++nCompress;
  1111. } break;
  1112. case 'J': {
  1113. compress = cmSystemTools::TarCompressXZ;
  1114. ++nCompress;
  1115. } break;
  1116. case 'z': {
  1117. compress = cmSystemTools::TarCompressGZip;
  1118. ++nCompress;
  1119. } break;
  1120. case 'v': {
  1121. verbose = true;
  1122. } break;
  1123. case 't': {
  1124. action = cmSystemTools::TarActionList;
  1125. } break;
  1126. case 'c': {
  1127. action = cmSystemTools::TarActionCreate;
  1128. } break;
  1129. case 'x': {
  1130. action = cmSystemTools::TarActionExtract;
  1131. } break;
  1132. default: {
  1133. cmSystemTools::Message(
  1134. std::string("tar: Unknown argument: ") + flag, "Warning");
  1135. }
  1136. }
  1137. }
  1138. if ((format == "7zip" || format == "zip") && nCompress > 0) {
  1139. cmSystemTools::Error("Can not use compression flags with format: " +
  1140. format);
  1141. return 1;
  1142. }
  1143. if (nCompress > 1) {
  1144. cmSystemTools::Error("Can only compress a tar file one way; "
  1145. "at most one flag of z, j, or J may be used");
  1146. return 1;
  1147. }
  1148. if (action == cmSystemTools::TarActionList) {
  1149. if (!cmSystemTools::ListTar(outFile, files, verbose)) {
  1150. cmSystemTools::Error("Problem listing tar: " + outFile);
  1151. return 1;
  1152. }
  1153. } else if (action == cmSystemTools::TarActionCreate) {
  1154. if (files.empty()) {
  1155. cmSystemTools::Message("tar: No files or directories specified",
  1156. "Warning");
  1157. }
  1158. if (!cmSystemTools::CreateTar(outFile, files, compress, verbose, mtime,
  1159. format)) {
  1160. cmSystemTools::Error("Problem creating tar: " + outFile);
  1161. return 1;
  1162. }
  1163. } else if (action == cmSystemTools::TarActionExtract) {
  1164. if (!cmSystemTools::ExtractTar(outFile, files, verbose)) {
  1165. cmSystemTools::Error("Problem extracting tar: " + outFile);
  1166. return 1;
  1167. }
  1168. #ifdef WIN32
  1169. // OK, on windows 7 after we untar some files,
  1170. // sometimes we can not rename the directory after
  1171. // the untar is done. This breaks the external project
  1172. // untar and rename code. So, by default we will wait
  1173. // 1/10th of a second after the untar. If CMAKE_UNTAR_DELAY
  1174. // is set in the env, its value will be used instead of 100.
  1175. int delay = 100;
  1176. std::string delayVar;
  1177. if (cmSystemTools::GetEnv("CMAKE_UNTAR_DELAY", delayVar)) {
  1178. delay = atoi(delayVar.c_str());
  1179. }
  1180. if (delay) {
  1181. cmSystemTools::Delay(delay);
  1182. }
  1183. #endif
  1184. } else {
  1185. cmSystemTools::Error("tar: No action specified. Please choose: 't' "
  1186. "(list), 'c' (create) or 'x' (extract)");
  1187. return 1;
  1188. }
  1189. return 0;
  1190. }
  1191. if (args[1] == "server") {
  1192. const std::string pipePrefix = "--pipe=";
  1193. bool supportExperimental = false;
  1194. bool isDebug = false;
  1195. std::string pipe;
  1196. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1197. if (arg == "--experimental") {
  1198. supportExperimental = true;
  1199. } else if (arg == "--debug") {
  1200. pipe.clear();
  1201. isDebug = true;
  1202. } else if (cmHasPrefix(arg, pipePrefix)) {
  1203. isDebug = false;
  1204. pipe = arg.substr(pipePrefix.size());
  1205. if (pipe.empty()) {
  1206. cmSystemTools::Error("No pipe given after --pipe=");
  1207. return 2;
  1208. }
  1209. } else {
  1210. cmSystemTools::Error("Unknown argument for server mode");
  1211. return 1;
  1212. }
  1213. }
  1214. #if !defined(CMAKE_BOOTSTRAP)
  1215. cmConnection* conn;
  1216. if (isDebug) {
  1217. conn = new cmServerStdIoConnection;
  1218. } else {
  1219. conn = new cmServerPipeConnection(pipe);
  1220. }
  1221. cmServer server(conn, supportExperimental);
  1222. std::string errorMessage;
  1223. if (server.Serve(&errorMessage)) {
  1224. return 0;
  1225. }
  1226. cmSystemTools::Error(errorMessage);
  1227. #else
  1228. static_cast<void>(supportExperimental);
  1229. static_cast<void>(isDebug);
  1230. cmSystemTools::Error("CMake was not built with server mode enabled");
  1231. #endif
  1232. return 1;
  1233. }
  1234. #if !defined(CMAKE_BOOTSTRAP)
  1235. // Internal CMake Fortran module support.
  1236. if (args[1] == "cmake_copy_f90_mod" && args.size() >= 4) {
  1237. return cmDependsFortran::CopyModule(args) ? 0 : 1;
  1238. }
  1239. #endif
  1240. #if defined(_WIN32) && !defined(__CYGWIN__)
  1241. // Write registry value
  1242. if (args[1] == "write_regv" && args.size() > 3) {
  1243. return cmSystemTools::WriteRegistryValue(args[2].c_str(),
  1244. args[3].c_str())
  1245. ? 0
  1246. : 1;
  1247. }
  1248. // Delete registry value
  1249. if (args[1] == "delete_regv" && args.size() > 2) {
  1250. return cmSystemTools::DeleteRegistryValue(args[2].c_str()) ? 0 : 1;
  1251. }
  1252. // Remove file
  1253. if (args[1] == "comspec" && args.size() > 2) {
  1254. std::cerr << "Win9x helper \"cmake -E comspec\" no longer supported\n";
  1255. return 1;
  1256. }
  1257. if (args[1] == "env_vs8_wince" && args.size() == 3) {
  1258. return cmcmd::WindowsCEEnvironment("8.0", args[2]);
  1259. }
  1260. if (args[1] == "env_vs9_wince" && args.size() == 3) {
  1261. return cmcmd::WindowsCEEnvironment("9.0", args[2]);
  1262. }
  1263. #endif
  1264. }
  1265. ::CMakeCommandUsage(args[0].c_str());
  1266. return 1;
  1267. }
  1268. int cmcmd::HashSumFile(std::vector<std::string> const& args,
  1269. cmCryptoHash::Algo algo)
  1270. {
  1271. if (args.size() < 3) {
  1272. return -1;
  1273. }
  1274. int retval = 0;
  1275. for (auto const& filename : cmMakeRange(args).advance(2)) {
  1276. // Cannot compute sum of a directory
  1277. if (cmSystemTools::FileIsDirectory(filename)) {
  1278. std::cerr << "Error: " << filename << " is a directory" << std::endl;
  1279. retval++;
  1280. } else {
  1281. std::string value = cmSystemTools::ComputeFileHash(filename, algo);
  1282. if (value.empty()) {
  1283. // To mimic "md5sum/shasum" behavior in a shell:
  1284. std::cerr << filename << ": No such file or directory" << std::endl;
  1285. retval++;
  1286. } else {
  1287. std::cout << value << " " << filename << std::endl;
  1288. }
  1289. }
  1290. }
  1291. return retval;
  1292. }
  1293. int cmcmd::SymlinkLibrary(std::vector<std::string> const& args)
  1294. {
  1295. int result = 0;
  1296. std::string realName = args[2];
  1297. std::string soName = args[3];
  1298. std::string name = args[4];
  1299. cmSystemTools::ConvertToUnixSlashes(realName);
  1300. cmSystemTools::ConvertToUnixSlashes(soName);
  1301. cmSystemTools::ConvertToUnixSlashes(name);
  1302. if (soName != realName) {
  1303. if (!cmcmd::SymlinkInternal(realName, soName)) {
  1304. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1305. result = 1;
  1306. }
  1307. }
  1308. if (name != soName) {
  1309. if (!cmcmd::SymlinkInternal(soName, name)) {
  1310. cmSystemTools::ReportLastSystemError("cmake_symlink_library");
  1311. result = 1;
  1312. }
  1313. }
  1314. return result;
  1315. }
  1316. int cmcmd::SymlinkExecutable(std::vector<std::string> const& args)
  1317. {
  1318. int result = 0;
  1319. std::string const& realName = args[2];
  1320. std::string const& name = args[3];
  1321. if (name != realName) {
  1322. if (!cmcmd::SymlinkInternal(realName, name)) {
  1323. cmSystemTools::ReportLastSystemError("cmake_symlink_executable");
  1324. result = 1;
  1325. }
  1326. }
  1327. return result;
  1328. }
  1329. bool cmcmd::SymlinkInternal(std::string const& file, std::string const& link)
  1330. {
  1331. if (cmSystemTools::FileExists(link) || cmSystemTools::FileIsSymlink(link)) {
  1332. cmSystemTools::RemoveFile(link);
  1333. }
  1334. #if defined(_WIN32) && !defined(__CYGWIN__)
  1335. return cmSystemTools::CopyFileAlways(file, link);
  1336. #else
  1337. std::string linktext = cmSystemTools::GetFilenameName(file);
  1338. return cmSystemTools::CreateSymlink(linktext, link);
  1339. #endif
  1340. }
  1341. static void cmcmdProgressReport(std::string const& dir, std::string const& num)
  1342. {
  1343. std::string dirName = cmStrCat(dir, "/Progress");
  1344. std::string fName;
  1345. FILE* progFile;
  1346. // read the count
  1347. fName = cmStrCat(dirName, "/count.txt");
  1348. progFile = cmsys::SystemTools::Fopen(fName, "r");
  1349. int count = 0;
  1350. if (!progFile) {
  1351. return;
  1352. }
  1353. if (1 != fscanf(progFile, "%i", &count)) {
  1354. cmSystemTools::Message("Could not read from progress file.");
  1355. }
  1356. fclose(progFile);
  1357. const char* last = num.c_str();
  1358. for (const char* c = last;; ++c) {
  1359. if (*c == ',' || *c == '\0') {
  1360. if (c != last) {
  1361. fName = cmStrCat(dirName, '/');
  1362. fName.append(last, c - last);
  1363. progFile = cmsys::SystemTools::Fopen(fName, "w");
  1364. if (progFile) {
  1365. fprintf(progFile, "empty");
  1366. fclose(progFile);
  1367. }
  1368. }
  1369. if (*c == '\0') {
  1370. break;
  1371. }
  1372. last = c + 1;
  1373. }
  1374. }
  1375. int fileNum =
  1376. static_cast<int>(cmsys::Directory::GetNumberOfFilesInDirectory(dirName));
  1377. if (count > 0) {
  1378. // print the progress
  1379. fprintf(stdout, "[%3i%%] ", ((fileNum - 3) * 100) / count);
  1380. }
  1381. }
  1382. int cmcmd::ExecuteEchoColor(std::vector<std::string> const& args)
  1383. {
  1384. // The arguments are
  1385. // args[0] == <cmake-executable>
  1386. // args[1] == cmake_echo_color
  1387. bool enabled = true;
  1388. int color = cmsysTerminal_Color_Normal;
  1389. bool newline = true;
  1390. std::string progressDir;
  1391. for (auto const& arg : cmMakeRange(args).advance(2)) {
  1392. if (cmHasLiteralPrefix(arg, "--switch=")) {
  1393. // Enable or disable color based on the switch value.
  1394. std::string value = arg.substr(9);
  1395. if (!value.empty()) {
  1396. enabled = cmIsOn(value);
  1397. }
  1398. } else if (cmHasLiteralPrefix(arg, "--progress-dir=")) {
  1399. progressDir = arg.substr(15);
  1400. } else if (cmHasLiteralPrefix(arg, "--progress-num=")) {
  1401. if (!progressDir.empty()) {
  1402. std::string const& progressNum = arg.substr(15);
  1403. cmcmdProgressReport(progressDir, progressNum);
  1404. }
  1405. } else if (arg == "--normal") {
  1406. color = cmsysTerminal_Color_Normal;
  1407. } else if (arg == "--black") {
  1408. color = cmsysTerminal_Color_ForegroundBlack;
  1409. } else if (arg == "--red") {
  1410. color = cmsysTerminal_Color_ForegroundRed;
  1411. } else if (arg == "--green") {
  1412. color = cmsysTerminal_Color_ForegroundGreen;
  1413. } else if (arg == "--yellow") {
  1414. color = cmsysTerminal_Color_ForegroundYellow;
  1415. } else if (arg == "--blue") {
  1416. color = cmsysTerminal_Color_ForegroundBlue;
  1417. } else if (arg == "--magenta") {
  1418. color = cmsysTerminal_Color_ForegroundMagenta;
  1419. } else if (arg == "--cyan") {
  1420. color = cmsysTerminal_Color_ForegroundCyan;
  1421. } else if (arg == "--white") {
  1422. color = cmsysTerminal_Color_ForegroundWhite;
  1423. } else if (arg == "--bold") {
  1424. color |= cmsysTerminal_Color_ForegroundBold;
  1425. } else if (arg == "--no-newline") {
  1426. newline = false;
  1427. } else if (arg == "--newline") {
  1428. newline = true;
  1429. } else {
  1430. // Color is enabled. Print with the current color.
  1431. cmSystemTools::MakefileColorEcho(color, arg.c_str(), newline, enabled);
  1432. }
  1433. }
  1434. return 0;
  1435. }
  1436. int cmcmd::ExecuteLinkScript(std::vector<std::string> const& args)
  1437. {
  1438. // The arguments are
  1439. // args[0] == <cmake-executable>
  1440. // args[1] == cmake_link_script
  1441. // args[2] == <link-script-name>
  1442. // args[3] == --verbose=?
  1443. bool verbose = false;
  1444. if (args.size() >= 4) {
  1445. if (cmHasLiteralPrefix(args[3], "--verbose=")) {
  1446. if (!cmIsOff(args[3].substr(10))) {
  1447. verbose = true;
  1448. }
  1449. }
  1450. }
  1451. // Allocate a process instance.
  1452. cmsysProcess* cp = cmsysProcess_New();
  1453. if (!cp) {
  1454. std::cerr << "Error allocating process instance in link script."
  1455. << std::endl;
  1456. return 1;
  1457. }
  1458. // Children should share stdout and stderr with this process.
  1459. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDOUT, 1);
  1460. cmsysProcess_SetPipeShared(cp, cmsysProcess_Pipe_STDERR, 1);
  1461. // Run the command lines verbatim.
  1462. cmsysProcess_SetOption(cp, cmsysProcess_Option_Verbatim, 1);
  1463. // Read command lines from the script.
  1464. cmsys::ifstream fin(args[2].c_str());
  1465. if (!fin) {
  1466. std::cerr << "Error opening link script \"" << args[2] << "\""
  1467. << std::endl;
  1468. return 1;
  1469. }
  1470. // Run one command at a time.
  1471. std::string command;
  1472. int result = 0;
  1473. while (result == 0 && cmSystemTools::GetLineFromStream(fin, command)) {
  1474. // Skip empty command lines.
  1475. if (command.find_first_not_of(" \t") == std::string::npos) {
  1476. continue;
  1477. }
  1478. // Setup this command line.
  1479. const char* cmd[2] = { command.c_str(), nullptr };
  1480. cmsysProcess_SetCommand(cp, cmd);
  1481. // Report the command if verbose output is enabled.
  1482. if (verbose) {
  1483. std::cout << command << std::endl;
  1484. }
  1485. // Run the command and wait for it to exit.
  1486. cmsysProcess_Execute(cp);
  1487. cmsysProcess_WaitForExit(cp, nullptr);
  1488. // Report failure if any.
  1489. switch (cmsysProcess_GetState(cp)) {
  1490. case cmsysProcess_State_Exited: {
  1491. int value = cmsysProcess_GetExitValue(cp);
  1492. if (value != 0) {
  1493. result = value;
  1494. }
  1495. } break;
  1496. case cmsysProcess_State_Exception:
  1497. std::cerr << "Error running link command: "
  1498. << cmsysProcess_GetExceptionString(cp) << std::endl;
  1499. result = 1;
  1500. break;
  1501. case cmsysProcess_State_Error:
  1502. std::cerr << "Error running link command: "
  1503. << cmsysProcess_GetErrorString(cp) << std::endl;
  1504. result = 2;
  1505. break;
  1506. default:
  1507. break;
  1508. }
  1509. }
  1510. // Free the process instance.
  1511. cmsysProcess_Delete(cp);
  1512. // Return the final resulting return value.
  1513. return result;
  1514. }
  1515. int cmcmd::WindowsCEEnvironment(const char* version, const std::string& name)
  1516. {
  1517. #if !defined(CMAKE_BOOTSTRAP) && defined(_WIN32) && !defined(__CYGWIN__)
  1518. cmVisualStudioWCEPlatformParser parser(name.c_str());
  1519. parser.ParseVersion(version);
  1520. if (parser.Found()) {
  1521. std::cout << "@echo off" << std::endl;
  1522. std::cout << "echo Environment Selection: " << name << std::endl;
  1523. std::cout << "set PATH=" << parser.GetPathDirectories() << std::endl;
  1524. std::cout << "set INCLUDE=" << parser.GetIncludeDirectories() << std::endl;
  1525. std::cout << "set LIB=" << parser.GetLibraryDirectories() << std::endl;
  1526. return 0;
  1527. }
  1528. #else
  1529. (void)version;
  1530. #endif
  1531. std::cerr << "Could not find " << name;
  1532. return -1;
  1533. }
  1534. int cmcmd::RunPreprocessor(const std::vector<std::string>& command,
  1535. const std::string& intermediate_file)
  1536. {
  1537. cmUVProcessChainBuilder builder;
  1538. uv_fs_t fs_req;
  1539. int preprocessedFile =
  1540. uv_fs_open(nullptr, &fs_req, intermediate_file.c_str(), O_CREAT | O_RDWR,
  1541. 0644, nullptr);
  1542. uv_fs_req_cleanup(&fs_req);
  1543. builder
  1544. .SetExternalStream(cmUVProcessChainBuilder::Stream_OUTPUT,
  1545. preprocessedFile)
  1546. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1547. .AddCommand(command);
  1548. auto process = builder.Start();
  1549. if (!process.Valid()) {
  1550. std::cerr << "Failed to start preprocessor.";
  1551. return 1;
  1552. }
  1553. if (!process.Wait()) {
  1554. std::cerr << "Failed to wait for preprocessor";
  1555. return 1;
  1556. }
  1557. auto status = process.GetStatus();
  1558. if (!status[0] || status[0]->ExitStatus != 0) {
  1559. return 1;
  1560. }
  1561. return 0;
  1562. }
  1563. int cmcmd::RunLLVMRC(std::vector<std::string> const& args)
  1564. {
  1565. // The arguments are
  1566. // args[0] == <cmake-executable>
  1567. // args[1] == cmake_llvm_rc
  1568. // args[2] == intermediate_file
  1569. // args[3..n] == preprocess+args
  1570. // args[n+1] == --
  1571. // args[n+2...] == llvm-rc+args
  1572. if (args.size() < 3) {
  1573. std::cerr << "Invalid cmake_llvm_rc arguments";
  1574. return 1;
  1575. }
  1576. const std::string& intermediate_file = args[2];
  1577. std::vector<std::string> preprocess;
  1578. std::vector<std::string> resource_compile;
  1579. std::vector<std::string>* pArgTgt = &preprocess;
  1580. for (std::string const& arg : cmMakeRange(args).advance(3)) {
  1581. if (arg == "--") {
  1582. pArgTgt = &resource_compile;
  1583. } else {
  1584. pArgTgt->push_back(arg);
  1585. }
  1586. }
  1587. if (preprocess.empty()) {
  1588. std::cerr << "Empty preprocessing command";
  1589. return 1;
  1590. }
  1591. if (resource_compile.empty()) {
  1592. std::cerr << "Empty resource compilation command";
  1593. return 1;
  1594. }
  1595. auto result = RunPreprocessor(preprocess, intermediate_file);
  1596. if (result != 0) {
  1597. cmSystemTools::RemoveFile(intermediate_file);
  1598. return result;
  1599. }
  1600. cmUVProcessChainBuilder builder;
  1601. builder.SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  1602. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR)
  1603. .AddCommand(resource_compile);
  1604. auto process = builder.Start();
  1605. result = 0;
  1606. if (!process.Valid()) {
  1607. std::cerr << "Failed to start resource compiler.";
  1608. result = 1;
  1609. } else {
  1610. if (!process.Wait()) {
  1611. std::cerr << "Failed to wait for resource compiler";
  1612. result = 1;
  1613. }
  1614. }
  1615. cmSystemTools::RemoveFile(intermediate_file);
  1616. if (result != 0) {
  1617. return result;
  1618. }
  1619. auto status = process.GetStatus();
  1620. if (!status[0] || status[0]->ExitStatus != 0) {
  1621. return 1;
  1622. }
  1623. return 0;
  1624. }
  1625. class cmVSLink
  1626. {
  1627. int Type;
  1628. bool Verbose;
  1629. bool Incremental;
  1630. bool LinkGeneratesManifest;
  1631. std::vector<std::string> LinkCommand;
  1632. std::vector<std::string> UserManifests;
  1633. std::string LinkerManifestFile;
  1634. std::string ManifestFile;
  1635. std::string ManifestFileRC;
  1636. std::string ManifestFileRes;
  1637. std::string TargetFile;
  1638. std::string MtPath;
  1639. std::string RcPath;
  1640. public:
  1641. cmVSLink(int type, bool verbose)
  1642. : Type(type)
  1643. , Verbose(verbose)
  1644. , Incremental(false)
  1645. , LinkGeneratesManifest(true)
  1646. {
  1647. }
  1648. bool Parse(std::vector<std::string>::const_iterator argBeg,
  1649. std::vector<std::string>::const_iterator argEnd);
  1650. int Link();
  1651. private:
  1652. int LinkIncremental();
  1653. int LinkNonIncremental();
  1654. int RunMT(std::string const& out, bool notify);
  1655. };
  1656. // For visual studio 2005 and newer manifest files need to be embedded into
  1657. // exe and dll's. This code does that in such a way that incremental linking
  1658. // still works.
  1659. int cmcmd::VisualStudioLink(std::vector<std::string> const& args, int type)
  1660. {
  1661. #if defined(_WIN32) && !defined(CMAKE_BOOTSTRAP)
  1662. // Replace streambuf so we output in the system codepage. CMake is set up
  1663. // to output in Unicode (see SetUTF8Pipes) but the Visual Studio linker
  1664. // outputs using the system codepage so we need to change behavior when
  1665. // we run the link command.
  1666. cmsys::ConsoleBuf::Manager consoleOut(std::cout);
  1667. cmsys::ConsoleBuf::Manager consoleErr(std::cerr, true);
  1668. #endif
  1669. if (args.size() < 2) {
  1670. return -1;
  1671. }
  1672. const bool verbose = cmSystemTools::HasEnv("VERBOSE");
  1673. std::vector<std::string> expandedArgs;
  1674. for (std::string const& i : args) {
  1675. // check for nmake temporary files
  1676. if (i[0] == '@' && !cmHasLiteralPrefix(i, "@CMakeFiles")) {
  1677. cmsys::ifstream fin(i.substr(1).c_str());
  1678. std::string line;
  1679. while (cmSystemTools::GetLineFromStream(fin, line)) {
  1680. cmSystemTools::ParseWindowsCommandLine(line.c_str(), expandedArgs);
  1681. }
  1682. } else {
  1683. expandedArgs.push_back(i);
  1684. }
  1685. }
  1686. cmVSLink vsLink(type, verbose);
  1687. if (!vsLink.Parse(expandedArgs.begin() + 2, expandedArgs.end())) {
  1688. return -1;
  1689. }
  1690. return vsLink.Link();
  1691. }
  1692. enum NumberFormat
  1693. {
  1694. FORMAT_DECIMAL,
  1695. FORMAT_HEX
  1696. };
  1697. struct NumberFormatter
  1698. {
  1699. NumberFormat Format;
  1700. int Value;
  1701. NumberFormatter(NumberFormat format, int value)
  1702. : Format(format)
  1703. , Value(value)
  1704. {
  1705. }
  1706. };
  1707. std::ostream& operator<<(std::ostream& stream,
  1708. NumberFormatter const& formatter)
  1709. {
  1710. auto const& flags = stream.flags();
  1711. if (formatter.Format == FORMAT_DECIMAL) {
  1712. stream << std::dec << formatter.Value;
  1713. } else {
  1714. stream << "0x" << std::hex << formatter.Value;
  1715. }
  1716. stream.flags(flags);
  1717. return stream;
  1718. }
  1719. static bool RunCommand(const char* comment,
  1720. std::vector<std::string> const& command, bool verbose,
  1721. NumberFormat exitFormat, int* retCodeOut = nullptr,
  1722. bool (*retCodeOkay)(int) = nullptr)
  1723. {
  1724. if (verbose) {
  1725. std::cout << comment << ":\n";
  1726. std::cout << cmJoin(command, " ") << "\n";
  1727. }
  1728. std::string output;
  1729. int retCode = 0;
  1730. bool commandResult = cmSystemTools::RunSingleCommand(
  1731. command, &output, &output, &retCode, nullptr, cmSystemTools::OUTPUT_NONE);
  1732. bool const retCodeSuccess =
  1733. retCode == 0 || (retCodeOkay && retCodeOkay(retCode));
  1734. bool const success = commandResult && retCodeSuccess;
  1735. if (retCodeOut) {
  1736. if (commandResult || !retCodeSuccess) {
  1737. *retCodeOut = retCode;
  1738. } else {
  1739. *retCodeOut = -1;
  1740. }
  1741. }
  1742. if (!success) {
  1743. std::cout << comment << ": command \"" << cmJoin(command, " ")
  1744. << "\" failed (exit code "
  1745. << NumberFormatter(exitFormat, retCode)
  1746. << ") with the following output:\n"
  1747. << output;
  1748. } else {
  1749. // always print the output of the command, unless
  1750. // it is the dumb rc command banner
  1751. if (output.find("Resource Compiler Version") == std::string::npos) {
  1752. std::cout << output;
  1753. }
  1754. }
  1755. return success;
  1756. }
  1757. bool cmVSLink::Parse(std::vector<std::string>::const_iterator argBeg,
  1758. std::vector<std::string>::const_iterator argEnd)
  1759. {
  1760. // Parse our own arguments.
  1761. std::string intDir;
  1762. auto arg = argBeg;
  1763. while (arg != argEnd && cmHasLiteralPrefix(*arg, "-")) {
  1764. if (*arg == "--") {
  1765. ++arg;
  1766. break;
  1767. }
  1768. if (*arg == "--manifests") {
  1769. for (++arg; arg != argEnd && !cmHasLiteralPrefix(*arg, "-"); ++arg) {
  1770. this->UserManifests.push_back(*arg);
  1771. }
  1772. } else if (cmHasLiteralPrefix(*arg, "--intdir=")) {
  1773. intDir = arg->substr(9);
  1774. ++arg;
  1775. } else if (cmHasLiteralPrefix(*arg, "--rc=")) {
  1776. this->RcPath = arg->substr(5);
  1777. ++arg;
  1778. } else if (cmHasLiteralPrefix(*arg, "--mt=")) {
  1779. this->MtPath = arg->substr(5);
  1780. ++arg;
  1781. } else {
  1782. std::cerr << "unknown argument '" << *arg << "'\n";
  1783. return false;
  1784. }
  1785. }
  1786. if (intDir.empty()) {
  1787. return false;
  1788. }
  1789. // The rest of the arguments form the link command.
  1790. if (arg == argEnd) {
  1791. return false;
  1792. }
  1793. this->LinkCommand.insert(this->LinkCommand.begin(), arg, argEnd);
  1794. // Parse the link command to extract information we need.
  1795. for (; arg != argEnd; ++arg) {
  1796. if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL:YES") == 0) {
  1797. this->Incremental = true;
  1798. } else if (cmSystemTools::Strucmp(arg->c_str(), "/INCREMENTAL") == 0) {
  1799. this->Incremental = true;
  1800. } else if (cmSystemTools::Strucmp(arg->c_str(), "/MANIFEST:NO") == 0) {
  1801. this->LinkGeneratesManifest = false;
  1802. } else if (cmHasLiteralPrefix(*arg, "/Fe")) {
  1803. this->TargetFile = arg->substr(3);
  1804. } else if (cmHasLiteralPrefix(*arg, "/out:")) {
  1805. this->TargetFile = arg->substr(5);
  1806. }
  1807. }
  1808. if (this->TargetFile.empty()) {
  1809. return false;
  1810. }
  1811. this->ManifestFile = intDir + "/embed.manifest";
  1812. this->LinkerManifestFile = intDir + "/intermediate.manifest";
  1813. if (this->Incremental) {
  1814. // We will compile a resource containing the manifest and
  1815. // pass it to the link command.
  1816. this->ManifestFileRC = intDir + "/manifest.rc";
  1817. this->ManifestFileRes = intDir + "/manifest.res";
  1818. } else if (this->UserManifests.empty()) {
  1819. // Prior to support for user-specified manifests CMake placed the
  1820. // linker-generated manifest next to the binary (as if it were not to be
  1821. // embedded) when not linking incrementally. Preserve this behavior.
  1822. this->ManifestFile = this->TargetFile + ".manifest";
  1823. this->LinkerManifestFile = this->ManifestFile;
  1824. }
  1825. if (this->LinkGeneratesManifest) {
  1826. this->LinkCommand.emplace_back("/MANIFEST");
  1827. this->LinkCommand.push_back("/MANIFESTFILE:" + this->LinkerManifestFile);
  1828. }
  1829. return true;
  1830. }
  1831. int cmVSLink::Link()
  1832. {
  1833. if (this->Incremental &&
  1834. (this->LinkGeneratesManifest || !this->UserManifests.empty())) {
  1835. if (this->Verbose) {
  1836. std::cout << "Visual Studio Incremental Link with embedded manifests\n";
  1837. }
  1838. return LinkIncremental();
  1839. }
  1840. if (this->Verbose) {
  1841. if (!this->Incremental) {
  1842. std::cout << "Visual Studio Non-Incremental Link\n";
  1843. } else {
  1844. std::cout << "Visual Studio Incremental Link without manifests\n";
  1845. }
  1846. }
  1847. return LinkNonIncremental();
  1848. }
  1849. static bool mtRetIsUpdate(int mtRet)
  1850. {
  1851. // 'mt /notify_update' returns a special value (differing between
  1852. // Windows and POSIX hosts) when it updated the manifest file.
  1853. return mtRet == 0x41020001 || mtRet == 0xbb;
  1854. }
  1855. int cmVSLink::LinkIncremental()
  1856. {
  1857. // This follows the steps listed here:
  1858. // http://blogs.msdn.com/zakramer/archive/2006/05/22/603558.aspx
  1859. // 1. Compiler compiles the application and generates the *.obj files.
  1860. // 2. An empty manifest file is generated if this is a clean build and if
  1861. // not the previous one is reused.
  1862. // 3. The resource compiler (rc.exe) compiles the *.manifest file to a
  1863. // *.res file.
  1864. // 4. Linker generates the binary (EXE or DLL) with the /incremental
  1865. // switch and embeds the dummy manifest file. The linker also generates
  1866. // the real manifest file based on the binaries that your binary depends
  1867. // on.
  1868. // 5. The manifest tool (mt.exe) is then used to generate the final
  1869. // manifest.
  1870. // If the final manifest is changed, then 6 and 7 are run, if not
  1871. // they are skipped, and it is done.
  1872. // 6. The resource compiler is invoked one more time.
  1873. // 7. Finally, the Linker does another incremental link, but since the
  1874. // only thing that has changed is the *.res file that contains the
  1875. // manifest it is a short link.
  1876. // Create a resource file referencing the manifest.
  1877. std::string absManifestFile =
  1878. cmSystemTools::CollapseFullPath(this->ManifestFile);
  1879. if (this->Verbose) {
  1880. std::cout << "Create " << this->ManifestFileRC << "\n";
  1881. }
  1882. {
  1883. cmsys::ofstream fout(this->ManifestFileRC.c_str());
  1884. if (!fout) {
  1885. return -1;
  1886. }
  1887. // Insert a pragma statement to specify utf-8 encoding.
  1888. fout << "#pragma code_page(65001)\n";
  1889. fout << this->Type
  1890. << " /* CREATEPROCESS_MANIFEST_RESOURCE_ID */ "
  1891. "24 /* RT_MANIFEST */ \""
  1892. << absManifestFile << "\"";
  1893. }
  1894. // If we have not previously generated a manifest file,
  1895. // generate an empty one so the resource compiler succeeds.
  1896. if (!cmSystemTools::FileExists(this->ManifestFile)) {
  1897. if (this->Verbose) {
  1898. std::cout << "Create empty: " << this->ManifestFile << "\n";
  1899. }
  1900. cmsys::ofstream foutTmp(this->ManifestFile.c_str());
  1901. }
  1902. // Compile the resource file.
  1903. std::vector<std::string> rcCommand;
  1904. rcCommand.push_back(this->RcPath.empty() ? "rc" : this->RcPath);
  1905. rcCommand.emplace_back("/fo");
  1906. rcCommand.push_back(this->ManifestFileRes);
  1907. rcCommand.push_back(this->ManifestFileRC);
  1908. if (!RunCommand("RC Pass 1", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1909. return -1;
  1910. }
  1911. // Tell the linker to use our manifest compiled into a resource.
  1912. this->LinkCommand.push_back(this->ManifestFileRes);
  1913. // Run the link command (possibly generates intermediate manifest).
  1914. if (!RunCommand("LINK Pass 1", this->LinkCommand, this->Verbose,
  1915. FORMAT_DECIMAL)) {
  1916. return -1;
  1917. }
  1918. // Run the manifest tool to create the final manifest.
  1919. int mtRet = this->RunMT("/out:" + this->ManifestFile, true);
  1920. // If mt returns a special value then it updated the manifest file so
  1921. // we need to embed it again. Otherwise we are done.
  1922. if (!mtRetIsUpdate(mtRet)) {
  1923. return mtRet;
  1924. }
  1925. // Compile the resource file again.
  1926. if (!RunCommand("RC Pass 2", rcCommand, this->Verbose, FORMAT_DECIMAL)) {
  1927. return -1;
  1928. }
  1929. // Link incrementally again to use the updated resource.
  1930. if (!RunCommand("FINAL LINK", this->LinkCommand, this->Verbose,
  1931. FORMAT_DECIMAL)) {
  1932. return -1;
  1933. }
  1934. return 0;
  1935. }
  1936. int cmVSLink::LinkNonIncremental()
  1937. {
  1938. // Run the link command (possibly generates intermediate manifest).
  1939. if (!RunCommand("LINK", this->LinkCommand, this->Verbose, FORMAT_DECIMAL)) {
  1940. return -1;
  1941. }
  1942. // If we have no manifest files we are done.
  1943. if (!this->LinkGeneratesManifest && this->UserManifests.empty()) {
  1944. return 0;
  1945. }
  1946. // Run the manifest tool to embed the final manifest in the binary.
  1947. std::string mtOut =
  1948. "/outputresource:" + this->TargetFile + (this->Type == 1 ? ";#1" : ";#2");
  1949. return this->RunMT(mtOut, false);
  1950. }
  1951. int cmVSLink::RunMT(std::string const& out, bool notify)
  1952. {
  1953. std::vector<std::string> mtCommand;
  1954. mtCommand.push_back(this->MtPath.empty() ? "mt" : this->MtPath);
  1955. mtCommand.emplace_back("/nologo");
  1956. mtCommand.emplace_back("/manifest");
  1957. if (this->LinkGeneratesManifest) {
  1958. mtCommand.push_back(this->LinkerManifestFile);
  1959. }
  1960. cm::append(mtCommand, this->UserManifests);
  1961. mtCommand.push_back(out);
  1962. if (notify) {
  1963. // Add an undocumented option that enables a special return
  1964. // code to notify us when the manifest is modified.
  1965. mtCommand.emplace_back("/notify_update");
  1966. }
  1967. int mtRet = 0;
  1968. if (!RunCommand("MT", mtCommand, this->Verbose, FORMAT_HEX, &mtRet,
  1969. mtRetIsUpdate)) {
  1970. return -1;
  1971. }
  1972. return mtRet;
  1973. }