cmcmd.cxx 73 KB

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