cmcmd.cxx 72 KB

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