cmFileCommand.cxx 119 KB

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