cmFileCommand.cxx 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520
  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 "cmFileCommand.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cctype>
  7. #include <cmath>
  8. #include <cstdio>
  9. #include <cstdlib>
  10. #include <map>
  11. #include <set>
  12. #include <sstream>
  13. #include <utility>
  14. #include <vector>
  15. #include <cm/memory>
  16. #include <cm/string_view>
  17. #include <cmext/algorithm>
  18. #include <cmext/string_view>
  19. #include <cm3p/kwiml/int.h>
  20. #include "cmsys/FStream.hxx"
  21. #include "cmsys/Glob.hxx"
  22. #include "cmsys/RegularExpression.hxx"
  23. #include "cm_sys_stat.h"
  24. #include "cmAlgorithms.h"
  25. #include "cmArgumentParser.h"
  26. #include "cmCMakePath.h"
  27. #include "cmCryptoHash.h"
  28. #include "cmExecutionStatus.h"
  29. #include "cmFSPermissions.h"
  30. #include "cmFileCopier.h"
  31. #include "cmFileInstaller.h"
  32. #include "cmFileLockPool.h"
  33. #include "cmFileTimes.h"
  34. #include "cmGeneratedFileStream.h"
  35. #include "cmGeneratorExpression.h"
  36. #include "cmGlobalGenerator.h"
  37. #include "cmHexFileConverter.h"
  38. #include "cmListFileCache.h"
  39. #include "cmMakefile.h"
  40. #include "cmMessageType.h"
  41. #include "cmNewLineStyle.h"
  42. #include "cmPolicies.h"
  43. #include "cmProperty.h"
  44. #include "cmRange.h"
  45. #include "cmRuntimeDependencyArchive.h"
  46. #include "cmState.h"
  47. #include "cmStringAlgorithms.h"
  48. #include "cmSubcommandTable.h"
  49. #include "cmSystemTools.h"
  50. #include "cmTimestamp.h"
  51. #include "cmWorkingDirectory.h"
  52. #include "cmake.h"
  53. #if !defined(CMAKE_BOOTSTRAP)
  54. # include <cm3p/curl/curl.h>
  55. # include "cmCurl.h"
  56. # include "cmFileLockResult.h"
  57. #endif
  58. #if defined(CMAKE_USE_ELF_PARSER)
  59. # include "cmELF.h"
  60. #endif
  61. #if defined(_WIN32)
  62. # include <windows.h>
  63. #endif
  64. namespace {
  65. #if defined(_WIN32)
  66. // libcurl doesn't support file:// urls for unicode filenames on Windows.
  67. // Convert string from UTF-8 to ACP if this is a file:// URL.
  68. std::string fix_file_url_windows(const std::string& url)
  69. {
  70. std::string ret = url;
  71. if (strncmp(url.c_str(), "file://", 7) == 0) {
  72. std::wstring wurl = cmsys::Encoding::ToWide(url);
  73. if (!wurl.empty()) {
  74. int mblen =
  75. WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, NULL, 0, NULL, NULL);
  76. if (mblen > 0) {
  77. std::vector<char> chars(mblen);
  78. mblen = WideCharToMultiByte(CP_ACP, 0, wurl.c_str(), -1, &chars[0],
  79. mblen, NULL, NULL);
  80. if (mblen > 0) {
  81. ret = &chars[0];
  82. }
  83. }
  84. }
  85. }
  86. return ret;
  87. }
  88. #endif
  89. bool HandleWriteImpl(std::vector<std::string> const& args, bool append,
  90. cmExecutionStatus& status)
  91. {
  92. auto i = args.begin();
  93. i++; // Get rid of subcommand
  94. std::string fileName = *i;
  95. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  96. fileName =
  97. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', *i);
  98. }
  99. i++;
  100. if (!status.GetMakefile().CanIWriteThisFile(fileName)) {
  101. std::string e =
  102. "attempted to write a file: " + fileName + " into a source directory.";
  103. status.SetError(e);
  104. cmSystemTools::SetFatalErrorOccured();
  105. return false;
  106. }
  107. std::string dir = cmSystemTools::GetFilenamePath(fileName);
  108. cmSystemTools::MakeDirectory(dir);
  109. mode_t mode = 0;
  110. bool writable = false;
  111. // Set permissions to writable
  112. if (cmSystemTools::GetPermissions(fileName, mode)) {
  113. #if defined(_MSC_VER) || defined(__MINGW32__)
  114. writable = (mode & S_IWRITE) != 0;
  115. mode_t newMode = mode | S_IWRITE;
  116. #else
  117. writable = mode & S_IWUSR;
  118. mode_t newMode = mode | S_IWUSR | S_IWGRP;
  119. #endif
  120. if (!writable) {
  121. cmSystemTools::SetPermissions(fileName, newMode);
  122. }
  123. }
  124. // If GetPermissions fails, pretend like it is ok. File open will fail if
  125. // the file is not writable
  126. cmsys::ofstream file(fileName.c_str(),
  127. append ? std::ios::app : std::ios::out);
  128. if (!file) {
  129. std::string error =
  130. cmStrCat("failed to open for writing (",
  131. cmSystemTools::GetLastSystemError(), "):\n ", fileName);
  132. status.SetError(error);
  133. return false;
  134. }
  135. std::string message = cmJoin(cmMakeRange(i, args.end()), std::string());
  136. file << message;
  137. if (!file) {
  138. std::string error =
  139. cmStrCat("write failed (", cmSystemTools::GetLastSystemError(), "):\n ",
  140. fileName);
  141. status.SetError(error);
  142. return false;
  143. }
  144. file.close();
  145. if (mode && !writable) {
  146. cmSystemTools::SetPermissions(fileName, mode);
  147. }
  148. return true;
  149. }
  150. bool HandleWriteCommand(std::vector<std::string> const& args,
  151. cmExecutionStatus& status)
  152. {
  153. return HandleWriteImpl(args, false, status);
  154. }
  155. bool HandleAppendCommand(std::vector<std::string> const& args,
  156. cmExecutionStatus& status)
  157. {
  158. return HandleWriteImpl(args, true, status);
  159. }
  160. bool HandleReadCommand(std::vector<std::string> const& args,
  161. cmExecutionStatus& status)
  162. {
  163. if (args.size() < 3) {
  164. status.SetError("READ must be called with at least two additional "
  165. "arguments");
  166. return false;
  167. }
  168. std::string const& fileNameArg = args[1];
  169. std::string const& variable = args[2];
  170. struct Arguments
  171. {
  172. std::string Offset;
  173. std::string Limit;
  174. bool Hex = false;
  175. };
  176. static auto const parser = cmArgumentParser<Arguments>{}
  177. .Bind("OFFSET"_s, &Arguments::Offset)
  178. .Bind("LIMIT"_s, &Arguments::Limit)
  179. .Bind("HEX"_s, &Arguments::Hex);
  180. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(3));
  181. std::string fileName = fileNameArg;
  182. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  183. fileName = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  184. fileNameArg);
  185. }
  186. // Open the specified file.
  187. #if defined(_WIN32) || defined(__CYGWIN__)
  188. cmsys::ifstream file(fileName.c_str(),
  189. arguments.Hex ? (std::ios::binary | std::ios::in)
  190. : std::ios::in);
  191. #else
  192. cmsys::ifstream file(fileName.c_str());
  193. #endif
  194. if (!file) {
  195. std::string error =
  196. cmStrCat("failed to open for reading (",
  197. cmSystemTools::GetLastSystemError(), "):\n ", fileName);
  198. status.SetError(error);
  199. return false;
  200. }
  201. // is there a limit?
  202. long sizeLimit = -1;
  203. if (!arguments.Limit.empty()) {
  204. sizeLimit = atoi(arguments.Limit.c_str());
  205. }
  206. // is there an offset?
  207. long offset = 0;
  208. if (!arguments.Offset.empty()) {
  209. offset = atoi(arguments.Offset.c_str());
  210. }
  211. file.seekg(offset, std::ios::beg); // explicit ios::beg for IBM VisualAge 6
  212. std::string output;
  213. if (arguments.Hex) {
  214. // Convert part of the file into hex code
  215. char c;
  216. while ((sizeLimit != 0) && (file.get(c))) {
  217. char hex[4];
  218. sprintf(hex, "%.2x", c & 0xff);
  219. output += hex;
  220. if (sizeLimit > 0) {
  221. sizeLimit--;
  222. }
  223. }
  224. } else {
  225. std::string line;
  226. bool has_newline = false;
  227. while (
  228. sizeLimit != 0 &&
  229. cmSystemTools::GetLineFromStream(file, line, &has_newline, sizeLimit)) {
  230. if (sizeLimit > 0) {
  231. sizeLimit = sizeLimit - static_cast<long>(line.size());
  232. if (has_newline) {
  233. sizeLimit--;
  234. }
  235. if (sizeLimit < 0) {
  236. sizeLimit = 0;
  237. }
  238. }
  239. output += line;
  240. if (has_newline) {
  241. output += "\n";
  242. }
  243. }
  244. }
  245. status.GetMakefile().AddDefinition(variable, output);
  246. return true;
  247. }
  248. bool HandleHashCommand(std::vector<std::string> const& args,
  249. cmExecutionStatus& status)
  250. {
  251. #if !defined(CMAKE_BOOTSTRAP)
  252. if (args.size() != 3) {
  253. status.SetError(
  254. cmStrCat(args[0], " requires a file name and output variable"));
  255. return false;
  256. }
  257. std::unique_ptr<cmCryptoHash> hash(cmCryptoHash::New(args[0]));
  258. if (hash) {
  259. std::string out = hash->HashFile(args[1]);
  260. if (!out.empty()) {
  261. status.GetMakefile().AddDefinition(args[2], out);
  262. return true;
  263. }
  264. status.SetError(cmStrCat(args[0], " failed to read file \"", args[1],
  265. "\": ", cmSystemTools::GetLastSystemError()));
  266. }
  267. return false;
  268. #else
  269. status.SetError(cmStrCat(args[0], " not available during bootstrap"));
  270. return false;
  271. #endif
  272. }
  273. bool HandleStringsCommand(std::vector<std::string> const& args,
  274. cmExecutionStatus& status)
  275. {
  276. if (args.size() < 3) {
  277. status.SetError("STRINGS requires a file name and output variable");
  278. return false;
  279. }
  280. // Get the file to read.
  281. std::string fileName = args[1];
  282. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  283. fileName =
  284. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  285. }
  286. // Get the variable in which to store the results.
  287. std::string outVar = args[2];
  288. // Parse the options.
  289. enum
  290. {
  291. arg_none,
  292. arg_limit_input,
  293. arg_limit_output,
  294. arg_limit_count,
  295. arg_length_minimum,
  296. arg_length_maximum,
  297. arg__maximum,
  298. arg_regex,
  299. arg_encoding
  300. };
  301. unsigned int minlen = 0;
  302. unsigned int maxlen = 0;
  303. int limit_input = -1;
  304. int limit_output = -1;
  305. unsigned int limit_count = 0;
  306. cmsys::RegularExpression regex;
  307. bool have_regex = false;
  308. bool newline_consume = false;
  309. bool hex_conversion_enabled = true;
  310. enum
  311. {
  312. encoding_none = cmsys::FStream::BOM_None,
  313. encoding_utf8 = cmsys::FStream::BOM_UTF8,
  314. encoding_utf16le = cmsys::FStream::BOM_UTF16LE,
  315. encoding_utf16be = cmsys::FStream::BOM_UTF16BE,
  316. encoding_utf32le = cmsys::FStream::BOM_UTF32LE,
  317. encoding_utf32be = cmsys::FStream::BOM_UTF32BE
  318. };
  319. int encoding = encoding_none;
  320. int arg_mode = arg_none;
  321. for (unsigned int i = 3; i < args.size(); ++i) {
  322. if (args[i] == "LIMIT_INPUT") {
  323. arg_mode = arg_limit_input;
  324. } else if (args[i] == "LIMIT_OUTPUT") {
  325. arg_mode = arg_limit_output;
  326. } else if (args[i] == "LIMIT_COUNT") {
  327. arg_mode = arg_limit_count;
  328. } else if (args[i] == "LENGTH_MINIMUM") {
  329. arg_mode = arg_length_minimum;
  330. } else if (args[i] == "LENGTH_MAXIMUM") {
  331. arg_mode = arg_length_maximum;
  332. } else if (args[i] == "REGEX") {
  333. arg_mode = arg_regex;
  334. } else if (args[i] == "NEWLINE_CONSUME") {
  335. newline_consume = true;
  336. arg_mode = arg_none;
  337. } else if (args[i] == "NO_HEX_CONVERSION") {
  338. hex_conversion_enabled = false;
  339. arg_mode = arg_none;
  340. } else if (args[i] == "ENCODING") {
  341. arg_mode = arg_encoding;
  342. } else if (arg_mode == arg_limit_input) {
  343. if (sscanf(args[i].c_str(), "%d", &limit_input) != 1 ||
  344. limit_input < 0) {
  345. status.SetError(cmStrCat("STRINGS option LIMIT_INPUT value \"",
  346. args[i], "\" is not an unsigned integer."));
  347. return false;
  348. }
  349. arg_mode = arg_none;
  350. } else if (arg_mode == arg_limit_output) {
  351. if (sscanf(args[i].c_str(), "%d", &limit_output) != 1 ||
  352. limit_output < 0) {
  353. status.SetError(cmStrCat("STRINGS option LIMIT_OUTPUT value \"",
  354. args[i], "\" is not an unsigned integer."));
  355. return false;
  356. }
  357. arg_mode = arg_none;
  358. } else if (arg_mode == arg_limit_count) {
  359. int count;
  360. if (sscanf(args[i].c_str(), "%d", &count) != 1 || count < 0) {
  361. status.SetError(cmStrCat("STRINGS option LIMIT_COUNT value \"",
  362. args[i], "\" is not an unsigned integer."));
  363. return false;
  364. }
  365. limit_count = count;
  366. arg_mode = arg_none;
  367. } else if (arg_mode == arg_length_minimum) {
  368. int len;
  369. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  370. status.SetError(cmStrCat("STRINGS option LENGTH_MINIMUM value \"",
  371. args[i], "\" is not an unsigned integer."));
  372. return false;
  373. }
  374. minlen = len;
  375. arg_mode = arg_none;
  376. } else if (arg_mode == arg_length_maximum) {
  377. int len;
  378. if (sscanf(args[i].c_str(), "%d", &len) != 1 || len < 0) {
  379. status.SetError(cmStrCat("STRINGS option LENGTH_MAXIMUM value \"",
  380. args[i], "\" is not an unsigned integer."));
  381. return false;
  382. }
  383. maxlen = len;
  384. arg_mode = arg_none;
  385. } else if (arg_mode == arg_regex) {
  386. if (!regex.compile(args[i])) {
  387. status.SetError(cmStrCat("STRINGS option REGEX value \"", args[i],
  388. "\" could not be compiled."));
  389. return false;
  390. }
  391. have_regex = true;
  392. arg_mode = arg_none;
  393. } else if (arg_mode == arg_encoding) {
  394. if (args[i] == "UTF-8") {
  395. encoding = encoding_utf8;
  396. } else if (args[i] == "UTF-16LE") {
  397. encoding = encoding_utf16le;
  398. } else if (args[i] == "UTF-16BE") {
  399. encoding = encoding_utf16be;
  400. } else if (args[i] == "UTF-32LE") {
  401. encoding = encoding_utf32le;
  402. } else if (args[i] == "UTF-32BE") {
  403. encoding = encoding_utf32be;
  404. } else {
  405. status.SetError(cmStrCat("STRINGS option ENCODING \"", args[i],
  406. "\" not recognized."));
  407. return false;
  408. }
  409. arg_mode = arg_none;
  410. } else {
  411. status.SetError(
  412. cmStrCat("STRINGS given unknown argument \"", args[i], "\""));
  413. return false;
  414. }
  415. }
  416. if (hex_conversion_enabled) {
  417. // TODO: should work without temp file, but just on a memory buffer
  418. std::string binaryFileName =
  419. cmStrCat(status.GetMakefile().GetCurrentBinaryDirectory(),
  420. "/CMakeFiles/FileCommandStringsBinaryFile");
  421. if (cmHexFileConverter::TryConvert(fileName, binaryFileName)) {
  422. fileName = binaryFileName;
  423. }
  424. }
  425. // Open the specified file.
  426. #if defined(_WIN32) || defined(__CYGWIN__)
  427. cmsys::ifstream fin(fileName.c_str(), std::ios::in | std::ios::binary);
  428. #else
  429. cmsys::ifstream fin(fileName.c_str());
  430. #endif
  431. if (!fin) {
  432. status.SetError(
  433. cmStrCat("STRINGS file \"", fileName, "\" cannot be read."));
  434. return false;
  435. }
  436. // If BOM is found and encoding was not specified, use the BOM
  437. int bom_found = cmsys::FStream::ReadBOM(fin);
  438. if (encoding == encoding_none && bom_found != cmsys::FStream::BOM_None) {
  439. encoding = bom_found;
  440. }
  441. unsigned int bytes_rem = 0;
  442. if (encoding == encoding_utf16le || encoding == encoding_utf16be) {
  443. bytes_rem = 1;
  444. }
  445. if (encoding == encoding_utf32le || encoding == encoding_utf32be) {
  446. bytes_rem = 3;
  447. }
  448. // Parse strings out of the file.
  449. int output_size = 0;
  450. std::vector<std::string> strings;
  451. std::string s;
  452. while ((!limit_count || strings.size() < limit_count) &&
  453. (limit_input < 0 || static_cast<int>(fin.tellg()) < limit_input) &&
  454. fin) {
  455. std::string current_str;
  456. int c = fin.get();
  457. for (unsigned int i = 0; i < bytes_rem; ++i) {
  458. int c1 = fin.get();
  459. if (!fin) {
  460. fin.putback(static_cast<char>(c1));
  461. break;
  462. }
  463. c = (c << 8) | c1;
  464. }
  465. if (encoding == encoding_utf16le) {
  466. c = ((c & 0xFF) << 8) | ((c & 0xFF00) >> 8);
  467. } else if (encoding == encoding_utf32le) {
  468. c = (((c & 0xFF) << 24) | ((c & 0xFF00) << 8) | ((c & 0xFF0000) >> 8) |
  469. ((c & 0xFF000000) >> 24));
  470. }
  471. if (c == '\r') {
  472. // Ignore CR character to make output always have UNIX newlines.
  473. continue;
  474. }
  475. if (c >= 0 && c <= 0xFF &&
  476. (isprint(c) || c == '\t' || (c == '\n' && newline_consume))) {
  477. // This is an ASCII character that may be part of a string.
  478. // Cast added to avoid compiler warning. Cast is ok because
  479. // c is guaranteed to fit in char by the above if...
  480. current_str += static_cast<char>(c);
  481. } else if (encoding == encoding_utf8) {
  482. // Check for UTF-8 encoded string (up to 4 octets)
  483. static const unsigned char utf8_check_table[3][2] = {
  484. { 0xE0, 0xC0 },
  485. { 0xF0, 0xE0 },
  486. { 0xF8, 0xF0 },
  487. };
  488. // how many octets are there?
  489. unsigned int num_utf8_bytes = 0;
  490. for (unsigned int j = 0; num_utf8_bytes == 0 && j < 3; j++) {
  491. if ((c & utf8_check_table[j][0]) == utf8_check_table[j][1]) {
  492. num_utf8_bytes = j + 2;
  493. }
  494. }
  495. // get subsequent octets and check that they are valid
  496. for (unsigned int j = 0; j < num_utf8_bytes; j++) {
  497. if (j != 0) {
  498. c = fin.get();
  499. if (!fin || (c & 0xC0) != 0x80) {
  500. fin.putback(static_cast<char>(c));
  501. break;
  502. }
  503. }
  504. current_str += static_cast<char>(c);
  505. }
  506. // if this was an invalid utf8 sequence, discard the data, and put
  507. // back subsequent characters
  508. if ((current_str.length() != num_utf8_bytes)) {
  509. for (unsigned int j = 0; j < current_str.size() - 1; j++) {
  510. c = current_str[current_str.size() - 1 - j];
  511. fin.putback(static_cast<char>(c));
  512. }
  513. current_str.clear();
  514. }
  515. }
  516. if (c == '\n' && !newline_consume) {
  517. // The current line has been terminated. Check if the current
  518. // string matches the requirements. The length may now be as
  519. // low as zero since blank lines are allowed.
  520. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  521. output_size += static_cast<int>(s.size()) + 1;
  522. if (limit_output >= 0 && output_size >= limit_output) {
  523. s.clear();
  524. break;
  525. }
  526. strings.push_back(s);
  527. }
  528. // Reset the string to empty.
  529. s.clear();
  530. } else if (current_str.empty()) {
  531. // A non-string character has been found. Check if the current
  532. // string matches the requirements. We require that the length
  533. // be at least one no matter what the user specified.
  534. if (s.length() >= minlen && !s.empty() &&
  535. (!have_regex || regex.find(s))) {
  536. output_size += static_cast<int>(s.size()) + 1;
  537. if (limit_output >= 0 && output_size >= limit_output) {
  538. s.clear();
  539. break;
  540. }
  541. strings.push_back(s);
  542. }
  543. // Reset the string to empty.
  544. s.clear();
  545. } else {
  546. s += current_str;
  547. }
  548. if (maxlen > 0 && s.size() == maxlen) {
  549. // Terminate a string if the maximum length is reached.
  550. if (s.length() >= minlen && (!have_regex || regex.find(s))) {
  551. output_size += static_cast<int>(s.size()) + 1;
  552. if (limit_output >= 0 && output_size >= limit_output) {
  553. s.clear();
  554. break;
  555. }
  556. strings.push_back(s);
  557. }
  558. s.clear();
  559. }
  560. }
  561. // If there is a non-empty current string we have hit the end of the
  562. // input file or the input size limit. Check if the current string
  563. // matches the requirements.
  564. if ((!limit_count || strings.size() < limit_count) && !s.empty() &&
  565. s.length() >= minlen && (!have_regex || regex.find(s))) {
  566. output_size += static_cast<int>(s.size()) + 1;
  567. if (limit_output < 0 || output_size < limit_output) {
  568. strings.push_back(s);
  569. }
  570. }
  571. // Encode the result in a CMake list.
  572. const char* sep = "";
  573. std::string output;
  574. for (std::string const& sr : strings) {
  575. // Separate the strings in the output to make it a list.
  576. output += sep;
  577. sep = ";";
  578. // Store the string in the output, but escape semicolons to
  579. // make sure it is a list.
  580. for (char i : sr) {
  581. if (i == ';') {
  582. output += '\\';
  583. }
  584. output += i;
  585. }
  586. }
  587. // Save the output in a makefile variable.
  588. status.GetMakefile().AddDefinition(outVar, output);
  589. return true;
  590. }
  591. bool HandleGlobImpl(std::vector<std::string> const& args, bool recurse,
  592. cmExecutionStatus& status)
  593. {
  594. // File commands has at least one argument
  595. assert(args.size() > 1);
  596. auto i = args.begin();
  597. i++; // Get rid of subcommand
  598. std::string variable = *i;
  599. i++;
  600. cmsys::Glob g;
  601. g.SetRecurse(recurse);
  602. bool explicitFollowSymlinks = false;
  603. cmPolicies::PolicyStatus policyStatus =
  604. status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0009);
  605. if (recurse) {
  606. switch (policyStatus) {
  607. case cmPolicies::REQUIRED_IF_USED:
  608. case cmPolicies::REQUIRED_ALWAYS:
  609. case cmPolicies::NEW:
  610. g.RecurseThroughSymlinksOff();
  611. break;
  612. case cmPolicies::OLD:
  613. case cmPolicies::WARN:
  614. g.RecurseThroughSymlinksOn();
  615. break;
  616. }
  617. }
  618. cmake* cm = status.GetMakefile().GetCMakeInstance();
  619. std::vector<std::string> files;
  620. bool configureDepends = false;
  621. bool warnConfigureLate = false;
  622. bool warnFollowedSymlinks = false;
  623. const cmake::WorkingMode workingMode = cm->GetWorkingMode();
  624. while (i != args.end()) {
  625. if (*i == "LIST_DIRECTORIES") {
  626. ++i; // skip LIST_DIRECTORIES
  627. if (i != args.end()) {
  628. if (cmIsOn(*i)) {
  629. g.SetListDirs(true);
  630. g.SetRecurseListDirs(true);
  631. } else if (cmIsOff(*i)) {
  632. g.SetListDirs(false);
  633. g.SetRecurseListDirs(false);
  634. } else {
  635. status.SetError("LIST_DIRECTORIES missing bool value.");
  636. return false;
  637. }
  638. ++i;
  639. } else {
  640. status.SetError("LIST_DIRECTORIES missing bool value.");
  641. return false;
  642. }
  643. } else if (*i == "FOLLOW_SYMLINKS") {
  644. ++i; // skip FOLLOW_SYMLINKS
  645. if (recurse) {
  646. explicitFollowSymlinks = true;
  647. g.RecurseThroughSymlinksOn();
  648. if (i == args.end()) {
  649. status.SetError(
  650. "GLOB_RECURSE requires a glob expression after FOLLOW_SYMLINKS.");
  651. return false;
  652. }
  653. }
  654. } else if (*i == "RELATIVE") {
  655. ++i; // skip RELATIVE
  656. if (i == args.end()) {
  657. status.SetError("GLOB requires a directory after the RELATIVE tag.");
  658. return false;
  659. }
  660. g.SetRelative(i->c_str());
  661. ++i;
  662. if (i == args.end()) {
  663. status.SetError(
  664. "GLOB requires a glob expression after the directory.");
  665. return false;
  666. }
  667. } else if (*i == "CONFIGURE_DEPENDS") {
  668. // Generated build system depends on glob results
  669. if (!configureDepends && warnConfigureLate) {
  670. status.GetMakefile().IssueMessage(
  671. MessageType::AUTHOR_WARNING,
  672. "CONFIGURE_DEPENDS flag was given after a glob expression was "
  673. "already evaluated.");
  674. }
  675. if (workingMode != cmake::NORMAL_MODE) {
  676. status.GetMakefile().IssueMessage(
  677. MessageType::FATAL_ERROR,
  678. "CONFIGURE_DEPENDS is invalid for script and find package modes.");
  679. return false;
  680. }
  681. configureDepends = true;
  682. ++i;
  683. if (i == args.end()) {
  684. status.SetError(
  685. "GLOB requires a glob expression after CONFIGURE_DEPENDS.");
  686. return false;
  687. }
  688. } else {
  689. std::string expr = *i;
  690. if (!cmsys::SystemTools::FileIsFullPath(*i)) {
  691. expr = status.GetMakefile().GetCurrentSourceDirectory();
  692. // Handle script mode
  693. if (!expr.empty()) {
  694. expr += "/" + *i;
  695. } else {
  696. expr = *i;
  697. }
  698. }
  699. cmsys::Glob::GlobMessages globMessages;
  700. g.FindFiles(expr, &globMessages);
  701. if (!globMessages.empty()) {
  702. bool shouldExit = false;
  703. for (cmsys::Glob::Message const& globMessage : globMessages) {
  704. if (globMessage.type == cmsys::Glob::cyclicRecursion) {
  705. status.GetMakefile().IssueMessage(
  706. MessageType::AUTHOR_WARNING,
  707. "Cyclic recursion detected while globbing for '" + *i + "':\n" +
  708. globMessage.content);
  709. } else if (globMessage.type == cmsys::Glob::error) {
  710. status.GetMakefile().IssueMessage(
  711. MessageType::FATAL_ERROR,
  712. "Error has occurred while globbing for '" + *i + "' - " +
  713. globMessage.content);
  714. shouldExit = true;
  715. } else if (cm->GetDebugOutput() || cm->GetTrace()) {
  716. status.GetMakefile().IssueMessage(
  717. MessageType::LOG,
  718. cmStrCat("Globbing for\n ", *i, "\nEncountered an error:\n ",
  719. globMessage.content));
  720. }
  721. }
  722. if (shouldExit) {
  723. return false;
  724. }
  725. }
  726. if (recurse && !explicitFollowSymlinks &&
  727. g.GetFollowedSymlinkCount() != 0) {
  728. warnFollowedSymlinks = true;
  729. }
  730. std::vector<std::string>& foundFiles = g.GetFiles();
  731. cm::append(files, foundFiles);
  732. if (configureDepends) {
  733. std::sort(foundFiles.begin(), foundFiles.end());
  734. foundFiles.erase(std::unique(foundFiles.begin(), foundFiles.end()),
  735. foundFiles.end());
  736. cm->AddGlobCacheEntry(
  737. recurse, (recurse ? g.GetRecurseListDirs() : g.GetListDirs()),
  738. (recurse ? g.GetRecurseThroughSymlinks() : false),
  739. (g.GetRelative() ? g.GetRelative() : ""), expr, foundFiles, variable,
  740. status.GetMakefile().GetBacktrace());
  741. } else {
  742. warnConfigureLate = true;
  743. }
  744. ++i;
  745. }
  746. }
  747. switch (policyStatus) {
  748. case cmPolicies::REQUIRED_IF_USED:
  749. case cmPolicies::REQUIRED_ALWAYS:
  750. case cmPolicies::NEW:
  751. // Correct behavior, yay!
  752. break;
  753. case cmPolicies::OLD:
  754. // Probably not really the expected behavior, but the author explicitly
  755. // asked for the old behavior... no warning.
  756. case cmPolicies::WARN:
  757. // Possibly unexpected old behavior *and* we actually traversed
  758. // symlinks without being explicitly asked to: warn the author.
  759. if (warnFollowedSymlinks) {
  760. status.GetMakefile().IssueMessage(
  761. MessageType::AUTHOR_WARNING,
  762. cmPolicies::GetPolicyWarning(cmPolicies::CMP0009));
  763. }
  764. break;
  765. }
  766. std::sort(files.begin(), files.end());
  767. files.erase(std::unique(files.begin(), files.end()), files.end());
  768. status.GetMakefile().AddDefinition(variable, cmJoin(files, ";"));
  769. return true;
  770. }
  771. bool HandleGlobCommand(std::vector<std::string> const& args,
  772. cmExecutionStatus& status)
  773. {
  774. return HandleGlobImpl(args, false, status);
  775. }
  776. bool HandleGlobRecurseCommand(std::vector<std::string> const& args,
  777. cmExecutionStatus& status)
  778. {
  779. return HandleGlobImpl(args, true, status);
  780. }
  781. bool HandleMakeDirectoryCommand(std::vector<std::string> const& args,
  782. cmExecutionStatus& status)
  783. {
  784. // File command has at least one argument
  785. assert(args.size() > 1);
  786. std::string expr;
  787. for (std::string const& arg :
  788. cmMakeRange(args).advance(1)) // Get rid of subcommand
  789. {
  790. const std::string* cdir = &arg;
  791. if (!cmsys::SystemTools::FileIsFullPath(arg)) {
  792. expr =
  793. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  794. cdir = &expr;
  795. }
  796. if (!status.GetMakefile().CanIWriteThisFile(*cdir)) {
  797. std::string e = "attempted to create a directory: " + *cdir +
  798. " into a source directory.";
  799. status.SetError(e);
  800. cmSystemTools::SetFatalErrorOccured();
  801. return false;
  802. }
  803. if (!cmSystemTools::MakeDirectory(*cdir)) {
  804. std::string error = "problem creating directory: " + *cdir;
  805. status.SetError(error);
  806. return false;
  807. }
  808. }
  809. return true;
  810. }
  811. bool HandleTouchImpl(std::vector<std::string> const& args, bool create,
  812. cmExecutionStatus& status)
  813. {
  814. // File command has at least one argument
  815. assert(args.size() > 1);
  816. for (std::string const& arg :
  817. cmMakeRange(args).advance(1)) // Get rid of subcommand
  818. {
  819. std::string tfile = arg;
  820. if (!cmsys::SystemTools::FileIsFullPath(tfile)) {
  821. tfile =
  822. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  823. }
  824. if (!status.GetMakefile().CanIWriteThisFile(tfile)) {
  825. std::string e =
  826. "attempted to touch a file: " + tfile + " in a source directory.";
  827. status.SetError(e);
  828. cmSystemTools::SetFatalErrorOccured();
  829. return false;
  830. }
  831. if (!cmSystemTools::Touch(tfile, create)) {
  832. std::string error = "problem touching file: " + tfile;
  833. status.SetError(error);
  834. return false;
  835. }
  836. }
  837. return true;
  838. }
  839. bool HandleTouchCommand(std::vector<std::string> const& args,
  840. cmExecutionStatus& status)
  841. {
  842. return HandleTouchImpl(args, true, status);
  843. }
  844. bool HandleTouchNocreateCommand(std::vector<std::string> const& args,
  845. cmExecutionStatus& status)
  846. {
  847. return HandleTouchImpl(args, false, status);
  848. }
  849. bool HandleDifferentCommand(std::vector<std::string> const& args,
  850. cmExecutionStatus& status)
  851. {
  852. /*
  853. FILE(DIFFERENT <variable> FILES <lhs> <rhs>)
  854. */
  855. // Evaluate arguments.
  856. const char* file_lhs = nullptr;
  857. const char* file_rhs = nullptr;
  858. const char* var = nullptr;
  859. enum Doing
  860. {
  861. DoingNone,
  862. DoingVar,
  863. DoingFileLHS,
  864. DoingFileRHS
  865. };
  866. Doing doing = DoingVar;
  867. for (unsigned int i = 1; i < args.size(); ++i) {
  868. if (args[i] == "FILES") {
  869. doing = DoingFileLHS;
  870. } else if (doing == DoingVar) {
  871. var = args[i].c_str();
  872. doing = DoingNone;
  873. } else if (doing == DoingFileLHS) {
  874. file_lhs = args[i].c_str();
  875. doing = DoingFileRHS;
  876. } else if (doing == DoingFileRHS) {
  877. file_rhs = args[i].c_str();
  878. doing = DoingNone;
  879. } else {
  880. status.SetError(cmStrCat("DIFFERENT given unknown argument ", args[i]));
  881. return false;
  882. }
  883. }
  884. if (!var) {
  885. status.SetError("DIFFERENT not given result variable name.");
  886. return false;
  887. }
  888. if (!file_lhs || !file_rhs) {
  889. status.SetError("DIFFERENT not given FILES option with two file names.");
  890. return false;
  891. }
  892. // Compare the files.
  893. const char* result =
  894. cmSystemTools::FilesDiffer(file_lhs, file_rhs) ? "1" : "0";
  895. status.GetMakefile().AddDefinition(var, result);
  896. return true;
  897. }
  898. bool HandleCopyCommand(std::vector<std::string> const& args,
  899. cmExecutionStatus& status)
  900. {
  901. cmFileCopier copier(status);
  902. return copier.Run(args);
  903. }
  904. bool HandleRPathChangeCommand(std::vector<std::string> const& args,
  905. cmExecutionStatus& status)
  906. {
  907. // Evaluate arguments.
  908. std::string file;
  909. const char* oldRPath = nullptr;
  910. const char* newRPath = nullptr;
  911. bool removeEnvironmentRPath = false;
  912. enum Doing
  913. {
  914. DoingNone,
  915. DoingFile,
  916. DoingOld,
  917. DoingNew
  918. };
  919. Doing doing = DoingNone;
  920. for (unsigned int i = 1; i < args.size(); ++i) {
  921. if (args[i] == "OLD_RPATH") {
  922. doing = DoingOld;
  923. } else if (args[i] == "NEW_RPATH") {
  924. doing = DoingNew;
  925. } else if (args[i] == "FILE") {
  926. doing = DoingFile;
  927. } else if (args[i] == "INSTALL_REMOVE_ENVIRONMENT_RPATH") {
  928. removeEnvironmentRPath = true;
  929. } else if (doing == DoingFile) {
  930. file = args[i];
  931. doing = DoingNone;
  932. } else if (doing == DoingOld) {
  933. oldRPath = args[i].c_str();
  934. doing = DoingNone;
  935. } else if (doing == DoingNew) {
  936. newRPath = args[i].c_str();
  937. doing = DoingNone;
  938. } else {
  939. status.SetError(
  940. cmStrCat("RPATH_CHANGE given unknown argument ", args[i]));
  941. return false;
  942. }
  943. }
  944. if (file.empty()) {
  945. status.SetError("RPATH_CHANGE not given FILE option.");
  946. return false;
  947. }
  948. if (!oldRPath) {
  949. status.SetError("RPATH_CHANGE not given OLD_RPATH option.");
  950. return false;
  951. }
  952. if (!newRPath) {
  953. status.SetError("RPATH_CHANGE not given NEW_RPATH option.");
  954. return false;
  955. }
  956. if (!cmSystemTools::FileExists(file, true)) {
  957. status.SetError(
  958. cmStrCat("RPATH_CHANGE given FILE \"", file, "\" that does not exist."));
  959. return false;
  960. }
  961. bool success = true;
  962. cmFileTimes const ft(file);
  963. std::string emsg;
  964. bool changed;
  965. if (!cmSystemTools::ChangeRPath(file, oldRPath, newRPath,
  966. removeEnvironmentRPath, &emsg, &changed)) {
  967. status.SetError(cmStrCat("RPATH_CHANGE could not write new RPATH:\n ",
  968. newRPath, "\nto the file:\n ", file, "\n",
  969. emsg));
  970. success = false;
  971. }
  972. if (success) {
  973. if (changed) {
  974. std::string message =
  975. cmStrCat("Set runtime path of \"", file, "\" to \"", newRPath, '"');
  976. status.GetMakefile().DisplayStatus(message, -1);
  977. }
  978. ft.Store(file);
  979. }
  980. return success;
  981. }
  982. bool HandleRPathRemoveCommand(std::vector<std::string> const& args,
  983. cmExecutionStatus& status)
  984. {
  985. // Evaluate arguments.
  986. std::string file;
  987. enum Doing
  988. {
  989. DoingNone,
  990. DoingFile
  991. };
  992. Doing doing = DoingNone;
  993. for (unsigned int i = 1; i < args.size(); ++i) {
  994. if (args[i] == "FILE") {
  995. doing = DoingFile;
  996. } else if (doing == DoingFile) {
  997. file = args[i];
  998. doing = DoingNone;
  999. } else {
  1000. status.SetError(
  1001. cmStrCat("RPATH_REMOVE given unknown argument ", args[i]));
  1002. return false;
  1003. }
  1004. }
  1005. if (file.empty()) {
  1006. status.SetError("RPATH_REMOVE not given FILE option.");
  1007. return false;
  1008. }
  1009. if (!cmSystemTools::FileExists(file, true)) {
  1010. status.SetError(
  1011. cmStrCat("RPATH_REMOVE given FILE \"", file, "\" that does not exist."));
  1012. return false;
  1013. }
  1014. bool success = true;
  1015. cmFileTimes const ft(file);
  1016. std::string emsg;
  1017. bool removed;
  1018. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  1019. status.SetError(
  1020. cmStrCat("RPATH_REMOVE could not remove RPATH from file: \n ", file,
  1021. "\n", emsg));
  1022. success = false;
  1023. }
  1024. if (success) {
  1025. if (removed) {
  1026. std::string message =
  1027. cmStrCat("Removed runtime path from \"", file, '"');
  1028. status.GetMakefile().DisplayStatus(message, -1);
  1029. }
  1030. ft.Store(file);
  1031. }
  1032. return success;
  1033. }
  1034. bool HandleRPathCheckCommand(std::vector<std::string> const& args,
  1035. cmExecutionStatus& status)
  1036. {
  1037. // Evaluate arguments.
  1038. std::string file;
  1039. const char* rpath = nullptr;
  1040. enum Doing
  1041. {
  1042. DoingNone,
  1043. DoingFile,
  1044. DoingRPath
  1045. };
  1046. Doing doing = DoingNone;
  1047. for (unsigned int i = 1; i < args.size(); ++i) {
  1048. if (args[i] == "RPATH") {
  1049. doing = DoingRPath;
  1050. } else if (args[i] == "FILE") {
  1051. doing = DoingFile;
  1052. } else if (doing == DoingFile) {
  1053. file = args[i];
  1054. doing = DoingNone;
  1055. } else if (doing == DoingRPath) {
  1056. rpath = args[i].c_str();
  1057. doing = DoingNone;
  1058. } else {
  1059. status.SetError(
  1060. cmStrCat("RPATH_CHECK given unknown argument ", args[i]));
  1061. return false;
  1062. }
  1063. }
  1064. if (file.empty()) {
  1065. status.SetError("RPATH_CHECK not given FILE option.");
  1066. return false;
  1067. }
  1068. if (!rpath) {
  1069. status.SetError("RPATH_CHECK not given RPATH option.");
  1070. return false;
  1071. }
  1072. // If the file exists but does not have the desired RPath then
  1073. // delete it. This is used during installation to re-install a file
  1074. // if its RPath will change.
  1075. if (cmSystemTools::FileExists(file, true) &&
  1076. !cmSystemTools::CheckRPath(file, rpath)) {
  1077. cmSystemTools::RemoveFile(file);
  1078. }
  1079. return true;
  1080. }
  1081. bool HandleReadElfCommand(std::vector<std::string> const& args,
  1082. cmExecutionStatus& status)
  1083. {
  1084. if (args.size() < 4) {
  1085. status.SetError("READ_ELF must be called with at least three additional "
  1086. "arguments.");
  1087. return false;
  1088. }
  1089. std::string const& fileNameArg = args[1];
  1090. struct Arguments
  1091. {
  1092. std::string RPath;
  1093. std::string RunPath;
  1094. std::string Error;
  1095. };
  1096. static auto const parser = cmArgumentParser<Arguments>{}
  1097. .Bind("RPATH"_s, &Arguments::RPath)
  1098. .Bind("RUNPATH"_s, &Arguments::RunPath)
  1099. .Bind("CAPTURE_ERROR"_s, &Arguments::Error);
  1100. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(2));
  1101. if (!cmSystemTools::FileExists(fileNameArg, true)) {
  1102. status.SetError(cmStrCat("READ_ELF given FILE \"", fileNameArg,
  1103. "\" that does not exist."));
  1104. return false;
  1105. }
  1106. #if defined(CMAKE_USE_ELF_PARSER)
  1107. cmELF elf(fileNameArg.c_str());
  1108. if (!arguments.RPath.empty()) {
  1109. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  1110. std::string rpath(se_rpath->Value);
  1111. std::replace(rpath.begin(), rpath.end(), ':', ';');
  1112. status.GetMakefile().AddDefinition(arguments.RPath, rpath);
  1113. }
  1114. }
  1115. if (!arguments.RunPath.empty()) {
  1116. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  1117. std::string runpath(se_runpath->Value);
  1118. std::replace(runpath.begin(), runpath.end(), ':', ';');
  1119. status.GetMakefile().AddDefinition(arguments.RunPath, runpath);
  1120. }
  1121. }
  1122. return true;
  1123. #else
  1124. std::string error = "ELF parser not available on this platform.";
  1125. if (arguments.Error.empty()) {
  1126. status.SetError(error);
  1127. return false;
  1128. }
  1129. status.GetMakefile().AddDefinition(arguments.Error, error);
  1130. return true;
  1131. #endif
  1132. }
  1133. bool HandleInstallCommand(std::vector<std::string> const& args,
  1134. cmExecutionStatus& status)
  1135. {
  1136. cmFileInstaller installer(status);
  1137. return installer.Run(args);
  1138. }
  1139. bool HandleRealPathCommand(std::vector<std::string> const& args,
  1140. cmExecutionStatus& status)
  1141. {
  1142. if (args.size() < 3) {
  1143. status.SetError("REAL_PATH requires a path and an output variable");
  1144. return false;
  1145. }
  1146. struct Arguments
  1147. {
  1148. std::string BaseDirectory;
  1149. };
  1150. static auto const parser = cmArgumentParser<Arguments>{}.Bind(
  1151. "BASE_DIRECTORY"_s, &Arguments::BaseDirectory);
  1152. std::vector<std::string> unparsedArguments;
  1153. std::vector<std::string> keywordsMissingValue;
  1154. std::vector<std::string> parsedKeywords;
  1155. auto arguments =
  1156. parser.Parse(cmMakeRange(args).advance(3), &unparsedArguments,
  1157. &keywordsMissingValue, &parsedKeywords);
  1158. if (!unparsedArguments.empty()) {
  1159. status.SetError("REAL_PATH called with unexpected arguments");
  1160. return false;
  1161. }
  1162. if (!keywordsMissingValue.empty()) {
  1163. status.SetError("BASE_DIRECTORY requires a value");
  1164. return false;
  1165. }
  1166. if (parsedKeywords.empty()) {
  1167. arguments.BaseDirectory = status.GetMakefile().GetCurrentSourceDirectory();
  1168. }
  1169. cmCMakePath path(args[1]);
  1170. path = path.Absolute(arguments.BaseDirectory).Normal();
  1171. auto realPath = cmSystemTools::GetRealPath(path.GenericString());
  1172. status.GetMakefile().AddDefinition(args[2], realPath);
  1173. return true;
  1174. }
  1175. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1176. cmExecutionStatus& status)
  1177. {
  1178. if (args.size() != 4) {
  1179. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1180. return false;
  1181. }
  1182. const std::string& outVar = args[1];
  1183. const std::string& directoryName = args[2];
  1184. const std::string& fileName = args[3];
  1185. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1186. std::string errstring =
  1187. "RELATIVE_PATH must be passed a full path to the directory: " +
  1188. directoryName;
  1189. status.SetError(errstring);
  1190. return false;
  1191. }
  1192. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1193. std::string errstring =
  1194. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1195. status.SetError(errstring);
  1196. return false;
  1197. }
  1198. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1199. status.GetMakefile().AddDefinition(outVar, res);
  1200. return true;
  1201. }
  1202. bool HandleRename(std::vector<std::string> const& args,
  1203. cmExecutionStatus& status)
  1204. {
  1205. if (args.size() != 3) {
  1206. status.SetError("RENAME given incorrect number of arguments.");
  1207. return false;
  1208. }
  1209. // Compute full path for old and new names.
  1210. std::string oldname = args[1];
  1211. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1212. oldname =
  1213. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1214. }
  1215. std::string newname = args[2];
  1216. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1217. newname =
  1218. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1219. }
  1220. if (!cmSystemTools::RenameFile(oldname, newname)) {
  1221. std::string err = cmSystemTools::GetLastSystemError();
  1222. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname,
  1223. "\nto\n ", newname, "\nbecause: ", err, "\n"));
  1224. return false;
  1225. }
  1226. return true;
  1227. }
  1228. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1229. cmExecutionStatus& status)
  1230. {
  1231. std::string message;
  1232. for (std::string const& arg :
  1233. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1234. {
  1235. std::string fileName = arg;
  1236. if (fileName.empty()) {
  1237. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1238. status.GetMakefile().IssueMessage(
  1239. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1240. continue;
  1241. }
  1242. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1243. fileName =
  1244. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1245. }
  1246. if (cmSystemTools::FileIsDirectory(fileName) &&
  1247. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1248. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1249. } else {
  1250. cmSystemTools::RemoveFile(fileName);
  1251. }
  1252. }
  1253. return true;
  1254. }
  1255. bool HandleRemove(std::vector<std::string> const& args,
  1256. cmExecutionStatus& status)
  1257. {
  1258. return HandleRemoveImpl(args, false, status);
  1259. }
  1260. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1261. cmExecutionStatus& status)
  1262. {
  1263. return HandleRemoveImpl(args, true, status);
  1264. }
  1265. std::string ToNativePath(const std::string& path)
  1266. {
  1267. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1268. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1269. outPath.back() == '\"') {
  1270. return outPath.substr(1, outPath.size() - 2);
  1271. }
  1272. return outPath;
  1273. }
  1274. std::string ToCMakePath(const std::string& path)
  1275. {
  1276. auto temp = path;
  1277. cmSystemTools::ConvertToUnixSlashes(temp);
  1278. return temp;
  1279. }
  1280. bool HandlePathCommand(std::vector<std::string> const& args,
  1281. std::string (*convert)(std::string const&),
  1282. cmExecutionStatus& status)
  1283. {
  1284. if (args.size() != 3) {
  1285. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1286. "called with exactly three arguments.");
  1287. return false;
  1288. }
  1289. #if defined(_WIN32) && !defined(__CYGWIN__)
  1290. char pathSep = ';';
  1291. #else
  1292. char pathSep = ':';
  1293. #endif
  1294. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1295. std::string value = cmJoin(cmMakeRange(path).transform(convert), ";");
  1296. status.GetMakefile().AddDefinition(args[2], value);
  1297. return true;
  1298. }
  1299. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1300. cmExecutionStatus& status)
  1301. {
  1302. return HandlePathCommand(args, ToCMakePath, status);
  1303. }
  1304. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1305. cmExecutionStatus& status)
  1306. {
  1307. return HandlePathCommand(args, ToNativePath, status);
  1308. }
  1309. #if !defined(CMAKE_BOOTSTRAP)
  1310. // Stuff for curl download/upload
  1311. using cmFileCommandVectorOfChar = std::vector<char>;
  1312. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1313. {
  1314. int realsize = static_cast<int>(size * nmemb);
  1315. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1316. if (fout) {
  1317. const char* chPtr = static_cast<char*>(ptr);
  1318. fout->write(chPtr, realsize);
  1319. }
  1320. return realsize;
  1321. }
  1322. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1323. void* data)
  1324. {
  1325. int realsize = static_cast<int>(size * nmemb);
  1326. const char* chPtr = static_cast<char*>(ptr);
  1327. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1328. chPtr + realsize);
  1329. return realsize;
  1330. }
  1331. size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1332. size_t size, void* data)
  1333. {
  1334. cmFileCommandVectorOfChar& vec =
  1335. *static_cast<cmFileCommandVectorOfChar*>(data);
  1336. switch (type) {
  1337. case CURLINFO_TEXT:
  1338. case CURLINFO_HEADER_IN:
  1339. case CURLINFO_HEADER_OUT:
  1340. cm::append(vec, chPtr, chPtr + size);
  1341. break;
  1342. case CURLINFO_DATA_IN:
  1343. case CURLINFO_DATA_OUT:
  1344. case CURLINFO_SSL_DATA_IN:
  1345. case CURLINFO_SSL_DATA_OUT: {
  1346. char buf[128];
  1347. int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1348. static_cast<KWIML_INT_uint64_t>(size));
  1349. if (n > 0) {
  1350. cm::append(vec, buf, buf + n);
  1351. }
  1352. } break;
  1353. default:
  1354. break;
  1355. }
  1356. return 0;
  1357. }
  1358. class cURLProgressHelper
  1359. {
  1360. public:
  1361. cURLProgressHelper(cmMakefile* mf, const char* text)
  1362. : Makefile(mf)
  1363. , Text(text)
  1364. {
  1365. }
  1366. bool UpdatePercentage(double value, double total, std::string& status)
  1367. {
  1368. long OldPercentage = this->CurrentPercentage;
  1369. if (total > 0.0) {
  1370. this->CurrentPercentage = std::lround(value / total * 100.0);
  1371. if (this->CurrentPercentage > 100) {
  1372. // Avoid extra progress reports for unexpected data beyond total.
  1373. this->CurrentPercentage = 100;
  1374. }
  1375. }
  1376. bool updated = (OldPercentage != this->CurrentPercentage);
  1377. if (updated) {
  1378. status =
  1379. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1380. }
  1381. return updated;
  1382. }
  1383. cmMakefile* GetMakefile() { return this->Makefile; }
  1384. private:
  1385. long CurrentPercentage = -1;
  1386. cmMakefile* Makefile;
  1387. std::string Text;
  1388. };
  1389. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1390. double ultotal, double ulnow)
  1391. {
  1392. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1393. static_cast<void>(ultotal);
  1394. static_cast<void>(ulnow);
  1395. std::string status;
  1396. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1397. cmMakefile* mf = helper->GetMakefile();
  1398. mf->DisplayStatus(status, -1);
  1399. }
  1400. return 0;
  1401. }
  1402. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1403. double ultotal, double ulnow)
  1404. {
  1405. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1406. static_cast<void>(dltotal);
  1407. static_cast<void>(dlnow);
  1408. std::string status;
  1409. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1410. cmMakefile* mf = helper->GetMakefile();
  1411. mf->DisplayStatus(status, -1);
  1412. }
  1413. return 0;
  1414. }
  1415. class cURLEasyGuard
  1416. {
  1417. public:
  1418. cURLEasyGuard(CURL* easy)
  1419. : Easy(easy)
  1420. {
  1421. }
  1422. ~cURLEasyGuard()
  1423. {
  1424. if (this->Easy) {
  1425. ::curl_easy_cleanup(this->Easy);
  1426. }
  1427. }
  1428. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1429. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1430. void release() { this->Easy = nullptr; }
  1431. private:
  1432. ::CURL* Easy;
  1433. };
  1434. #endif
  1435. #define check_curl_result(result, errstr) \
  1436. do { \
  1437. if (result != CURLE_OK) { \
  1438. std::string e(errstr); \
  1439. e += ::curl_easy_strerror(result); \
  1440. status.SetError(e); \
  1441. return false; \
  1442. } \
  1443. } while (false)
  1444. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1445. cmExecutionStatus& status)
  1446. {
  1447. #if !defined(CMAKE_BOOTSTRAP)
  1448. auto i = args.begin();
  1449. if (args.size() < 2) {
  1450. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1451. return false;
  1452. }
  1453. ++i; // Get rid of subcommand
  1454. std::string url = *i;
  1455. ++i;
  1456. std::string file;
  1457. long timeout = 0;
  1458. long inactivity_timeout = 0;
  1459. std::string logVar;
  1460. std::string statusVar;
  1461. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1462. cmProp cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1463. std::string netrc_level =
  1464. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1465. std::string netrc_file =
  1466. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1467. std::string expectedHash;
  1468. std::string hashMatchMSG;
  1469. std::unique_ptr<cmCryptoHash> hash;
  1470. bool showProgress = false;
  1471. std::string userpwd;
  1472. std::vector<std::string> curl_headers;
  1473. while (i != args.end()) {
  1474. if (*i == "TIMEOUT") {
  1475. ++i;
  1476. if (i != args.end()) {
  1477. timeout = atol(i->c_str());
  1478. } else {
  1479. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1480. return false;
  1481. }
  1482. } else if (*i == "INACTIVITY_TIMEOUT") {
  1483. ++i;
  1484. if (i != args.end()) {
  1485. inactivity_timeout = atol(i->c_str());
  1486. } else {
  1487. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1488. return false;
  1489. }
  1490. } else if (*i == "LOG") {
  1491. ++i;
  1492. if (i == args.end()) {
  1493. status.SetError("DOWNLOAD missing VAR for LOG.");
  1494. return false;
  1495. }
  1496. logVar = *i;
  1497. } else if (*i == "STATUS") {
  1498. ++i;
  1499. if (i == args.end()) {
  1500. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1501. return false;
  1502. }
  1503. statusVar = *i;
  1504. } else if (*i == "TLS_VERIFY") {
  1505. ++i;
  1506. if (i != args.end()) {
  1507. tls_verify = cmIsOn(*i);
  1508. } else {
  1509. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1510. return false;
  1511. }
  1512. } else if (*i == "TLS_CAINFO") {
  1513. ++i;
  1514. if (i != args.end()) {
  1515. cainfo = &(*i);
  1516. } else {
  1517. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1518. return false;
  1519. }
  1520. } else if (*i == "NETRC_FILE") {
  1521. ++i;
  1522. if (i != args.end()) {
  1523. netrc_file = *i;
  1524. } else {
  1525. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1526. return false;
  1527. }
  1528. } else if (*i == "NETRC") {
  1529. ++i;
  1530. if (i != args.end()) {
  1531. netrc_level = *i;
  1532. } else {
  1533. status.SetError("DOWNLOAD missing level value for NETRC.");
  1534. return false;
  1535. }
  1536. } else if (*i == "EXPECTED_MD5") {
  1537. ++i;
  1538. if (i == args.end()) {
  1539. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1540. return false;
  1541. }
  1542. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1543. hashMatchMSG = "MD5 sum";
  1544. expectedHash = cmSystemTools::LowerCase(*i);
  1545. } else if (*i == "SHOW_PROGRESS") {
  1546. showProgress = true;
  1547. } else if (*i == "EXPECTED_HASH") {
  1548. ++i;
  1549. if (i == args.end()) {
  1550. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1551. return false;
  1552. }
  1553. std::string::size_type pos = i->find("=");
  1554. if (pos == std::string::npos) {
  1555. std::string err =
  1556. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1557. status.SetError(err);
  1558. return false;
  1559. }
  1560. std::string algo = i->substr(0, pos);
  1561. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1562. hash = std::unique_ptr<cmCryptoHash>(cmCryptoHash::New(algo));
  1563. if (!hash) {
  1564. std::string err =
  1565. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1566. status.SetError(err);
  1567. return false;
  1568. }
  1569. hashMatchMSG = algo + " hash";
  1570. } else if (*i == "USERPWD") {
  1571. ++i;
  1572. if (i == args.end()) {
  1573. status.SetError("DOWNLOAD missing string for USERPWD.");
  1574. return false;
  1575. }
  1576. userpwd = *i;
  1577. } else if (*i == "HTTPHEADER") {
  1578. ++i;
  1579. if (i == args.end()) {
  1580. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1581. return false;
  1582. }
  1583. curl_headers.push_back(*i);
  1584. } else if (file.empty()) {
  1585. file = *i;
  1586. } else {
  1587. // Do not return error for compatibility reason.
  1588. std::string err = cmStrCat("Unexpected argument: ", *i);
  1589. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1590. }
  1591. ++i;
  1592. }
  1593. // Can't calculate hash if we don't save the file.
  1594. // TODO Incrementally calculate hash in the write callback as the file is
  1595. // being downloaded so this check can be relaxed.
  1596. if (file.empty() && hash) {
  1597. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1598. return false;
  1599. }
  1600. // If file exists already, and caller specified an expected md5 or sha,
  1601. // and the existing file already has the expected hash, then simply
  1602. // return.
  1603. //
  1604. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1605. std::string msg;
  1606. std::string actualHash = hash->HashFile(file);
  1607. if (actualHash == expectedHash) {
  1608. msg = cmStrCat("returning early; file already exists with expected ",
  1609. hashMatchMSG, '"');
  1610. if (!statusVar.empty()) {
  1611. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1612. }
  1613. return true;
  1614. }
  1615. }
  1616. // Make sure parent directory exists so we can write to the file
  1617. // as we receive downloaded bits from curl...
  1618. //
  1619. if (!file.empty()) {
  1620. std::string dir = cmSystemTools::GetFilenamePath(file);
  1621. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1622. !cmSystemTools::MakeDirectory(dir)) {
  1623. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1624. dir +
  1625. "' - Specify file by full path name and verify that you "
  1626. "have directory creation and file write privileges.";
  1627. status.SetError(errstring);
  1628. return false;
  1629. }
  1630. }
  1631. cmsys::ofstream fout;
  1632. if (!file.empty()) {
  1633. fout.open(file.c_str(), std::ios::binary);
  1634. if (!fout) {
  1635. status.SetError("DOWNLOAD cannot open file for write.");
  1636. return false;
  1637. }
  1638. }
  1639. # if defined(_WIN32)
  1640. url = fix_file_url_windows(url);
  1641. # endif
  1642. ::CURL* curl;
  1643. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1644. curl = ::curl_easy_init();
  1645. if (!curl) {
  1646. status.SetError("DOWNLOAD error initializing curl.");
  1647. return false;
  1648. }
  1649. cURLEasyGuard g_curl(curl);
  1650. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1651. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1652. // enable HTTP ERROR parsing
  1653. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1654. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1655. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1656. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1657. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1658. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1659. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1660. cmFileCommandCurlDebugCallback);
  1661. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1662. // check to see if TLS verification is requested
  1663. if (tls_verify) {
  1664. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1665. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  1666. } else {
  1667. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1668. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  1669. }
  1670. // check to see if a CAINFO file has been specified
  1671. // command arg comes first
  1672. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cmToCStr(cainfo));
  1673. if (!cainfo_err.empty()) {
  1674. status.SetError(cainfo_err);
  1675. return false;
  1676. }
  1677. // check to see if netrc parameters have been specified
  1678. // local command args takes precedence over CMAKE_NETRC*
  1679. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1680. std::string const& netrc_option_err =
  1681. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1682. if (!netrc_option_err.empty()) {
  1683. status.SetError(netrc_option_err);
  1684. return false;
  1685. }
  1686. cmFileCommandVectorOfChar chunkDebug;
  1687. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  1688. file.empty() ? nullptr : &fout);
  1689. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1690. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1691. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1692. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1693. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1694. if (!logVar.empty()) {
  1695. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1696. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1697. }
  1698. if (timeout > 0) {
  1699. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1700. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1701. }
  1702. if (inactivity_timeout > 0) {
  1703. // Give up if there is no progress for a long time.
  1704. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1705. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1706. }
  1707. // Need the progress helper's scope to last through the duration of
  1708. // the curl_easy_perform call... so this object is declared at function
  1709. // scope intentionally, rather than inside the "if(showProgress)"
  1710. // block...
  1711. //
  1712. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1713. if (showProgress) {
  1714. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1715. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1716. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1717. cmFileDownloadProgressCallback);
  1718. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1719. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1720. reinterpret_cast<void*>(&helper));
  1721. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1722. }
  1723. if (!userpwd.empty()) {
  1724. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1725. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1726. }
  1727. struct curl_slist* headers = nullptr;
  1728. for (std::string const& h : curl_headers) {
  1729. headers = ::curl_slist_append(headers, h.c_str());
  1730. }
  1731. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1732. res = ::curl_easy_perform(curl);
  1733. ::curl_slist_free_all(headers);
  1734. /* always cleanup */
  1735. g_curl.release();
  1736. ::curl_easy_cleanup(curl);
  1737. if (!statusVar.empty()) {
  1738. status.GetMakefile().AddDefinition(
  1739. statusVar,
  1740. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1741. }
  1742. ::curl_global_cleanup();
  1743. // Explicitly flush/close so we can measure the md5 accurately.
  1744. //
  1745. if (!file.empty()) {
  1746. fout.flush();
  1747. fout.close();
  1748. }
  1749. // Verify MD5 sum if requested:
  1750. //
  1751. if (hash) {
  1752. std::string actualHash = hash->HashFile(file);
  1753. if (actualHash.empty()) {
  1754. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1755. return false;
  1756. }
  1757. if (expectedHash != actualHash) {
  1758. if (!statusVar.empty() && res == 0) {
  1759. status.GetMakefile().AddDefinition(statusVar,
  1760. "1;HASH mismatch: "
  1761. "expected: " +
  1762. expectedHash +
  1763. " actual: " + actualHash);
  1764. }
  1765. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  1766. " for file: [",
  1767. file,
  1768. "]\n"
  1769. " expected hash: [",
  1770. expectedHash,
  1771. "]\n"
  1772. " actual hash: [",
  1773. actualHash,
  1774. "]\n"
  1775. " status: [",
  1776. static_cast<int>(res), ";\"",
  1777. ::curl_easy_strerror(res), "\"]\n"));
  1778. return false;
  1779. }
  1780. }
  1781. if (!logVar.empty()) {
  1782. chunkDebug.push_back(0);
  1783. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1784. }
  1785. return true;
  1786. #else
  1787. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  1788. return false;
  1789. #endif
  1790. }
  1791. bool HandleUploadCommand(std::vector<std::string> const& args,
  1792. cmExecutionStatus& status)
  1793. {
  1794. #if !defined(CMAKE_BOOTSTRAP)
  1795. if (args.size() < 3) {
  1796. status.SetError("UPLOAD must be called with at least three arguments.");
  1797. return false;
  1798. }
  1799. auto i = args.begin();
  1800. ++i;
  1801. std::string filename = *i;
  1802. ++i;
  1803. std::string url = *i;
  1804. ++i;
  1805. long timeout = 0;
  1806. long inactivity_timeout = 0;
  1807. std::string logVar;
  1808. std::string statusVar;
  1809. bool showProgress = false;
  1810. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1811. cmProp cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1812. std::string userpwd;
  1813. std::string netrc_level =
  1814. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1815. std::string netrc_file =
  1816. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1817. std::vector<std::string> curl_headers;
  1818. while (i != args.end()) {
  1819. if (*i == "TIMEOUT") {
  1820. ++i;
  1821. if (i != args.end()) {
  1822. timeout = atol(i->c_str());
  1823. } else {
  1824. status.SetError("UPLOAD missing time for TIMEOUT.");
  1825. return false;
  1826. }
  1827. } else if (*i == "INACTIVITY_TIMEOUT") {
  1828. ++i;
  1829. if (i != args.end()) {
  1830. inactivity_timeout = atol(i->c_str());
  1831. } else {
  1832. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1833. return false;
  1834. }
  1835. } else if (*i == "LOG") {
  1836. ++i;
  1837. if (i == args.end()) {
  1838. status.SetError("UPLOAD missing VAR for LOG.");
  1839. return false;
  1840. }
  1841. logVar = *i;
  1842. } else if (*i == "STATUS") {
  1843. ++i;
  1844. if (i == args.end()) {
  1845. status.SetError("UPLOAD missing VAR for STATUS.");
  1846. return false;
  1847. }
  1848. statusVar = *i;
  1849. } else if (*i == "SHOW_PROGRESS") {
  1850. showProgress = true;
  1851. } else if (*i == "TLS_VERIFY") {
  1852. ++i;
  1853. if (i != args.end()) {
  1854. tls_verify = cmIsOn(*i);
  1855. } else {
  1856. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  1857. return false;
  1858. }
  1859. } else if (*i == "TLS_CAINFO") {
  1860. ++i;
  1861. if (i != args.end()) {
  1862. cainfo = &(*i);
  1863. } else {
  1864. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  1865. return false;
  1866. }
  1867. } else if (*i == "NETRC_FILE") {
  1868. ++i;
  1869. if (i != args.end()) {
  1870. netrc_file = *i;
  1871. } else {
  1872. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  1873. return false;
  1874. }
  1875. } else if (*i == "NETRC") {
  1876. ++i;
  1877. if (i != args.end()) {
  1878. netrc_level = *i;
  1879. } else {
  1880. status.SetError("UPLOAD missing level value for NETRC.");
  1881. return false;
  1882. }
  1883. } else if (*i == "USERPWD") {
  1884. ++i;
  1885. if (i == args.end()) {
  1886. status.SetError("UPLOAD missing string for USERPWD.");
  1887. return false;
  1888. }
  1889. userpwd = *i;
  1890. } else if (*i == "HTTPHEADER") {
  1891. ++i;
  1892. if (i == args.end()) {
  1893. status.SetError("UPLOAD missing string for HTTPHEADER.");
  1894. return false;
  1895. }
  1896. curl_headers.push_back(*i);
  1897. } else {
  1898. // Do not return error for compatibility reason.
  1899. std::string err = cmStrCat("Unexpected argument: ", *i);
  1900. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1901. }
  1902. ++i;
  1903. }
  1904. // Open file for reading:
  1905. //
  1906. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  1907. if (!fin) {
  1908. std::string errStr =
  1909. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  1910. status.SetError(errStr);
  1911. return false;
  1912. }
  1913. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  1914. # if defined(_WIN32)
  1915. url = fix_file_url_windows(url);
  1916. # endif
  1917. ::CURL* curl;
  1918. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1919. curl = ::curl_easy_init();
  1920. if (!curl) {
  1921. status.SetError("UPLOAD error initializing curl.");
  1922. fclose(fin);
  1923. return false;
  1924. }
  1925. cURLEasyGuard g_curl(curl);
  1926. // enable HTTP ERROR parsing
  1927. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1928. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  1929. // enable uploading
  1930. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  1931. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  1932. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1933. check_curl_result(res, "UPLOAD cannot set url: ");
  1934. res =
  1935. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  1936. check_curl_result(res, "UPLOAD cannot set write function: ");
  1937. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1938. cmFileCommandCurlDebugCallback);
  1939. check_curl_result(res, "UPLOAD cannot set debug function: ");
  1940. // check to see if TLS verification is requested
  1941. if (tls_verify) {
  1942. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1943. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  1944. } else {
  1945. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1946. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  1947. }
  1948. // check to see if a CAINFO file has been specified
  1949. // command arg comes first
  1950. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cmToCStr(cainfo));
  1951. if (!cainfo_err.empty()) {
  1952. status.SetError(cainfo_err);
  1953. return false;
  1954. }
  1955. cmFileCommandVectorOfChar chunkResponse;
  1956. cmFileCommandVectorOfChar chunkDebug;
  1957. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  1958. check_curl_result(res, "UPLOAD cannot set write data: ");
  1959. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1960. check_curl_result(res, "UPLOAD cannot set debug data: ");
  1961. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1962. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  1963. if (!logVar.empty()) {
  1964. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1965. check_curl_result(res, "UPLOAD cannot set verbose: ");
  1966. }
  1967. if (timeout > 0) {
  1968. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1969. check_curl_result(res, "UPLOAD cannot set timeout: ");
  1970. }
  1971. if (inactivity_timeout > 0) {
  1972. // Give up if there is no progress for a long time.
  1973. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1974. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1975. }
  1976. // Need the progress helper's scope to last through the duration of
  1977. // the curl_easy_perform call... so this object is declared at function
  1978. // scope intentionally, rather than inside the "if(showProgress)"
  1979. // block...
  1980. //
  1981. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  1982. if (showProgress) {
  1983. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1984. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  1985. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1986. cmFileUploadProgressCallback);
  1987. check_curl_result(res, "UPLOAD cannot set progress function: ");
  1988. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1989. reinterpret_cast<void*>(&helper));
  1990. check_curl_result(res, "UPLOAD cannot set progress data: ");
  1991. }
  1992. // now specify which file to upload
  1993. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  1994. check_curl_result(res, "UPLOAD cannot set input file: ");
  1995. // and give the size of the upload (optional)
  1996. res =
  1997. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  1998. check_curl_result(res, "UPLOAD cannot set input file size: ");
  1999. if (!userpwd.empty()) {
  2000. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2001. check_curl_result(res, "UPLOAD cannot set user password: ");
  2002. }
  2003. // check to see if netrc parameters have been specified
  2004. // local command args takes precedence over CMAKE_NETRC*
  2005. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2006. std::string const& netrc_option_err =
  2007. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2008. if (!netrc_option_err.empty()) {
  2009. status.SetError(netrc_option_err);
  2010. return false;
  2011. }
  2012. struct curl_slist* headers = nullptr;
  2013. for (std::string const& h : curl_headers) {
  2014. headers = ::curl_slist_append(headers, h.c_str());
  2015. }
  2016. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2017. res = ::curl_easy_perform(curl);
  2018. ::curl_slist_free_all(headers);
  2019. /* always cleanup */
  2020. g_curl.release();
  2021. ::curl_easy_cleanup(curl);
  2022. if (!statusVar.empty()) {
  2023. status.GetMakefile().AddDefinition(
  2024. statusVar,
  2025. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2026. }
  2027. ::curl_global_cleanup();
  2028. fclose(fin);
  2029. fin = nullptr;
  2030. if (!logVar.empty()) {
  2031. std::string log;
  2032. if (!chunkResponse.empty()) {
  2033. chunkResponse.push_back(0);
  2034. log += "Response:\n";
  2035. log += chunkResponse.data();
  2036. log += "\n";
  2037. }
  2038. if (!chunkDebug.empty()) {
  2039. chunkDebug.push_back(0);
  2040. log += "Debug:\n";
  2041. log += chunkDebug.data();
  2042. log += "\n";
  2043. }
  2044. status.GetMakefile().AddDefinition(logVar, log);
  2045. }
  2046. return true;
  2047. #else
  2048. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2049. return false;
  2050. #endif
  2051. }
  2052. void AddEvaluationFile(const std::string& inputName,
  2053. const std::string& targetName,
  2054. const std::string& outputExpr,
  2055. const std::string& condition, bool inputIsContent,
  2056. cmExecutionStatus& status)
  2057. {
  2058. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2059. cmGeneratorExpression outputGe(lfbt);
  2060. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2061. outputGe.Parse(outputExpr);
  2062. cmGeneratorExpression conditionGe(lfbt);
  2063. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2064. conditionGe.Parse(condition);
  2065. status.GetMakefile().AddEvaluationFile(
  2066. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2067. inputIsContent);
  2068. }
  2069. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2070. cmExecutionStatus& status)
  2071. {
  2072. if (args.size() < 5) {
  2073. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2074. return false;
  2075. }
  2076. struct Arguments
  2077. {
  2078. std::string Output;
  2079. std::string Input;
  2080. std::string Content;
  2081. std::string Condition;
  2082. std::string Target;
  2083. };
  2084. static auto const parser = cmArgumentParser<Arguments>{}
  2085. .Bind("OUTPUT"_s, &Arguments::Output)
  2086. .Bind("INPUT"_s, &Arguments::Input)
  2087. .Bind("CONTENT"_s, &Arguments::Content)
  2088. .Bind("CONDITION"_s, &Arguments::Condition)
  2089. .Bind("TARGET"_s, &Arguments::Target);
  2090. std::vector<std::string> unparsedArguments;
  2091. std::vector<std::string> keywordsMissingValues;
  2092. std::vector<std::string> parsedKeywords;
  2093. Arguments const arguments =
  2094. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments,
  2095. &keywordsMissingValues, &parsedKeywords);
  2096. if (!keywordsMissingValues.empty()) {
  2097. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2098. return false;
  2099. }
  2100. if (!unparsedArguments.empty()) {
  2101. status.SetError("Unknown argument to GENERATE subcommand.");
  2102. return false;
  2103. }
  2104. bool mandatoryOptionsSpecified = false;
  2105. if (parsedKeywords.size() > 1) {
  2106. const bool outputOprionSpecified = parsedKeywords[0] == "OUTPUT"_s;
  2107. const bool inputOrContentSpecified =
  2108. parsedKeywords[1] == "INPUT"_s || parsedKeywords[1] == "CONTENT"_s;
  2109. if (outputOprionSpecified && inputOrContentSpecified) {
  2110. mandatoryOptionsSpecified = true;
  2111. }
  2112. }
  2113. if (!mandatoryOptionsSpecified) {
  2114. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2115. return false;
  2116. }
  2117. const bool conditionOptionSpecified =
  2118. std::find(parsedKeywords.begin(), parsedKeywords.end(), "CONDITION"_s) !=
  2119. parsedKeywords.end();
  2120. if (conditionOptionSpecified && arguments.Condition.empty()) {
  2121. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2122. "if specified.");
  2123. return false;
  2124. }
  2125. const bool targetOptionSpecified =
  2126. std::find(parsedKeywords.begin(), parsedKeywords.end(), "TARGET"_s) !=
  2127. parsedKeywords.end();
  2128. if (targetOptionSpecified && arguments.Target.empty()) {
  2129. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2130. "if specified.");
  2131. return false;
  2132. }
  2133. const bool outputOptionSpecified =
  2134. std::find(parsedKeywords.begin(), parsedKeywords.end(), "OUTPUT"_s) !=
  2135. parsedKeywords.end();
  2136. if (outputOptionSpecified && parsedKeywords[0] != "OUTPUT"_s) {
  2137. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2138. return false;
  2139. }
  2140. const bool inputIsContent = parsedKeywords[1] != "INPUT"_s;
  2141. if (inputIsContent && parsedKeywords[1] != "CONTENT") {
  2142. status.SetError("Unknown argument to GENERATE subcommand.");
  2143. }
  2144. std::string input = arguments.Input;
  2145. if (inputIsContent) {
  2146. input = arguments.Content;
  2147. }
  2148. AddEvaluationFile(input, arguments.Target, arguments.Output,
  2149. arguments.Condition, inputIsContent, status);
  2150. return true;
  2151. }
  2152. bool HandleLockCommand(std::vector<std::string> const& args,
  2153. cmExecutionStatus& status)
  2154. {
  2155. #if !defined(CMAKE_BOOTSTRAP)
  2156. // Default values
  2157. bool directory = false;
  2158. bool release = false;
  2159. enum Guard
  2160. {
  2161. GUARD_FUNCTION,
  2162. GUARD_FILE,
  2163. GUARD_PROCESS
  2164. };
  2165. Guard guard = GUARD_PROCESS;
  2166. std::string resultVariable;
  2167. unsigned long timeout = static_cast<unsigned long>(-1);
  2168. // Parse arguments
  2169. if (args.size() < 2) {
  2170. status.GetMakefile().IssueMessage(
  2171. MessageType::FATAL_ERROR,
  2172. "sub-command LOCK requires at least two arguments.");
  2173. return false;
  2174. }
  2175. std::string path = args[1];
  2176. for (unsigned i = 2; i < args.size(); ++i) {
  2177. if (args[i] == "DIRECTORY") {
  2178. directory = true;
  2179. } else if (args[i] == "RELEASE") {
  2180. release = true;
  2181. } else if (args[i] == "GUARD") {
  2182. ++i;
  2183. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2184. if (i >= args.size()) {
  2185. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2186. return false;
  2187. }
  2188. if (args[i] == "FUNCTION") {
  2189. guard = GUARD_FUNCTION;
  2190. } else if (args[i] == "FILE") {
  2191. guard = GUARD_FILE;
  2192. } else if (args[i] == "PROCESS") {
  2193. guard = GUARD_PROCESS;
  2194. } else {
  2195. status.GetMakefile().IssueMessage(
  2196. MessageType::FATAL_ERROR,
  2197. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2198. return false;
  2199. }
  2200. } else if (args[i] == "RESULT_VARIABLE") {
  2201. ++i;
  2202. if (i >= args.size()) {
  2203. status.GetMakefile().IssueMessage(
  2204. MessageType::FATAL_ERROR,
  2205. "expected variable name after RESULT_VARIABLE");
  2206. return false;
  2207. }
  2208. resultVariable = args[i];
  2209. } else if (args[i] == "TIMEOUT") {
  2210. ++i;
  2211. if (i >= args.size()) {
  2212. status.GetMakefile().IssueMessage(
  2213. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2214. return false;
  2215. }
  2216. long scanned;
  2217. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2218. status.GetMakefile().IssueMessage(
  2219. MessageType::FATAL_ERROR,
  2220. cmStrCat("TIMEOUT value \"", args[i],
  2221. "\" is not an unsigned integer."));
  2222. return false;
  2223. }
  2224. timeout = static_cast<unsigned long>(scanned);
  2225. } else {
  2226. status.GetMakefile().IssueMessage(
  2227. MessageType::FATAL_ERROR,
  2228. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2229. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2230. return false;
  2231. }
  2232. }
  2233. if (directory) {
  2234. path += "/cmake.lock";
  2235. }
  2236. // Unify path (remove '//', '/../', ...)
  2237. path = cmSystemTools::CollapseFullPath(
  2238. path, status.GetMakefile().GetCurrentSourceDirectory());
  2239. // Create file and directories if needed
  2240. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2241. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2242. status.GetMakefile().IssueMessage(
  2243. MessageType::FATAL_ERROR,
  2244. cmStrCat("directory\n \"", parentDir,
  2245. "\"\ncreation failed (check permissions)."));
  2246. cmSystemTools::SetFatalErrorOccured();
  2247. return false;
  2248. }
  2249. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2250. if (!file) {
  2251. status.GetMakefile().IssueMessage(
  2252. MessageType::FATAL_ERROR,
  2253. cmStrCat("file\n \"", path,
  2254. "\"\ncreation failed (check permissions)."));
  2255. cmSystemTools::SetFatalErrorOccured();
  2256. return false;
  2257. }
  2258. fclose(file);
  2259. // Actual lock/unlock
  2260. cmFileLockPool& lockPool =
  2261. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2262. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2263. if (release) {
  2264. fileLockResult = lockPool.Release(path);
  2265. } else {
  2266. switch (guard) {
  2267. case GUARD_FUNCTION:
  2268. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2269. break;
  2270. case GUARD_FILE:
  2271. fileLockResult = lockPool.LockFileScope(path, timeout);
  2272. break;
  2273. case GUARD_PROCESS:
  2274. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2275. break;
  2276. default:
  2277. cmSystemTools::SetFatalErrorOccured();
  2278. return false;
  2279. }
  2280. }
  2281. const std::string result = fileLockResult.GetOutputMessage();
  2282. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2283. status.GetMakefile().IssueMessage(
  2284. MessageType::FATAL_ERROR,
  2285. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2286. cmSystemTools::SetFatalErrorOccured();
  2287. return false;
  2288. }
  2289. if (!resultVariable.empty()) {
  2290. status.GetMakefile().AddDefinition(resultVariable, result);
  2291. }
  2292. return true;
  2293. #else
  2294. static_cast<void>(args);
  2295. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2296. return false;
  2297. #endif
  2298. }
  2299. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2300. cmExecutionStatus& status)
  2301. {
  2302. if (args.size() < 3) {
  2303. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2304. return false;
  2305. }
  2306. if (args.size() > 5) {
  2307. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2308. return false;
  2309. }
  2310. unsigned int argsIndex = 1;
  2311. const std::string& filename = args[argsIndex++];
  2312. const std::string& outputVariable = args[argsIndex++];
  2313. std::string formatString;
  2314. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2315. formatString = args[argsIndex++];
  2316. }
  2317. bool utcFlag = false;
  2318. if (args.size() > argsIndex) {
  2319. if (args[argsIndex] == "UTC") {
  2320. utcFlag = true;
  2321. } else {
  2322. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2323. args[argsIndex] + ".";
  2324. status.SetError(e);
  2325. return false;
  2326. }
  2327. }
  2328. cmTimestamp timestamp;
  2329. std::string result =
  2330. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2331. status.GetMakefile().AddDefinition(outputVariable, result);
  2332. return true;
  2333. }
  2334. bool HandleSizeCommand(std::vector<std::string> const& args,
  2335. cmExecutionStatus& status)
  2336. {
  2337. if (args.size() != 3) {
  2338. status.SetError(
  2339. cmStrCat(args[0], " requires a file name and output variable"));
  2340. return false;
  2341. }
  2342. unsigned int argsIndex = 1;
  2343. const std::string& filename = args[argsIndex++];
  2344. const std::string& outputVariable = args[argsIndex++];
  2345. if (!cmSystemTools::FileExists(filename, true)) {
  2346. status.SetError(
  2347. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2348. return false;
  2349. }
  2350. status.GetMakefile().AddDefinition(
  2351. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2352. return true;
  2353. }
  2354. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2355. cmExecutionStatus& status)
  2356. {
  2357. if (args.size() != 3) {
  2358. status.SetError(
  2359. cmStrCat(args[0], " requires a file name and output variable"));
  2360. return false;
  2361. }
  2362. const std::string& filename = args[1];
  2363. const std::string& outputVariable = args[2];
  2364. std::string result;
  2365. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2366. status.SetError(cmStrCat(
  2367. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2368. return false;
  2369. }
  2370. status.GetMakefile().AddDefinition(outputVariable, result);
  2371. return true;
  2372. }
  2373. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2374. cmExecutionStatus& status)
  2375. {
  2376. if (args.size() < 3) {
  2377. status.SetError("CREATE_LINK must be called with at least two additional "
  2378. "arguments");
  2379. return false;
  2380. }
  2381. std::string const& fileName = args[1];
  2382. std::string const& newFileName = args[2];
  2383. struct Arguments
  2384. {
  2385. std::string Result;
  2386. bool CopyOnError = false;
  2387. bool Symbolic = false;
  2388. };
  2389. static auto const parser =
  2390. cmArgumentParser<Arguments>{}
  2391. .Bind("RESULT"_s, &Arguments::Result)
  2392. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2393. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2394. std::vector<std::string> unconsumedArgs;
  2395. Arguments const arguments =
  2396. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2397. if (!unconsumedArgs.empty()) {
  2398. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2399. return false;
  2400. }
  2401. // The system error message generated in the operation.
  2402. std::string result;
  2403. // Check if the paths are distinct.
  2404. if (fileName == newFileName) {
  2405. result = "CREATE_LINK cannot use same file and newfile";
  2406. if (!arguments.Result.empty()) {
  2407. status.GetMakefile().AddDefinition(arguments.Result, result);
  2408. return true;
  2409. }
  2410. status.SetError(result);
  2411. return false;
  2412. }
  2413. // Hard link requires original file to exist.
  2414. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2415. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2416. if (!arguments.Result.empty()) {
  2417. status.GetMakefile().AddDefinition(arguments.Result, result);
  2418. return true;
  2419. }
  2420. status.SetError(result);
  2421. return false;
  2422. }
  2423. // Check if the new file already exists and remove it.
  2424. if ((cmSystemTools::FileExists(newFileName) ||
  2425. cmSystemTools::FileIsSymlink(newFileName)) &&
  2426. !cmSystemTools::RemoveFile(newFileName)) {
  2427. std::ostringstream e;
  2428. e << "Failed to create link '" << newFileName
  2429. << "' because existing path cannot be removed: "
  2430. << cmSystemTools::GetLastSystemError() << "\n";
  2431. if (!arguments.Result.empty()) {
  2432. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2433. return true;
  2434. }
  2435. status.SetError(e.str());
  2436. return false;
  2437. }
  2438. // Whether the operation completed successfully.
  2439. bool completed = false;
  2440. // Check if the command requires a symbolic link.
  2441. if (arguments.Symbolic) {
  2442. completed = cmSystemTools::CreateSymlink(fileName, newFileName, &result);
  2443. } else {
  2444. completed = cmSystemTools::CreateLink(fileName, newFileName, &result);
  2445. }
  2446. // Check if copy-on-error is enabled in the arguments.
  2447. if (!completed && arguments.CopyOnError) {
  2448. completed = cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2449. if (!completed) {
  2450. result = "Copy failed: " + cmSystemTools::GetLastSystemError();
  2451. }
  2452. }
  2453. // Check if the operation was successful.
  2454. if (completed) {
  2455. result = "0";
  2456. } else if (arguments.Result.empty()) {
  2457. // The operation failed and the result is not reported in a variable.
  2458. status.SetError(result);
  2459. return false;
  2460. }
  2461. if (!arguments.Result.empty()) {
  2462. status.GetMakefile().AddDefinition(arguments.Result, result);
  2463. }
  2464. return true;
  2465. }
  2466. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2467. cmExecutionStatus& status)
  2468. {
  2469. static const std::set<std::string> supportedPlatforms = { "Windows", "Linux",
  2470. "Darwin" };
  2471. std::string platform =
  2472. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2473. if (!supportedPlatforms.count(platform)) {
  2474. status.SetError(
  2475. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2476. platform, "\""));
  2477. cmSystemTools::SetFatalErrorOccured();
  2478. return false;
  2479. }
  2480. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2481. status.GetMakefile().IssueMessage(
  2482. MessageType::AUTHOR_WARNING,
  2483. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2484. " in project mode. This is probably not what "
  2485. "you intended to do. Instead, please consider"
  2486. " using it in an install(CODE) or "
  2487. "install(SCRIPT) command. For example:"
  2488. "\n install(CODE [["
  2489. "\n file(GET_RUNTIME_DEPENDENCIES"
  2490. "\n # ..."
  2491. "\n )"
  2492. "\n ]])");
  2493. }
  2494. struct Arguments
  2495. {
  2496. std::string ResolvedDependenciesVar;
  2497. std::string UnresolvedDependenciesVar;
  2498. std::string ConflictingDependenciesPrefix;
  2499. std::string BundleExecutable;
  2500. std::vector<std::string> Executables;
  2501. std::vector<std::string> Libraries;
  2502. std::vector<std::string> Directories;
  2503. std::vector<std::string> Modules;
  2504. std::vector<std::string> PreIncludeRegexes;
  2505. std::vector<std::string> PreExcludeRegexes;
  2506. std::vector<std::string> PostIncludeRegexes;
  2507. std::vector<std::string> PostExcludeRegexes;
  2508. };
  2509. static auto const parser =
  2510. cmArgumentParser<Arguments>{}
  2511. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2512. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2513. &Arguments::UnresolvedDependenciesVar)
  2514. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2515. &Arguments::ConflictingDependenciesPrefix)
  2516. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2517. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2518. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2519. .Bind("MODULES"_s, &Arguments::Modules)
  2520. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2521. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2522. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2523. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2524. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes);
  2525. std::vector<std::string> unrecognizedArguments;
  2526. std::vector<std::string> keywordsMissingValues;
  2527. auto parsedArgs =
  2528. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2529. &keywordsMissingValues);
  2530. auto argIt = unrecognizedArguments.begin();
  2531. if (argIt != unrecognizedArguments.end()) {
  2532. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2533. cmSystemTools::SetFatalErrorOccured();
  2534. return false;
  2535. }
  2536. const std::vector<std::string> LIST_ARGS = { "DIRECTORIES",
  2537. "EXECUTABLES",
  2538. "LIBRARIES",
  2539. "MODULES",
  2540. "POST_EXCLUDE_REGEXES",
  2541. "POST_INCLUDE_REGEXES",
  2542. "PRE_EXCLUDE_REGEXES",
  2543. "PRE_INCLUDE_REGEXES" };
  2544. auto kwbegin = keywordsMissingValues.cbegin();
  2545. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2546. if (kwend != kwbegin) {
  2547. status.SetError(cmStrCat("Keywords missing values:\n ",
  2548. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2549. cmSystemTools::SetFatalErrorOccured();
  2550. return false;
  2551. }
  2552. cmRuntimeDependencyArchive archive(
  2553. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2554. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2555. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes);
  2556. if (!archive.Prepare()) {
  2557. cmSystemTools::SetFatalErrorOccured();
  2558. return false;
  2559. }
  2560. if (!archive.GetRuntimeDependencies(
  2561. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2562. cmSystemTools::SetFatalErrorOccured();
  2563. return false;
  2564. }
  2565. std::vector<std::string> deps;
  2566. std::vector<std::string> unresolvedDeps;
  2567. std::vector<std::string> conflictingDeps;
  2568. for (auto const& val : archive.GetResolvedPaths()) {
  2569. bool unique = true;
  2570. auto it = val.second.begin();
  2571. assert(it != val.second.end());
  2572. auto const& firstPath = *it;
  2573. while (++it != val.second.end()) {
  2574. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2575. unique = false;
  2576. break;
  2577. }
  2578. }
  2579. if (unique) {
  2580. deps.push_back(firstPath);
  2581. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2582. conflictingDeps.push_back(val.first);
  2583. std::vector<std::string> paths;
  2584. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2585. std::string varName =
  2586. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2587. std::string pathsStr = cmJoin(paths, ";");
  2588. status.GetMakefile().AddDefinition(varName, pathsStr);
  2589. } else {
  2590. std::ostringstream e;
  2591. e << "Multiple conflicting paths found for " << val.first << ":";
  2592. for (auto const& path : val.second) {
  2593. e << "\n " << path;
  2594. }
  2595. status.SetError(e.str());
  2596. cmSystemTools::SetFatalErrorOccured();
  2597. return false;
  2598. }
  2599. }
  2600. if (!archive.GetUnresolvedPaths().empty()) {
  2601. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2602. unresolvedDeps.insert(unresolvedDeps.begin(),
  2603. archive.GetUnresolvedPaths().begin(),
  2604. archive.GetUnresolvedPaths().end());
  2605. } else {
  2606. auto it = archive.GetUnresolvedPaths().begin();
  2607. assert(it != archive.GetUnresolvedPaths().end());
  2608. status.SetError(cmStrCat("Could not resolve file ", *it));
  2609. cmSystemTools::SetFatalErrorOccured();
  2610. return false;
  2611. }
  2612. }
  2613. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2614. std::string val = cmJoin(deps, ";");
  2615. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2616. val);
  2617. }
  2618. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2619. std::string val = cmJoin(unresolvedDeps, ";");
  2620. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2621. val);
  2622. }
  2623. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2624. std::string val = cmJoin(conflictingDeps, ";");
  2625. status.GetMakefile().AddDefinition(
  2626. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2627. }
  2628. return true;
  2629. }
  2630. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2631. cmExecutionStatus& status)
  2632. {
  2633. struct Arguments
  2634. {
  2635. std::string Output;
  2636. std::string Content;
  2637. bool EscapeQuotes = false;
  2638. bool AtOnly = false;
  2639. std::string NewlineStyle;
  2640. };
  2641. static auto const parser =
  2642. cmArgumentParser<Arguments>{}
  2643. .Bind("OUTPUT"_s, &Arguments::Output)
  2644. .Bind("CONTENT"_s, &Arguments::Content)
  2645. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  2646. .Bind("@ONLY"_s, &Arguments::AtOnly)
  2647. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  2648. std::vector<std::string> unrecognizedArguments;
  2649. std::vector<std::string> keywordsMissingArguments;
  2650. std::vector<std::string> parsedKeywords;
  2651. auto parsedArgs =
  2652. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2653. &keywordsMissingArguments, &parsedKeywords);
  2654. auto argIt = unrecognizedArguments.begin();
  2655. if (argIt != unrecognizedArguments.end()) {
  2656. status.SetError(
  2657. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  2658. cmSystemTools::SetFatalErrorOccured();
  2659. return false;
  2660. }
  2661. std::vector<std::string> mandatoryOptions{ "OUTPUT", "CONTENT" };
  2662. for (auto const& e : mandatoryOptions) {
  2663. const bool optionHasNoValue =
  2664. std::find(keywordsMissingArguments.begin(),
  2665. keywordsMissingArguments.end(),
  2666. e) != keywordsMissingArguments.end();
  2667. if (optionHasNoValue) {
  2668. status.SetError(cmStrCat("CONFIGURE ", e, " option needs a value."));
  2669. cmSystemTools::SetFatalErrorOccured();
  2670. return false;
  2671. }
  2672. }
  2673. for (auto const& e : mandatoryOptions) {
  2674. const bool optionGiven =
  2675. std::find(parsedKeywords.begin(), parsedKeywords.end(), e) !=
  2676. parsedKeywords.end();
  2677. if (!optionGiven) {
  2678. status.SetError(cmStrCat("CONFIGURE ", e, " option is mandatory."));
  2679. cmSystemTools::SetFatalErrorOccured();
  2680. return false;
  2681. }
  2682. }
  2683. std::string errorMessage;
  2684. cmNewLineStyle newLineStyle;
  2685. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2686. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2687. return false;
  2688. }
  2689. // Check for generator expressions
  2690. std::string outputFile = cmSystemTools::CollapseFullPath(
  2691. parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  2692. std::string::size_type pos = outputFile.find_first_of("<>");
  2693. if (pos != std::string::npos) {
  2694. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2695. outputFile[pos],
  2696. "\". This character is not allowed."));
  2697. return false;
  2698. }
  2699. cmMakefile& makeFile = status.GetMakefile();
  2700. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2701. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2702. " into a source directory.");
  2703. return false;
  2704. }
  2705. cmSystemTools::ConvertToUnixSlashes(outputFile);
  2706. // Re-generate if non-temporary outputs are missing.
  2707. // when we finalize the configuration we will remove all
  2708. // output files that now don't exist.
  2709. makeFile.AddCMakeOutputFile(outputFile);
  2710. // Create output directory
  2711. const std::string::size_type slashPos = outputFile.rfind('/');
  2712. if (slashPos != std::string::npos) {
  2713. const std::string path = outputFile.substr(0, slashPos);
  2714. cmSystemTools::MakeDirectory(path);
  2715. }
  2716. std::string newLineCharacters;
  2717. bool open_with_binary_flag = false;
  2718. if (newLineStyle.IsValid()) {
  2719. open_with_binary_flag = true;
  2720. newLineCharacters = newLineStyle.GetCharacters();
  2721. }
  2722. cmGeneratedFileStream fout;
  2723. fout.Open(outputFile, false, open_with_binary_flag);
  2724. if (!fout) {
  2725. cmSystemTools::Error("Could not open file for write in copy operation " +
  2726. outputFile);
  2727. cmSystemTools::ReportLastSystemError("");
  2728. return false;
  2729. }
  2730. fout.SetCopyIfDifferent(true);
  2731. // copy input to output and expand variables from input at the same time
  2732. std::stringstream sin(parsedArgs.Content, std::ios::in);
  2733. std::string inLine;
  2734. std::string outLine;
  2735. while (cmSystemTools::GetLineFromStream(sin, inLine)) {
  2736. outLine.clear();
  2737. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  2738. parsedArgs.EscapeQuotes);
  2739. fout << outLine << newLineCharacters;
  2740. }
  2741. // close file before attempting to copy
  2742. fout.close();
  2743. return true;
  2744. }
  2745. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  2746. cmExecutionStatus& status)
  2747. {
  2748. struct Arguments
  2749. {
  2750. std::string Output;
  2751. std::string Format;
  2752. std::string Compression;
  2753. std::string CompressionLevel;
  2754. std::string MTime;
  2755. bool Verbose = false;
  2756. std::vector<std::string> Paths;
  2757. };
  2758. static auto const parser =
  2759. cmArgumentParser<Arguments>{}
  2760. .Bind("OUTPUT"_s, &Arguments::Output)
  2761. .Bind("FORMAT"_s, &Arguments::Format)
  2762. .Bind("COMPRESSION"_s, &Arguments::Compression)
  2763. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  2764. .Bind("MTIME"_s, &Arguments::MTime)
  2765. .Bind("VERBOSE"_s, &Arguments::Verbose)
  2766. .Bind("PATHS"_s, &Arguments::Paths);
  2767. std::vector<std::string> unrecognizedArguments;
  2768. std::vector<std::string> keywordsMissingValues;
  2769. auto parsedArgs =
  2770. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2771. &keywordsMissingValues);
  2772. auto argIt = unrecognizedArguments.begin();
  2773. if (argIt != unrecognizedArguments.end()) {
  2774. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2775. cmSystemTools::SetFatalErrorOccured();
  2776. return false;
  2777. }
  2778. const std::vector<std::string> LIST_ARGS = {
  2779. "OUTPUT", "FORMAT", "COMPRESSION", "COMPRESSION_LEVEL", "MTIME", "PATHS"
  2780. };
  2781. auto kwbegin = keywordsMissingValues.cbegin();
  2782. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2783. if (kwend != kwbegin) {
  2784. status.SetError(cmStrCat("Keywords missing values:\n ",
  2785. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2786. cmSystemTools::SetFatalErrorOccured();
  2787. return false;
  2788. }
  2789. const char* knownFormats[] = {
  2790. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  2791. };
  2792. if (!parsedArgs.Format.empty() &&
  2793. !cm::contains(knownFormats, parsedArgs.Format)) {
  2794. status.SetError(
  2795. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  2796. cmSystemTools::SetFatalErrorOccured();
  2797. return false;
  2798. }
  2799. const char* zipFileFormats[] = { "7zip", "zip" };
  2800. if (!parsedArgs.Compression.empty() &&
  2801. cm::contains(zipFileFormats, parsedArgs.Format)) {
  2802. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  2803. " does not support COMPRESSION arguments"));
  2804. cmSystemTools::SetFatalErrorOccured();
  2805. return false;
  2806. }
  2807. static std::map<std::string, cmSystemTools::cmTarCompression>
  2808. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  2809. { "BZip2", cmSystemTools::TarCompressBZip2 },
  2810. { "GZip", cmSystemTools::TarCompressGZip },
  2811. { "XZ", cmSystemTools::TarCompressXZ },
  2812. { "Zstd", cmSystemTools::TarCompressZstd } };
  2813. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  2814. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  2815. if (typeIt != compressionTypeMap.end()) {
  2816. compress = typeIt->second;
  2817. } else if (!parsedArgs.Compression.empty()) {
  2818. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  2819. " is not supported"));
  2820. cmSystemTools::SetFatalErrorOccured();
  2821. return false;
  2822. }
  2823. int compressionLevel = 0;
  2824. if (!parsedArgs.CompressionLevel.empty()) {
  2825. if (parsedArgs.CompressionLevel.size() != 1 &&
  2826. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  2827. status.SetError(cmStrCat("compression level ",
  2828. parsedArgs.CompressionLevel,
  2829. " should be in range 0 to 9"));
  2830. cmSystemTools::SetFatalErrorOccured();
  2831. return false;
  2832. }
  2833. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  2834. if (compressionLevel < 0 || compressionLevel > 9) {
  2835. status.SetError(cmStrCat("compression level ",
  2836. parsedArgs.CompressionLevel,
  2837. " should be in range 0 to 9"));
  2838. cmSystemTools::SetFatalErrorOccured();
  2839. return false;
  2840. }
  2841. if (compress == cmSystemTools::TarCompressNone) {
  2842. status.SetError(cmStrCat("compression level is not supported for "
  2843. "compression \"None\"",
  2844. parsedArgs.Compression));
  2845. cmSystemTools::SetFatalErrorOccured();
  2846. return false;
  2847. }
  2848. }
  2849. if (parsedArgs.Paths.empty()) {
  2850. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  2851. cmSystemTools::SetFatalErrorOccured();
  2852. return false;
  2853. }
  2854. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths, compress,
  2855. parsedArgs.Verbose, parsedArgs.MTime,
  2856. parsedArgs.Format, compressionLevel)) {
  2857. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  2858. cmSystemTools::SetFatalErrorOccured();
  2859. return false;
  2860. }
  2861. return true;
  2862. }
  2863. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  2864. cmExecutionStatus& status)
  2865. {
  2866. struct Arguments
  2867. {
  2868. std::string Input;
  2869. bool Verbose = false;
  2870. bool ListOnly = false;
  2871. std::string Destination;
  2872. std::vector<std::string> Patterns;
  2873. };
  2874. static auto const parser = cmArgumentParser<Arguments>{}
  2875. .Bind("INPUT"_s, &Arguments::Input)
  2876. .Bind("VERBOSE"_s, &Arguments::Verbose)
  2877. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  2878. .Bind("DESTINATION"_s, &Arguments::Destination)
  2879. .Bind("PATTERNS"_s, &Arguments::Patterns);
  2880. std::vector<std::string> unrecognizedArguments;
  2881. std::vector<std::string> keywordsMissingValues;
  2882. auto parsedArgs =
  2883. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments,
  2884. &keywordsMissingValues);
  2885. auto argIt = unrecognizedArguments.begin();
  2886. if (argIt != unrecognizedArguments.end()) {
  2887. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2888. cmSystemTools::SetFatalErrorOccured();
  2889. return false;
  2890. }
  2891. const std::vector<std::string> LIST_ARGS = { "INPUT", "DESTINATION",
  2892. "PATTERNS" };
  2893. auto kwbegin = keywordsMissingValues.cbegin();
  2894. auto kwend = cmRemoveMatching(keywordsMissingValues, LIST_ARGS);
  2895. if (kwend != kwbegin) {
  2896. status.SetError(cmStrCat("Keywords missing values:\n ",
  2897. cmJoin(cmMakeRange(kwbegin, kwend), "\n ")));
  2898. cmSystemTools::SetFatalErrorOccured();
  2899. return false;
  2900. }
  2901. std::string inFile = parsedArgs.Input;
  2902. if (parsedArgs.ListOnly) {
  2903. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  2904. parsedArgs.Verbose)) {
  2905. status.SetError(cmStrCat("failed to list: ", inFile));
  2906. cmSystemTools::SetFatalErrorOccured();
  2907. return false;
  2908. }
  2909. } else {
  2910. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  2911. if (!parsedArgs.Destination.empty()) {
  2912. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  2913. destDir = parsedArgs.Destination;
  2914. } else {
  2915. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  2916. }
  2917. if (!cmSystemTools::MakeDirectory(destDir)) {
  2918. status.SetError(cmStrCat("failed to create directory: ", destDir));
  2919. cmSystemTools::SetFatalErrorOccured();
  2920. return false;
  2921. }
  2922. if (!cmSystemTools::FileIsFullPath(inFile)) {
  2923. inFile =
  2924. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  2925. }
  2926. }
  2927. cmWorkingDirectory workdir(destDir);
  2928. if (workdir.Failed()) {
  2929. status.SetError(
  2930. cmStrCat("failed to change working directory to: ", destDir));
  2931. cmSystemTools::SetFatalErrorOccured();
  2932. return false;
  2933. }
  2934. if (!cmSystemTools::ExtractTar(inFile, parsedArgs.Patterns,
  2935. parsedArgs.Verbose)) {
  2936. status.SetError(cmStrCat("failed to extract: ", inFile));
  2937. cmSystemTools::SetFatalErrorOccured();
  2938. return false;
  2939. }
  2940. }
  2941. return true;
  2942. }
  2943. bool ValidateAndConvertPermissions(const std::vector<std::string>& permissions,
  2944. mode_t& perms, cmExecutionStatus& status)
  2945. {
  2946. for (const auto& i : permissions) {
  2947. if (!cmFSPermissions::stringToModeT(i, perms)) {
  2948. status.SetError(i + " is an invalid permission specifier");
  2949. cmSystemTools::SetFatalErrorOccured();
  2950. return false;
  2951. }
  2952. }
  2953. return true;
  2954. }
  2955. bool SetPermissions(const std::string& filename, const mode_t& perms,
  2956. cmExecutionStatus& status)
  2957. {
  2958. if (!cmSystemTools::SetPermissions(filename, perms)) {
  2959. status.SetError("Failed to set permissions for " + filename);
  2960. cmSystemTools::SetFatalErrorOccured();
  2961. return false;
  2962. }
  2963. return true;
  2964. }
  2965. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  2966. cmExecutionStatus& status)
  2967. {
  2968. mode_t perms = 0;
  2969. mode_t fperms = 0;
  2970. mode_t dperms = 0;
  2971. cmsys::Glob globber;
  2972. globber.SetRecurse(recurse);
  2973. globber.SetRecurseListDirs(recurse);
  2974. struct Arguments
  2975. {
  2976. std::vector<std::string> Permissions;
  2977. std::vector<std::string> FilePermissions;
  2978. std::vector<std::string> DirectoryPermissions;
  2979. };
  2980. static auto const parser =
  2981. cmArgumentParser<Arguments>{}
  2982. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  2983. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2984. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  2985. std::vector<std::string> pathEntries;
  2986. std::vector<std::string> keywordsMissingValues;
  2987. Arguments parsedArgs = parser.Parse(cmMakeRange(args).advance(1),
  2988. &pathEntries, &keywordsMissingValues);
  2989. // check validity of arguments
  2990. if (parsedArgs.Permissions.empty() && parsedArgs.FilePermissions.empty() &&
  2991. parsedArgs.DirectoryPermissions.empty()) // no permissions given
  2992. {
  2993. status.SetError("No permissions given");
  2994. cmSystemTools::SetFatalErrorOccured();
  2995. return false;
  2996. }
  2997. if (!parsedArgs.Permissions.empty() && !parsedArgs.FilePermissions.empty() &&
  2998. !parsedArgs.DirectoryPermissions.empty()) // all keywords are used
  2999. {
  3000. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3001. "DIRECTORY_PERMISSIONS from the invocation");
  3002. cmSystemTools::SetFatalErrorOccured();
  3003. return false;
  3004. }
  3005. if (!keywordsMissingValues.empty()) {
  3006. for (const auto& i : keywordsMissingValues) {
  3007. status.SetError(i + " is not given any arguments");
  3008. cmSystemTools::SetFatalErrorOccured();
  3009. }
  3010. return false;
  3011. }
  3012. // validate permissions
  3013. bool validatePermissions =
  3014. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3015. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3016. status) &&
  3017. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3018. status);
  3019. if (!validatePermissions) {
  3020. return false;
  3021. }
  3022. std::vector<std::string> allPathEntries;
  3023. if (recurse) {
  3024. std::vector<std::string> tempPathEntries;
  3025. for (const auto& i : pathEntries) {
  3026. if (cmSystemTools::FileIsDirectory(i)) {
  3027. globber.FindFiles(i + "/*");
  3028. tempPathEntries = globber.GetFiles();
  3029. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3030. tempPathEntries.end());
  3031. allPathEntries.emplace_back(i);
  3032. } else {
  3033. allPathEntries.emplace_back(i); // We validate path entries below
  3034. }
  3035. }
  3036. } else {
  3037. allPathEntries = std::move(pathEntries);
  3038. }
  3039. // chmod
  3040. for (const auto& i : allPathEntries) {
  3041. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3042. status.SetError(cmStrCat("does not exist:\n ", i));
  3043. cmSystemTools::SetFatalErrorOccured();
  3044. return false;
  3045. }
  3046. if (cmSystemTools::FileExists(i, true)) {
  3047. bool success = true;
  3048. const mode_t& filePermissions =
  3049. parsedArgs.FilePermissions.empty() ? perms : fperms;
  3050. if (filePermissions) {
  3051. success = SetPermissions(i, filePermissions, status);
  3052. }
  3053. if (!success) {
  3054. return false;
  3055. }
  3056. }
  3057. else if (cmSystemTools::FileIsDirectory(i)) {
  3058. bool success = true;
  3059. const mode_t& directoryPermissions =
  3060. parsedArgs.DirectoryPermissions.empty() ? perms : dperms;
  3061. if (directoryPermissions) {
  3062. success = SetPermissions(i, directoryPermissions, status);
  3063. }
  3064. if (!success) {
  3065. return false;
  3066. }
  3067. }
  3068. }
  3069. return true;
  3070. }
  3071. bool HandleChmodCommand(std::vector<std::string> const& args,
  3072. cmExecutionStatus& status)
  3073. {
  3074. return HandleChmodCommandImpl(args, false, status);
  3075. }
  3076. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3077. cmExecutionStatus& status)
  3078. {
  3079. return HandleChmodCommandImpl(args, true, status);
  3080. }
  3081. } // namespace
  3082. bool cmFileCommand(std::vector<std::string> const& args,
  3083. cmExecutionStatus& status)
  3084. {
  3085. if (args.size() < 2) {
  3086. status.SetError("must be called with at least two arguments.");
  3087. return false;
  3088. }
  3089. static cmSubcommandTable const subcommand{
  3090. { "WRITE"_s, HandleWriteCommand },
  3091. { "APPEND"_s, HandleAppendCommand },
  3092. { "DOWNLOAD"_s, HandleDownloadCommand },
  3093. { "UPLOAD"_s, HandleUploadCommand },
  3094. { "READ"_s, HandleReadCommand },
  3095. { "MD5"_s, HandleHashCommand },
  3096. { "SHA1"_s, HandleHashCommand },
  3097. { "SHA224"_s, HandleHashCommand },
  3098. { "SHA256"_s, HandleHashCommand },
  3099. { "SHA384"_s, HandleHashCommand },
  3100. { "SHA512"_s, HandleHashCommand },
  3101. { "SHA3_224"_s, HandleHashCommand },
  3102. { "SHA3_256"_s, HandleHashCommand },
  3103. { "SHA3_384"_s, HandleHashCommand },
  3104. { "SHA3_512"_s, HandleHashCommand },
  3105. { "STRINGS"_s, HandleStringsCommand },
  3106. { "GLOB"_s, HandleGlobCommand },
  3107. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3108. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3109. { "RENAME"_s, HandleRename },
  3110. { "REMOVE"_s, HandleRemove },
  3111. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3112. { "COPY"_s, HandleCopyCommand },
  3113. { "INSTALL"_s, HandleInstallCommand },
  3114. { "DIFFERENT"_s, HandleDifferentCommand },
  3115. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3116. { "CHRPATH"_s, HandleRPathChangeCommand },
  3117. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3118. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3119. { "READ_ELF"_s, HandleReadElfCommand },
  3120. { "REAL_PATH"_s, HandleRealPathCommand },
  3121. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3122. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3123. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3124. { "TOUCH"_s, HandleTouchCommand },
  3125. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3126. { "TIMESTAMP"_s, HandleTimestampCommand },
  3127. { "GENERATE"_s, HandleGenerateCommand },
  3128. { "LOCK"_s, HandleLockCommand },
  3129. { "SIZE"_s, HandleSizeCommand },
  3130. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3131. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3132. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3133. { "CONFIGURE"_s, HandleConfigureCommand },
  3134. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3135. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3136. { "CHMOD"_s, HandleChmodCommand },
  3137. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3138. };
  3139. return subcommand(args[0], args, status);
  3140. }