cmFileCommand.cxx 128 KB

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