cmFileCommand.cxx 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050
  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. if (warnAbout152) {
  1312. computeNewPath(input, realPath);
  1313. if (oldPolicyPath != realPath) {
  1314. status.GetMakefile().IssueMessage(
  1315. MessageType::AUTHOR_WARNING,
  1316. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0152),
  1317. "\n"
  1318. "From input path:\n ",
  1319. input, "\nthe policy OLD behavior produces path:\n ",
  1320. oldPolicyPath,
  1321. "\nbut the policy NEW behavior produces path:\n ",
  1322. realPath,
  1323. "\nSince the policy is not set, CMake is using the OLD "
  1324. "behavior for compatibility."));
  1325. }
  1326. }
  1327. realPath = oldPolicyPath;
  1328. }
  1329. status.GetMakefile().AddDefinition(args[2], realPath);
  1330. return true;
  1331. }
  1332. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1333. cmExecutionStatus& status)
  1334. {
  1335. if (args.size() != 4) {
  1336. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1337. return false;
  1338. }
  1339. const std::string& outVar = args[1];
  1340. const std::string& directoryName = args[2];
  1341. const std::string& fileName = args[3];
  1342. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1343. std::string errstring =
  1344. "RELATIVE_PATH must be passed a full path to the directory: " +
  1345. directoryName;
  1346. status.SetError(errstring);
  1347. return false;
  1348. }
  1349. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1350. std::string errstring =
  1351. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1352. status.SetError(errstring);
  1353. return false;
  1354. }
  1355. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1356. status.GetMakefile().AddDefinition(outVar, res);
  1357. return true;
  1358. }
  1359. bool HandleRename(std::vector<std::string> const& args,
  1360. cmExecutionStatus& status)
  1361. {
  1362. if (args.size() < 3) {
  1363. status.SetError("RENAME must be called with at least two additional "
  1364. "arguments");
  1365. return false;
  1366. }
  1367. // Compute full path for old and new names.
  1368. std::string oldname = args[1];
  1369. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1370. oldname =
  1371. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1372. }
  1373. std::string newname = args[2];
  1374. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1375. newname =
  1376. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1377. }
  1378. struct Arguments
  1379. {
  1380. bool NoReplace = false;
  1381. std::string Result;
  1382. };
  1383. static auto const parser = cmArgumentParser<Arguments>{}
  1384. .Bind("NO_REPLACE"_s, &Arguments::NoReplace)
  1385. .Bind("RESULT"_s, &Arguments::Result);
  1386. std::vector<std::string> unconsumedArgs;
  1387. Arguments const arguments =
  1388. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1389. if (!unconsumedArgs.empty()) {
  1390. status.SetError("RENAME unknown argument:\n " + unconsumedArgs.front());
  1391. return false;
  1392. }
  1393. std::string err;
  1394. switch (cmSystemTools::RenameFile(oldname, newname,
  1395. arguments.NoReplace
  1396. ? cmSystemTools::Replace::No
  1397. : cmSystemTools::Replace::Yes,
  1398. &err)) {
  1399. case cmSystemTools::RenameResult::Success:
  1400. if (!arguments.Result.empty()) {
  1401. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1402. }
  1403. return true;
  1404. case cmSystemTools::RenameResult::NoReplace:
  1405. if (!arguments.Result.empty()) {
  1406. err = "NO_REPLACE";
  1407. } else {
  1408. err = "path not replaced";
  1409. }
  1410. CM_FALLTHROUGH;
  1411. case cmSystemTools::RenameResult::Failure:
  1412. if (!arguments.Result.empty()) {
  1413. status.GetMakefile().AddDefinition(arguments.Result, err);
  1414. return true;
  1415. }
  1416. break;
  1417. }
  1418. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname, "\nto\n ",
  1419. newname, "\nbecause: ", err, "\n"));
  1420. return false;
  1421. }
  1422. bool HandleCopyFile(std::vector<std::string> const& args,
  1423. cmExecutionStatus& status)
  1424. {
  1425. if (args.size() < 3) {
  1426. status.SetError("COPY_FILE must be called with at least two additional "
  1427. "arguments");
  1428. return false;
  1429. }
  1430. // Compute full path for old and new names.
  1431. std::string oldname = args[1];
  1432. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1433. oldname =
  1434. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1435. }
  1436. std::string newname = args[2];
  1437. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1438. newname =
  1439. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1440. }
  1441. struct Arguments
  1442. {
  1443. bool InputMayBeRecent = false;
  1444. bool OnlyIfDifferent = false;
  1445. std::string Result;
  1446. };
  1447. static auto const parser =
  1448. cmArgumentParser<Arguments>{}
  1449. .Bind("INPUT_MAY_BE_RECENT"_s, &Arguments::InputMayBeRecent)
  1450. .Bind("ONLY_IF_DIFFERENT"_s, &Arguments::OnlyIfDifferent)
  1451. .Bind("RESULT"_s, &Arguments::Result);
  1452. std::vector<std::string> unconsumedArgs;
  1453. Arguments const arguments =
  1454. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1455. if (!unconsumedArgs.empty()) {
  1456. status.SetError("COPY_FILE unknown argument:\n " +
  1457. unconsumedArgs.front());
  1458. return false;
  1459. }
  1460. bool result = true;
  1461. if (cmsys::SystemTools::FileIsDirectory(oldname)) {
  1462. if (!arguments.Result.empty()) {
  1463. status.GetMakefile().AddDefinition(arguments.Result,
  1464. "cannot copy a directory");
  1465. } else {
  1466. status.SetError(
  1467. cmStrCat("COPY_FILE cannot copy a directory\n ", oldname));
  1468. result = false;
  1469. }
  1470. return result;
  1471. }
  1472. if (cmsys::SystemTools::FileIsDirectory(newname)) {
  1473. if (!arguments.Result.empty()) {
  1474. status.GetMakefile().AddDefinition(arguments.Result,
  1475. "cannot copy to a directory");
  1476. } else {
  1477. status.SetError(
  1478. cmStrCat("COPY_FILE cannot copy to a directory\n ", newname));
  1479. result = false;
  1480. }
  1481. return result;
  1482. }
  1483. cmSystemTools::CopyWhen when;
  1484. if (arguments.OnlyIfDifferent) {
  1485. when = cmSystemTools::CopyWhen::OnlyIfDifferent;
  1486. } else {
  1487. when = cmSystemTools::CopyWhen::Always;
  1488. }
  1489. cmSystemTools::CopyInputRecent const inputRecent = arguments.InputMayBeRecent
  1490. ? cmSystemTools::CopyInputRecent::Yes
  1491. : cmSystemTools::CopyInputRecent::No;
  1492. std::string err;
  1493. if (cmSystemTools::CopySingleFile(oldname, newname, when, inputRecent,
  1494. &err) ==
  1495. cmSystemTools::CopyResult::Success) {
  1496. if (!arguments.Result.empty()) {
  1497. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1498. }
  1499. } else {
  1500. if (!arguments.Result.empty()) {
  1501. status.GetMakefile().AddDefinition(arguments.Result, err);
  1502. } else {
  1503. status.SetError(cmStrCat("COPY_FILE failed to copy\n ", oldname,
  1504. "\nto\n ", newname, "\nbecause: ", err, "\n"));
  1505. result = false;
  1506. }
  1507. }
  1508. return result;
  1509. }
  1510. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1511. cmExecutionStatus& status)
  1512. {
  1513. for (std::string const& arg :
  1514. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1515. {
  1516. std::string fileName = arg;
  1517. if (fileName.empty()) {
  1518. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1519. status.GetMakefile().IssueMessage(
  1520. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1521. continue;
  1522. }
  1523. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1524. fileName =
  1525. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1526. }
  1527. if (cmSystemTools::FileIsDirectory(fileName) &&
  1528. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1529. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1530. } else {
  1531. cmSystemTools::RemoveFile(fileName);
  1532. }
  1533. }
  1534. return true;
  1535. }
  1536. bool HandleRemove(std::vector<std::string> const& args,
  1537. cmExecutionStatus& status)
  1538. {
  1539. return HandleRemoveImpl(args, false, status);
  1540. }
  1541. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1542. cmExecutionStatus& status)
  1543. {
  1544. return HandleRemoveImpl(args, true, status);
  1545. }
  1546. std::string ToNativePath(const std::string& path)
  1547. {
  1548. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1549. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1550. outPath.back() == '\"') {
  1551. return outPath.substr(1, outPath.size() - 2);
  1552. }
  1553. return outPath;
  1554. }
  1555. std::string ToCMakePath(const std::string& path)
  1556. {
  1557. auto temp = path;
  1558. cmSystemTools::ConvertToUnixSlashes(temp);
  1559. return temp;
  1560. }
  1561. bool HandlePathCommand(std::vector<std::string> const& args,
  1562. std::string (*convert)(std::string const&),
  1563. cmExecutionStatus& status)
  1564. {
  1565. if (args.size() != 3) {
  1566. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1567. "called with exactly three arguments.");
  1568. return false;
  1569. }
  1570. #if defined(_WIN32) && !defined(__CYGWIN__)
  1571. char pathSep = ';';
  1572. #else
  1573. char pathSep = ':';
  1574. #endif
  1575. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1576. std::string value = cmList::to_string(cmMakeRange(path).transform(convert));
  1577. status.GetMakefile().AddDefinition(args[2], value);
  1578. return true;
  1579. }
  1580. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1581. cmExecutionStatus& status)
  1582. {
  1583. return HandlePathCommand(args, ToCMakePath, status);
  1584. }
  1585. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1586. cmExecutionStatus& status)
  1587. {
  1588. return HandlePathCommand(args, ToNativePath, status);
  1589. }
  1590. #if !defined(CMAKE_BOOTSTRAP)
  1591. // Stuff for curl download/upload
  1592. using cmFileCommandVectorOfChar = std::vector<char>;
  1593. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1594. {
  1595. int realsize = static_cast<int>(size * nmemb);
  1596. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1597. if (fout) {
  1598. const char* chPtr = static_cast<char*>(ptr);
  1599. fout->write(chPtr, realsize);
  1600. }
  1601. return realsize;
  1602. }
  1603. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1604. void* data)
  1605. {
  1606. int realsize = static_cast<int>(size * nmemb);
  1607. const char* chPtr = static_cast<char*>(ptr);
  1608. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1609. chPtr + realsize);
  1610. return realsize;
  1611. }
  1612. int cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1613. size_t size, void* data)
  1614. {
  1615. cmFileCommandVectorOfChar& vec =
  1616. *static_cast<cmFileCommandVectorOfChar*>(data);
  1617. switch (type) {
  1618. case CURLINFO_TEXT:
  1619. case CURLINFO_HEADER_IN:
  1620. case CURLINFO_HEADER_OUT:
  1621. cm::append(vec, chPtr, chPtr + size);
  1622. break;
  1623. case CURLINFO_DATA_IN:
  1624. case CURLINFO_DATA_OUT:
  1625. case CURLINFO_SSL_DATA_IN:
  1626. case CURLINFO_SSL_DATA_OUT: {
  1627. char buf[128];
  1628. int n =
  1629. snprintf(buf, sizeof(buf), "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1630. static_cast<KWIML_INT_uint64_t>(size));
  1631. if (n > 0) {
  1632. cm::append(vec, buf, buf + n);
  1633. }
  1634. } break;
  1635. default:
  1636. break;
  1637. }
  1638. return 0;
  1639. }
  1640. # if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM >= 0x072000
  1641. const CURLoption CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_XFERINFOFUNCTION;
  1642. using cm_curl_off_t = curl_off_t;
  1643. # else
  1644. const CURLoption CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_PROGRESSFUNCTION;
  1645. using cm_curl_off_t = double;
  1646. # endif
  1647. class cURLProgressHelper
  1648. {
  1649. public:
  1650. cURLProgressHelper(cmMakefile* mf, const char* text)
  1651. : Makefile(mf)
  1652. , Text(text)
  1653. {
  1654. }
  1655. bool UpdatePercentage(cm_curl_off_t value, cm_curl_off_t total,
  1656. std::string& status)
  1657. {
  1658. long OldPercentage = this->CurrentPercentage;
  1659. if (total > 0) {
  1660. this->CurrentPercentage = std::lround(
  1661. static_cast<double>(value) / static_cast<double>(total) * 100.0);
  1662. if (this->CurrentPercentage > 100) {
  1663. // Avoid extra progress reports for unexpected data beyond total.
  1664. this->CurrentPercentage = 100;
  1665. }
  1666. }
  1667. bool updated = (OldPercentage != this->CurrentPercentage);
  1668. if (updated) {
  1669. status =
  1670. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1671. }
  1672. return updated;
  1673. }
  1674. cmMakefile* GetMakefile() { return this->Makefile; }
  1675. private:
  1676. long CurrentPercentage = -1;
  1677. cmMakefile* Makefile;
  1678. std::string Text;
  1679. };
  1680. int cmFileDownloadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1681. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1682. cm_curl_off_t ulnow)
  1683. {
  1684. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1685. static_cast<void>(ultotal);
  1686. static_cast<void>(ulnow);
  1687. std::string status;
  1688. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1689. cmMakefile* mf = helper->GetMakefile();
  1690. mf->DisplayStatus(status, -1);
  1691. }
  1692. return 0;
  1693. }
  1694. int cmFileUploadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1695. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1696. cm_curl_off_t ulnow)
  1697. {
  1698. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1699. static_cast<void>(dltotal);
  1700. static_cast<void>(dlnow);
  1701. std::string status;
  1702. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1703. cmMakefile* mf = helper->GetMakefile();
  1704. mf->DisplayStatus(status, -1);
  1705. }
  1706. return 0;
  1707. }
  1708. class cURLEasyGuard
  1709. {
  1710. public:
  1711. cURLEasyGuard(CURL* easy)
  1712. : Easy(easy)
  1713. {
  1714. }
  1715. ~cURLEasyGuard()
  1716. {
  1717. if (this->Easy) {
  1718. ::curl_easy_cleanup(this->Easy);
  1719. }
  1720. }
  1721. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1722. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1723. void release() { this->Easy = nullptr; }
  1724. private:
  1725. ::CURL* Easy;
  1726. };
  1727. #endif
  1728. #define check_curl_result(result, errstr) \
  1729. do { \
  1730. if (result != CURLE_OK) { \
  1731. std::string e(errstr); \
  1732. e += ::curl_easy_strerror(result); \
  1733. status.SetError(e); \
  1734. return false; \
  1735. } \
  1736. } while (false)
  1737. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1738. cmExecutionStatus& status)
  1739. {
  1740. #if !defined(CMAKE_BOOTSTRAP)
  1741. auto i = args.begin();
  1742. if (args.size() < 2) {
  1743. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1744. return false;
  1745. }
  1746. ++i; // Get rid of subcommand
  1747. std::string url = *i;
  1748. ++i;
  1749. std::string file;
  1750. long timeout = 0;
  1751. long inactivity_timeout = 0;
  1752. std::string logVar;
  1753. std::string statusVar;
  1754. cm::optional<std::string> tls_version;
  1755. cm::optional<bool> tls_verify;
  1756. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1757. std::string netrc_level =
  1758. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1759. std::string netrc_file =
  1760. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1761. std::string expectedHash;
  1762. std::string hashMatchMSG;
  1763. std::unique_ptr<cmCryptoHash> hash;
  1764. bool showProgress = false;
  1765. std::string userpwd;
  1766. std::vector<std::string> curl_headers;
  1767. std::vector<std::pair<std::string, cm::optional<std::string>>> curl_ranges;
  1768. while (i != args.end()) {
  1769. if (*i == "TIMEOUT") {
  1770. ++i;
  1771. if (i != args.end()) {
  1772. timeout = atol(i->c_str());
  1773. } else {
  1774. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1775. return false;
  1776. }
  1777. } else if (*i == "INACTIVITY_TIMEOUT") {
  1778. ++i;
  1779. if (i != args.end()) {
  1780. inactivity_timeout = atol(i->c_str());
  1781. } else {
  1782. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1783. return false;
  1784. }
  1785. } else if (*i == "LOG") {
  1786. ++i;
  1787. if (i == args.end()) {
  1788. status.SetError("DOWNLOAD missing VAR for LOG.");
  1789. return false;
  1790. }
  1791. logVar = *i;
  1792. } else if (*i == "STATUS") {
  1793. ++i;
  1794. if (i == args.end()) {
  1795. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1796. return false;
  1797. }
  1798. statusVar = *i;
  1799. } else if (*i == "TLS_VERSION") {
  1800. ++i;
  1801. if (i != args.end()) {
  1802. tls_version = *i;
  1803. } else {
  1804. status.SetError("DOWNLOAD missing value for TLS_VERSION.");
  1805. return false;
  1806. }
  1807. } else if (*i == "TLS_VERIFY") {
  1808. ++i;
  1809. if (i != args.end()) {
  1810. tls_verify = cmIsOn(*i);
  1811. } else {
  1812. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1813. return false;
  1814. }
  1815. } else if (*i == "TLS_CAINFO") {
  1816. ++i;
  1817. if (i != args.end()) {
  1818. cainfo = cmValue(*i);
  1819. } else {
  1820. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1821. return false;
  1822. }
  1823. } else if (*i == "NETRC_FILE") {
  1824. ++i;
  1825. if (i != args.end()) {
  1826. netrc_file = *i;
  1827. } else {
  1828. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1829. return false;
  1830. }
  1831. } else if (*i == "NETRC") {
  1832. ++i;
  1833. if (i != args.end()) {
  1834. netrc_level = *i;
  1835. } else {
  1836. status.SetError("DOWNLOAD missing level value for NETRC.");
  1837. return false;
  1838. }
  1839. } else if (*i == "EXPECTED_MD5") {
  1840. ++i;
  1841. if (i == args.end()) {
  1842. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1843. return false;
  1844. }
  1845. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1846. hashMatchMSG = "MD5 sum";
  1847. expectedHash = cmSystemTools::LowerCase(*i);
  1848. } else if (*i == "SHOW_PROGRESS") {
  1849. showProgress = true;
  1850. } else if (*i == "EXPECTED_HASH") {
  1851. ++i;
  1852. if (i == args.end()) {
  1853. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1854. return false;
  1855. }
  1856. std::string::size_type pos = i->find("=");
  1857. if (pos == std::string::npos) {
  1858. std::string err =
  1859. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1860. status.SetError(err);
  1861. return false;
  1862. }
  1863. std::string algo = i->substr(0, pos);
  1864. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1865. hash = cmCryptoHash::New(algo);
  1866. if (!hash) {
  1867. std::string err =
  1868. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1869. status.SetError(err);
  1870. return false;
  1871. }
  1872. hashMatchMSG = algo + " hash";
  1873. } else if (*i == "USERPWD") {
  1874. ++i;
  1875. if (i == args.end()) {
  1876. status.SetError("DOWNLOAD missing string for USERPWD.");
  1877. return false;
  1878. }
  1879. userpwd = *i;
  1880. } else if (*i == "HTTPHEADER") {
  1881. ++i;
  1882. if (i == args.end()) {
  1883. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1884. return false;
  1885. }
  1886. curl_headers.push_back(*i);
  1887. } else if (*i == "RANGE_START") {
  1888. ++i;
  1889. if (i == args.end()) {
  1890. status.SetError("DOWNLOAD missing value for RANGE_START.");
  1891. return false;
  1892. }
  1893. curl_ranges.emplace_back(*i, cm::nullopt);
  1894. } else if (*i == "RANGE_END") {
  1895. ++i;
  1896. if (curl_ranges.empty()) {
  1897. curl_ranges.emplace_back("0", *i);
  1898. } else {
  1899. auto& last_range = curl_ranges.back();
  1900. if (!last_range.second.has_value()) {
  1901. last_range.second = *i;
  1902. } else {
  1903. status.SetError("Multiple RANGE_END values is provided without "
  1904. "the corresponding RANGE_START.");
  1905. return false;
  1906. }
  1907. }
  1908. } else if (file.empty()) {
  1909. file = *i;
  1910. } else {
  1911. // Do not return error for compatibility reason.
  1912. std::string err = cmStrCat("Unexpected argument: ", *i);
  1913. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1914. }
  1915. ++i;
  1916. }
  1917. if (!tls_verify) {
  1918. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERIFY")) {
  1919. tls_verify = v.IsOn();
  1920. }
  1921. }
  1922. if (!tls_verify) {
  1923. if (cm::optional<std::string> v =
  1924. cmSystemTools::GetEnvVar("CMAKE_TLS_VERIFY")) {
  1925. tls_verify = cmIsOn(*v);
  1926. }
  1927. }
  1928. if (!tls_version) {
  1929. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERSION")) {
  1930. tls_version = *v;
  1931. }
  1932. }
  1933. if (!tls_version) {
  1934. if (cm::optional<std::string> v =
  1935. cmSystemTools::GetEnvVar("CMAKE_TLS_VERSION")) {
  1936. tls_version = std::move(v);
  1937. }
  1938. }
  1939. // Can't calculate hash if we don't save the file.
  1940. // TODO Incrementally calculate hash in the write callback as the file is
  1941. // being downloaded so this check can be relaxed.
  1942. if (file.empty() && hash) {
  1943. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1944. return false;
  1945. }
  1946. // If file exists already, and caller specified an expected md5 or sha,
  1947. // and the existing file already has the expected hash, then simply
  1948. // return.
  1949. //
  1950. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1951. std::string msg;
  1952. std::string actualHash = hash->HashFile(file);
  1953. if (actualHash == expectedHash) {
  1954. msg = cmStrCat("skipping download as file already exists with expected ",
  1955. hashMatchMSG, '"');
  1956. if (!statusVar.empty()) {
  1957. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1958. }
  1959. return true;
  1960. }
  1961. }
  1962. // Make sure parent directory exists so we can write to the file
  1963. // as we receive downloaded bits from curl...
  1964. //
  1965. if (!file.empty()) {
  1966. std::string dir = cmSystemTools::GetFilenamePath(file);
  1967. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1968. !cmSystemTools::MakeDirectory(dir)) {
  1969. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1970. dir +
  1971. "' - Specify file by full path name and verify that you "
  1972. "have directory creation and file write privileges.";
  1973. status.SetError(errstring);
  1974. return false;
  1975. }
  1976. }
  1977. cmsys::ofstream fout;
  1978. if (!file.empty()) {
  1979. fout.open(file.c_str(), std::ios::binary);
  1980. if (!fout) {
  1981. status.SetError("DOWNLOAD cannot open file for write.");
  1982. return false;
  1983. }
  1984. }
  1985. url = cmCurlFixFileURL(url);
  1986. ::CURL* curl;
  1987. cmCurlInitOnce();
  1988. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1989. curl = cm_curl_easy_init();
  1990. if (!curl) {
  1991. status.SetError("DOWNLOAD error initializing curl.");
  1992. return false;
  1993. }
  1994. cURLEasyGuard g_curl(curl);
  1995. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1996. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1997. // enable HTTP ERROR parsing
  1998. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1999. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  2000. curl_version_info_data* cv = curl_version_info(CURLVERSION_FIRST);
  2001. res = ::curl_easy_setopt(
  2002. curl, CURLOPT_USERAGENT,
  2003. cmStrCat("curl/", cv ? cv->version : LIBCURL_VERSION).c_str());
  2004. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  2005. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  2006. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  2007. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2008. cmFileCommandCurlDebugCallback);
  2009. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  2010. if (tls_version) {
  2011. if (cm::optional<int> v = cmCurlParseTLSVersion(*tls_version)) {
  2012. res = ::curl_easy_setopt(curl, CURLOPT_SSLVERSION, *v);
  2013. check_curl_result(
  2014. res,
  2015. cmStrCat("DOWNLOAD cannot set TLS/SSL version ", *tls_version, ": "));
  2016. } else {
  2017. status.SetError(
  2018. cmStrCat("DOWNLOAD given unknown TLS/SSL version ", *tls_version));
  2019. return false;
  2020. }
  2021. }
  2022. // check to see if TLS verification is requested
  2023. if (tls_verify && *tls_verify) {
  2024. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2025. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  2026. } else {
  2027. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2028. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  2029. }
  2030. for (const auto& range : curl_ranges) {
  2031. std::string curl_range = range.first + '-' +
  2032. (range.second.has_value() ? range.second.value() : "");
  2033. res = ::curl_easy_setopt(curl, CURLOPT_RANGE, curl_range.c_str());
  2034. check_curl_result(res, "DOWNLOAD cannot set range: ");
  2035. }
  2036. // check to see if a CAINFO file has been specified
  2037. // command arg comes first
  2038. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2039. if (!cainfo_err.empty()) {
  2040. status.SetError(cainfo_err);
  2041. return false;
  2042. }
  2043. // check to see if netrc parameters have been specified
  2044. // local command args takes precedence over CMAKE_NETRC*
  2045. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2046. std::string const& netrc_option_err =
  2047. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2048. if (!netrc_option_err.empty()) {
  2049. status.SetError(netrc_option_err);
  2050. return false;
  2051. }
  2052. cmFileCommandVectorOfChar chunkDebug;
  2053. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  2054. file.empty() ? nullptr : &fout);
  2055. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  2056. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2057. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  2058. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2059. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  2060. if (!logVar.empty()) {
  2061. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2062. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  2063. }
  2064. if (timeout > 0) {
  2065. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2066. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  2067. }
  2068. if (inactivity_timeout > 0) {
  2069. // Give up if there is no progress for a long time.
  2070. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2071. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2072. }
  2073. // Need the progress helper's scope to last through the duration of
  2074. // the curl_easy_perform call... so this object is declared at function
  2075. // scope intentionally, rather than inside the "if(showProgress)"
  2076. // block...
  2077. //
  2078. cURLProgressHelper helper(&status.GetMakefile(), "download");
  2079. if (showProgress) {
  2080. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2081. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  2082. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  2083. cmFileDownloadProgressCallback);
  2084. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  2085. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2086. reinterpret_cast<void*>(&helper));
  2087. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  2088. }
  2089. if (!userpwd.empty()) {
  2090. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2091. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  2092. }
  2093. struct curl_slist* headers = nullptr;
  2094. for (std::string const& h : curl_headers) {
  2095. headers = ::curl_slist_append(headers, h.c_str());
  2096. }
  2097. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2098. res = ::curl_easy_perform(curl);
  2099. ::curl_slist_free_all(headers);
  2100. /* always cleanup */
  2101. g_curl.release();
  2102. ::curl_easy_cleanup(curl);
  2103. if (!statusVar.empty()) {
  2104. status.GetMakefile().AddDefinition(
  2105. statusVar,
  2106. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2107. }
  2108. ::curl_global_cleanup();
  2109. // Ensure requested curl logs are returned (especially in case of failure)
  2110. //
  2111. if (!logVar.empty()) {
  2112. chunkDebug.push_back(0);
  2113. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  2114. }
  2115. // Explicitly flush/close so we can measure the md5 accurately.
  2116. //
  2117. if (!file.empty()) {
  2118. fout.flush();
  2119. fout.close();
  2120. }
  2121. // Verify MD5 sum if requested:
  2122. //
  2123. if (hash) {
  2124. if (res != CURLE_OK) {
  2125. status.SetError(cmStrCat(
  2126. "DOWNLOAD cannot compute hash on failed download\n"
  2127. " status: [",
  2128. static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\"]"));
  2129. return false;
  2130. }
  2131. std::string actualHash = hash->HashFile(file);
  2132. if (actualHash.empty()) {
  2133. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  2134. return false;
  2135. }
  2136. if (expectedHash != actualHash) {
  2137. if (!statusVar.empty() && res == 0) {
  2138. status.GetMakefile().AddDefinition(statusVar,
  2139. "1;HASH mismatch: "
  2140. "expected: " +
  2141. expectedHash +
  2142. " actual: " + actualHash);
  2143. }
  2144. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  2145. " for file: [",
  2146. file,
  2147. "]\n"
  2148. " expected hash: [",
  2149. expectedHash,
  2150. "]\n"
  2151. " actual hash: [",
  2152. actualHash, "]\n"));
  2153. return false;
  2154. }
  2155. }
  2156. return true;
  2157. #else
  2158. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  2159. return false;
  2160. #endif
  2161. }
  2162. bool HandleUploadCommand(std::vector<std::string> const& args,
  2163. cmExecutionStatus& status)
  2164. {
  2165. #if !defined(CMAKE_BOOTSTRAP)
  2166. if (args.size() < 3) {
  2167. status.SetError("UPLOAD must be called with at least three arguments.");
  2168. return false;
  2169. }
  2170. auto i = args.begin();
  2171. ++i;
  2172. std::string filename = *i;
  2173. ++i;
  2174. std::string url = *i;
  2175. ++i;
  2176. long timeout = 0;
  2177. long inactivity_timeout = 0;
  2178. std::string logVar;
  2179. std::string statusVar;
  2180. bool showProgress = false;
  2181. cm::optional<std::string> tls_version;
  2182. cm::optional<bool> tls_verify;
  2183. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  2184. std::string userpwd;
  2185. std::string netrc_level =
  2186. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  2187. std::string netrc_file =
  2188. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  2189. std::vector<std::string> curl_headers;
  2190. while (i != args.end()) {
  2191. if (*i == "TIMEOUT") {
  2192. ++i;
  2193. if (i != args.end()) {
  2194. timeout = atol(i->c_str());
  2195. } else {
  2196. status.SetError("UPLOAD missing time for TIMEOUT.");
  2197. return false;
  2198. }
  2199. } else if (*i == "INACTIVITY_TIMEOUT") {
  2200. ++i;
  2201. if (i != args.end()) {
  2202. inactivity_timeout = atol(i->c_str());
  2203. } else {
  2204. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  2205. return false;
  2206. }
  2207. } else if (*i == "LOG") {
  2208. ++i;
  2209. if (i == args.end()) {
  2210. status.SetError("UPLOAD missing VAR for LOG.");
  2211. return false;
  2212. }
  2213. logVar = *i;
  2214. } else if (*i == "STATUS") {
  2215. ++i;
  2216. if (i == args.end()) {
  2217. status.SetError("UPLOAD missing VAR for STATUS.");
  2218. return false;
  2219. }
  2220. statusVar = *i;
  2221. } else if (*i == "SHOW_PROGRESS") {
  2222. showProgress = true;
  2223. } else if (*i == "TLS_VERSION") {
  2224. ++i;
  2225. if (i != args.end()) {
  2226. tls_version = *i;
  2227. } else {
  2228. status.SetError("UPLOAD missing value for TLS_VERSION.");
  2229. return false;
  2230. }
  2231. } else if (*i == "TLS_VERIFY") {
  2232. ++i;
  2233. if (i != args.end()) {
  2234. tls_verify = cmIsOn(*i);
  2235. } else {
  2236. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  2237. return false;
  2238. }
  2239. } else if (*i == "TLS_CAINFO") {
  2240. ++i;
  2241. if (i != args.end()) {
  2242. cainfo = cmValue(*i);
  2243. } else {
  2244. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  2245. return false;
  2246. }
  2247. } else if (*i == "NETRC_FILE") {
  2248. ++i;
  2249. if (i != args.end()) {
  2250. netrc_file = *i;
  2251. } else {
  2252. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  2253. return false;
  2254. }
  2255. } else if (*i == "NETRC") {
  2256. ++i;
  2257. if (i != args.end()) {
  2258. netrc_level = *i;
  2259. } else {
  2260. status.SetError("UPLOAD missing level value for NETRC.");
  2261. return false;
  2262. }
  2263. } else if (*i == "USERPWD") {
  2264. ++i;
  2265. if (i == args.end()) {
  2266. status.SetError("UPLOAD missing string for USERPWD.");
  2267. return false;
  2268. }
  2269. userpwd = *i;
  2270. } else if (*i == "HTTPHEADER") {
  2271. ++i;
  2272. if (i == args.end()) {
  2273. status.SetError("UPLOAD missing string for HTTPHEADER.");
  2274. return false;
  2275. }
  2276. curl_headers.push_back(*i);
  2277. } else {
  2278. // Do not return error for compatibility reason.
  2279. std::string err = cmStrCat("Unexpected argument: ", *i);
  2280. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  2281. }
  2282. ++i;
  2283. }
  2284. if (!tls_verify) {
  2285. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERIFY")) {
  2286. tls_verify = v.IsOn();
  2287. }
  2288. }
  2289. if (!tls_verify) {
  2290. if (cm::optional<std::string> v =
  2291. cmSystemTools::GetEnvVar("CMAKE_TLS_VERIFY")) {
  2292. tls_verify = cmIsOn(*v);
  2293. }
  2294. }
  2295. if (!tls_version) {
  2296. if (cmValue v = status.GetMakefile().GetDefinition("CMAKE_TLS_VERSION")) {
  2297. tls_version = *v;
  2298. }
  2299. }
  2300. if (!tls_version) {
  2301. if (cm::optional<std::string> v =
  2302. cmSystemTools::GetEnvVar("CMAKE_TLS_VERSION")) {
  2303. tls_version = std::move(v);
  2304. }
  2305. }
  2306. // Open file for reading:
  2307. //
  2308. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2309. if (!fin) {
  2310. std::string errStr =
  2311. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  2312. status.SetError(errStr);
  2313. return false;
  2314. }
  2315. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2316. url = cmCurlFixFileURL(url);
  2317. ::CURL* curl;
  2318. cmCurlInitOnce();
  2319. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2320. curl = cm_curl_easy_init();
  2321. if (!curl) {
  2322. status.SetError("UPLOAD error initializing curl.");
  2323. fclose(fin);
  2324. return false;
  2325. }
  2326. cURLEasyGuard g_curl(curl);
  2327. // enable HTTP ERROR parsing
  2328. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2329. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2330. // enable uploading
  2331. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2332. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2333. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2334. check_curl_result(res, "UPLOAD cannot set url: ");
  2335. res =
  2336. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2337. check_curl_result(res, "UPLOAD cannot set write function: ");
  2338. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2339. cmFileCommandCurlDebugCallback);
  2340. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2341. if (tls_version) {
  2342. if (cm::optional<int> v = cmCurlParseTLSVersion(*tls_version)) {
  2343. res = ::curl_easy_setopt(curl, CURLOPT_SSLVERSION, *v);
  2344. check_curl_result(
  2345. res,
  2346. cmStrCat("UPLOAD cannot set TLS/SSL version ", *tls_version, ": "));
  2347. } else {
  2348. status.SetError(
  2349. cmStrCat("UPLOAD given unknown TLS/SSL version ", *tls_version));
  2350. return false;
  2351. }
  2352. }
  2353. // check to see if TLS verification is requested
  2354. if (tls_verify && *tls_verify) {
  2355. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2356. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  2357. } else {
  2358. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2359. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  2360. }
  2361. // check to see if a CAINFO file has been specified
  2362. // command arg comes first
  2363. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2364. if (!cainfo_err.empty()) {
  2365. status.SetError(cainfo_err);
  2366. return false;
  2367. }
  2368. cmFileCommandVectorOfChar chunkResponse;
  2369. cmFileCommandVectorOfChar chunkDebug;
  2370. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2371. check_curl_result(res, "UPLOAD cannot set write data: ");
  2372. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2373. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2374. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2375. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2376. if (!logVar.empty()) {
  2377. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2378. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2379. }
  2380. if (timeout > 0) {
  2381. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2382. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2383. }
  2384. if (inactivity_timeout > 0) {
  2385. // Give up if there is no progress for a long time.
  2386. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2387. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2388. }
  2389. // Need the progress helper's scope to last through the duration of
  2390. // the curl_easy_perform call... so this object is declared at function
  2391. // scope intentionally, rather than inside the "if(showProgress)"
  2392. // block...
  2393. //
  2394. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2395. if (showProgress) {
  2396. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2397. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2398. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  2399. cmFileUploadProgressCallback);
  2400. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2401. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2402. reinterpret_cast<void*>(&helper));
  2403. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2404. }
  2405. // now specify which file to upload
  2406. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2407. check_curl_result(res, "UPLOAD cannot set input file: ");
  2408. // and give the size of the upload (optional)
  2409. res =
  2410. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2411. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2412. if (!userpwd.empty()) {
  2413. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2414. check_curl_result(res, "UPLOAD cannot set user password: ");
  2415. }
  2416. // check to see if netrc parameters have been specified
  2417. // local command args takes precedence over CMAKE_NETRC*
  2418. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2419. std::string const& netrc_option_err =
  2420. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2421. if (!netrc_option_err.empty()) {
  2422. status.SetError(netrc_option_err);
  2423. return false;
  2424. }
  2425. struct curl_slist* headers = nullptr;
  2426. for (std::string const& h : curl_headers) {
  2427. headers = ::curl_slist_append(headers, h.c_str());
  2428. }
  2429. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2430. res = ::curl_easy_perform(curl);
  2431. ::curl_slist_free_all(headers);
  2432. /* always cleanup */
  2433. g_curl.release();
  2434. ::curl_easy_cleanup(curl);
  2435. if (!statusVar.empty()) {
  2436. status.GetMakefile().AddDefinition(
  2437. statusVar,
  2438. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2439. }
  2440. ::curl_global_cleanup();
  2441. fclose(fin);
  2442. fin = nullptr;
  2443. if (!logVar.empty()) {
  2444. std::string log;
  2445. if (!chunkResponse.empty()) {
  2446. chunkResponse.push_back(0);
  2447. log += "Response:\n";
  2448. log += chunkResponse.data();
  2449. log += "\n";
  2450. }
  2451. if (!chunkDebug.empty()) {
  2452. chunkDebug.push_back(0);
  2453. log += "Debug:\n";
  2454. log += chunkDebug.data();
  2455. log += "\n";
  2456. }
  2457. status.GetMakefile().AddDefinition(logVar, log);
  2458. }
  2459. return true;
  2460. #else
  2461. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2462. return false;
  2463. #endif
  2464. }
  2465. void AddEvaluationFile(const std::string& inputName,
  2466. const std::string& targetName,
  2467. const std::string& outputExpr,
  2468. const std::string& condition, bool inputIsContent,
  2469. const std::string& newLineCharacter, mode_t permissions,
  2470. cmExecutionStatus& status)
  2471. {
  2472. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2473. cmGeneratorExpression outputGe(*status.GetMakefile().GetCMakeInstance(),
  2474. lfbt);
  2475. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2476. outputGe.Parse(outputExpr);
  2477. cmGeneratorExpression conditionGe(*status.GetMakefile().GetCMakeInstance(),
  2478. lfbt);
  2479. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2480. conditionGe.Parse(condition);
  2481. status.GetMakefile().AddEvaluationFile(
  2482. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2483. newLineCharacter, permissions, inputIsContent);
  2484. }
  2485. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2486. cmExecutionStatus& status)
  2487. {
  2488. if (args.size() < 5) {
  2489. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2490. return false;
  2491. }
  2492. struct Arguments : public ArgumentParser::ParseResult
  2493. {
  2494. cm::optional<std::string> Output;
  2495. cm::optional<std::string> Input;
  2496. cm::optional<std::string> Content;
  2497. cm::optional<std::string> Condition;
  2498. cm::optional<std::string> Target;
  2499. cm::optional<std::string> NewLineStyle;
  2500. bool NoSourcePermissions = false;
  2501. bool UseSourcePermissions = false;
  2502. ArgumentParser::NonEmpty<std::vector<std::string>> FilePermissions;
  2503. std::vector<cm::string_view> ParsedKeywords;
  2504. };
  2505. static auto const parser =
  2506. cmArgumentParser<Arguments>{}
  2507. .Bind("OUTPUT"_s, &Arguments::Output)
  2508. .Bind("INPUT"_s, &Arguments::Input)
  2509. .Bind("CONTENT"_s, &Arguments::Content)
  2510. .Bind("CONDITION"_s, &Arguments::Condition)
  2511. .Bind("TARGET"_s, &Arguments::Target)
  2512. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2513. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2514. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2515. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle)
  2516. .BindParsedKeywords(&Arguments::ParsedKeywords);
  2517. std::vector<std::string> unparsedArguments;
  2518. Arguments const arguments =
  2519. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments);
  2520. if (arguments.MaybeReportError(status.GetMakefile())) {
  2521. return true;
  2522. }
  2523. if (!unparsedArguments.empty()) {
  2524. status.SetError("Unknown argument to GENERATE subcommand.");
  2525. return false;
  2526. }
  2527. if (!arguments.Output || arguments.ParsedKeywords[0] != "OUTPUT"_s) {
  2528. status.SetError("GENERATE requires OUTPUT as first option.");
  2529. return false;
  2530. }
  2531. std::string const& output = *arguments.Output;
  2532. if (!arguments.Input && !arguments.Content) {
  2533. status.SetError("GENERATE requires INPUT or CONTENT option.");
  2534. return false;
  2535. }
  2536. const bool inputIsContent = arguments.ParsedKeywords[1] == "CONTENT"_s;
  2537. if (!inputIsContent && arguments.ParsedKeywords[1] != "INPUT") {
  2538. status.SetError("Unknown argument to GENERATE subcommand.");
  2539. return false;
  2540. }
  2541. std::string const& input =
  2542. inputIsContent ? *arguments.Content : *arguments.Input;
  2543. if (arguments.Condition && arguments.Condition->empty()) {
  2544. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2545. "if specified.");
  2546. return false;
  2547. }
  2548. std::string const& condition =
  2549. arguments.Condition ? *arguments.Condition : std::string();
  2550. if (arguments.Target && arguments.Target->empty()) {
  2551. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2552. "if specified.");
  2553. return false;
  2554. }
  2555. std::string const& target =
  2556. arguments.Target ? *arguments.Target : std::string();
  2557. cmNewLineStyle newLineStyle;
  2558. if (arguments.NewLineStyle) {
  2559. std::string errorMessage;
  2560. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2561. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2562. return false;
  2563. }
  2564. }
  2565. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2566. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2567. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2568. return false;
  2569. }
  2570. if (!arguments.FilePermissions.empty()) {
  2571. if (arguments.NoSourcePermissions) {
  2572. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2573. "FILE_PERMISSIONS. Only one option allowed.");
  2574. return false;
  2575. }
  2576. if (arguments.UseSourcePermissions) {
  2577. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2578. "FILE_PERMISSIONS. Only one option allowed.");
  2579. return false;
  2580. }
  2581. }
  2582. if (arguments.UseSourcePermissions) {
  2583. if (inputIsContent) {
  2584. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2585. return false;
  2586. }
  2587. }
  2588. mode_t permissions = 0;
  2589. if (arguments.NoSourcePermissions) {
  2590. permissions |= cmFSPermissions::mode_owner_read;
  2591. permissions |= cmFSPermissions::mode_owner_write;
  2592. permissions |= cmFSPermissions::mode_group_read;
  2593. permissions |= cmFSPermissions::mode_world_read;
  2594. }
  2595. if (!arguments.FilePermissions.empty()) {
  2596. std::vector<std::string> invalidOptions;
  2597. for (auto const& e : arguments.FilePermissions) {
  2598. if (!cmFSPermissions::stringToModeT(e, permissions)) {
  2599. invalidOptions.push_back(e);
  2600. }
  2601. }
  2602. if (!invalidOptions.empty()) {
  2603. std::ostringstream oss;
  2604. oss << "given invalid permission ";
  2605. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2606. if (i == 0u) {
  2607. oss << "\"" << invalidOptions[i] << "\"";
  2608. } else {
  2609. oss << ",\"" << invalidOptions[i] << "\"";
  2610. }
  2611. }
  2612. oss << ".";
  2613. status.SetError(oss.str());
  2614. return false;
  2615. }
  2616. }
  2617. AddEvaluationFile(input, target, output, condition, inputIsContent,
  2618. newLineStyle.GetCharacters(), permissions, status);
  2619. return true;
  2620. }
  2621. bool HandleLockCommand(std::vector<std::string> const& args,
  2622. cmExecutionStatus& status)
  2623. {
  2624. #if !defined(CMAKE_BOOTSTRAP)
  2625. // Default values
  2626. bool directory = false;
  2627. bool release = false;
  2628. enum Guard
  2629. {
  2630. GUARD_FUNCTION,
  2631. GUARD_FILE,
  2632. GUARD_PROCESS
  2633. };
  2634. Guard guard = GUARD_PROCESS;
  2635. std::string resultVariable;
  2636. unsigned long timeout = static_cast<unsigned long>(-1);
  2637. // Parse arguments
  2638. if (args.size() < 2) {
  2639. status.GetMakefile().IssueMessage(
  2640. MessageType::FATAL_ERROR,
  2641. "sub-command LOCK requires at least two arguments.");
  2642. return false;
  2643. }
  2644. std::string path = args[1];
  2645. for (unsigned i = 2; i < args.size(); ++i) {
  2646. if (args[i] == "DIRECTORY") {
  2647. directory = true;
  2648. } else if (args[i] == "RELEASE") {
  2649. release = true;
  2650. } else if (args[i] == "GUARD") {
  2651. ++i;
  2652. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2653. if (i >= args.size()) {
  2654. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2655. return false;
  2656. }
  2657. if (args[i] == "FUNCTION") {
  2658. guard = GUARD_FUNCTION;
  2659. } else if (args[i] == "FILE") {
  2660. guard = GUARD_FILE;
  2661. } else if (args[i] == "PROCESS") {
  2662. guard = GUARD_PROCESS;
  2663. } else {
  2664. status.GetMakefile().IssueMessage(
  2665. MessageType::FATAL_ERROR,
  2666. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2667. return false;
  2668. }
  2669. } else if (args[i] == "RESULT_VARIABLE") {
  2670. ++i;
  2671. if (i >= args.size()) {
  2672. status.GetMakefile().IssueMessage(
  2673. MessageType::FATAL_ERROR,
  2674. "expected variable name after RESULT_VARIABLE");
  2675. return false;
  2676. }
  2677. resultVariable = args[i];
  2678. } else if (args[i] == "TIMEOUT") {
  2679. ++i;
  2680. if (i >= args.size()) {
  2681. status.GetMakefile().IssueMessage(
  2682. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2683. return false;
  2684. }
  2685. long scanned;
  2686. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2687. status.GetMakefile().IssueMessage(
  2688. MessageType::FATAL_ERROR,
  2689. cmStrCat("TIMEOUT value \"", args[i],
  2690. "\" is not an unsigned integer."));
  2691. return false;
  2692. }
  2693. timeout = static_cast<unsigned long>(scanned);
  2694. } else {
  2695. status.GetMakefile().IssueMessage(
  2696. MessageType::FATAL_ERROR,
  2697. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2698. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2699. return false;
  2700. }
  2701. }
  2702. if (directory) {
  2703. path += "/cmake.lock";
  2704. }
  2705. // Unify path (remove '//', '/../', ...)
  2706. path = cmSystemTools::CollapseFullPath(
  2707. path, status.GetMakefile().GetCurrentSourceDirectory());
  2708. // Create file and directories if needed
  2709. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2710. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2711. status.GetMakefile().IssueMessage(
  2712. MessageType::FATAL_ERROR,
  2713. cmStrCat("directory\n \"", parentDir,
  2714. "\"\ncreation failed (check permissions)."));
  2715. cmSystemTools::SetFatalErrorOccurred();
  2716. return false;
  2717. }
  2718. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2719. if (!file) {
  2720. status.GetMakefile().IssueMessage(
  2721. MessageType::FATAL_ERROR,
  2722. cmStrCat("file\n \"", path,
  2723. "\"\ncreation failed (check permissions)."));
  2724. cmSystemTools::SetFatalErrorOccurred();
  2725. return false;
  2726. }
  2727. fclose(file);
  2728. // Actual lock/unlock
  2729. cmFileLockPool& lockPool =
  2730. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2731. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2732. if (release) {
  2733. fileLockResult = lockPool.Release(path);
  2734. } else {
  2735. switch (guard) {
  2736. case GUARD_FUNCTION:
  2737. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2738. break;
  2739. case GUARD_FILE:
  2740. fileLockResult = lockPool.LockFileScope(path, timeout);
  2741. break;
  2742. case GUARD_PROCESS:
  2743. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2744. break;
  2745. default:
  2746. cmSystemTools::SetFatalErrorOccurred();
  2747. return false;
  2748. }
  2749. }
  2750. const std::string result = fileLockResult.GetOutputMessage();
  2751. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2752. status.GetMakefile().IssueMessage(
  2753. MessageType::FATAL_ERROR,
  2754. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2755. cmSystemTools::SetFatalErrorOccurred();
  2756. return false;
  2757. }
  2758. if (!resultVariable.empty()) {
  2759. status.GetMakefile().AddDefinition(resultVariable, result);
  2760. }
  2761. return true;
  2762. #else
  2763. static_cast<void>(args);
  2764. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2765. return false;
  2766. #endif
  2767. }
  2768. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2769. cmExecutionStatus& status)
  2770. {
  2771. if (args.size() < 3) {
  2772. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2773. return false;
  2774. }
  2775. if (args.size() > 5) {
  2776. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2777. return false;
  2778. }
  2779. unsigned int argsIndex = 1;
  2780. std::string filename = args[argsIndex++];
  2781. if (!cmsys::SystemTools::FileIsFullPath(filename)) {
  2782. filename = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  2783. filename);
  2784. }
  2785. const std::string& outputVariable = args[argsIndex++];
  2786. std::string formatString;
  2787. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2788. formatString = args[argsIndex++];
  2789. }
  2790. bool utcFlag = false;
  2791. if (args.size() > argsIndex) {
  2792. if (args[argsIndex] == "UTC") {
  2793. utcFlag = true;
  2794. } else {
  2795. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2796. args[argsIndex] + ".";
  2797. status.SetError(e);
  2798. return false;
  2799. }
  2800. }
  2801. cmTimestamp timestamp;
  2802. std::string result =
  2803. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2804. status.GetMakefile().AddDefinition(outputVariable, result);
  2805. return true;
  2806. }
  2807. bool HandleSizeCommand(std::vector<std::string> const& args,
  2808. cmExecutionStatus& status)
  2809. {
  2810. if (args.size() != 3) {
  2811. status.SetError(
  2812. cmStrCat(args[0], " requires a file name and output variable"));
  2813. return false;
  2814. }
  2815. unsigned int argsIndex = 1;
  2816. const std::string& filename = args[argsIndex++];
  2817. const std::string& outputVariable = args[argsIndex++];
  2818. if (!cmSystemTools::FileExists(filename, true)) {
  2819. status.SetError(
  2820. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2821. return false;
  2822. }
  2823. status.GetMakefile().AddDefinition(
  2824. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2825. return true;
  2826. }
  2827. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2828. cmExecutionStatus& status)
  2829. {
  2830. if (args.size() != 3) {
  2831. status.SetError(
  2832. cmStrCat(args[0], " requires a file name and output variable"));
  2833. return false;
  2834. }
  2835. const std::string& filename = args[1];
  2836. const std::string& outputVariable = args[2];
  2837. std::string result;
  2838. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2839. status.SetError(cmStrCat(
  2840. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2841. return false;
  2842. }
  2843. status.GetMakefile().AddDefinition(outputVariable, result);
  2844. return true;
  2845. }
  2846. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2847. cmExecutionStatus& status)
  2848. {
  2849. if (args.size() < 3) {
  2850. status.SetError("CREATE_LINK must be called with at least two additional "
  2851. "arguments");
  2852. return false;
  2853. }
  2854. std::string const& fileName = args[1];
  2855. std::string const& newFileName = args[2];
  2856. struct Arguments
  2857. {
  2858. std::string Result;
  2859. bool CopyOnError = false;
  2860. bool Symbolic = false;
  2861. };
  2862. static auto const parser =
  2863. cmArgumentParser<Arguments>{}
  2864. .Bind("RESULT"_s, &Arguments::Result)
  2865. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2866. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2867. std::vector<std::string> unconsumedArgs;
  2868. Arguments const arguments =
  2869. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2870. if (!unconsumedArgs.empty()) {
  2871. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2872. return false;
  2873. }
  2874. // The system error message generated in the operation.
  2875. std::string result;
  2876. // Check if the paths are distinct.
  2877. if (fileName == newFileName) {
  2878. result = "CREATE_LINK cannot use same file and newfile";
  2879. if (!arguments.Result.empty()) {
  2880. status.GetMakefile().AddDefinition(arguments.Result, result);
  2881. return true;
  2882. }
  2883. status.SetError(result);
  2884. return false;
  2885. }
  2886. // Hard link requires original file to exist.
  2887. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2888. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2889. if (!arguments.Result.empty()) {
  2890. status.GetMakefile().AddDefinition(arguments.Result, result);
  2891. return true;
  2892. }
  2893. status.SetError(result);
  2894. return false;
  2895. }
  2896. // Check if the new file already exists and remove it.
  2897. if (cmSystemTools::PathExists(newFileName) &&
  2898. !cmSystemTools::RemoveFile(newFileName)) {
  2899. auto err = cmStrCat("Failed to create link '", newFileName,
  2900. "' because existing path cannot be removed: ",
  2901. cmSystemTools::GetLastSystemError(), '\n');
  2902. if (!arguments.Result.empty()) {
  2903. status.GetMakefile().AddDefinition(arguments.Result, err);
  2904. return true;
  2905. }
  2906. status.SetError(err);
  2907. return false;
  2908. }
  2909. // Whether the operation completed successfully.
  2910. bool completed = false;
  2911. // Check if the command requires a symbolic link.
  2912. if (arguments.Symbolic) {
  2913. cmsys::Status linked =
  2914. cmSystemTools::CreateSymlinkQuietly(fileName, newFileName);
  2915. if (linked) {
  2916. completed = true;
  2917. } else {
  2918. result = cmStrCat("failed to create symbolic link '", newFileName,
  2919. "': ", linked.GetString());
  2920. }
  2921. } else {
  2922. cmsys::Status linked =
  2923. cmSystemTools::CreateLinkQuietly(fileName, newFileName);
  2924. if (linked) {
  2925. completed = true;
  2926. } else {
  2927. result = cmStrCat("failed to create link '", newFileName,
  2928. "': ", linked.GetString());
  2929. }
  2930. }
  2931. // Check if copy-on-error is enabled in the arguments.
  2932. if (!completed && arguments.CopyOnError) {
  2933. cmsys::Status copied =
  2934. cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2935. if (copied) {
  2936. completed = true;
  2937. } else {
  2938. result = "Copy failed: " + copied.GetString();
  2939. }
  2940. }
  2941. // Check if the operation was successful.
  2942. if (completed) {
  2943. result = "0";
  2944. } else if (arguments.Result.empty()) {
  2945. // The operation failed and the result is not reported in a variable.
  2946. status.SetError(result);
  2947. return false;
  2948. }
  2949. if (!arguments.Result.empty()) {
  2950. status.GetMakefile().AddDefinition(arguments.Result, result);
  2951. }
  2952. return true;
  2953. }
  2954. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2955. cmExecutionStatus& status)
  2956. {
  2957. std::string platform =
  2958. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2959. if (!cmRuntimeDependencyArchive::PlatformSupportsRuntimeDependencies(
  2960. platform)) {
  2961. status.SetError(
  2962. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2963. platform, "\""));
  2964. cmSystemTools::SetFatalErrorOccurred();
  2965. return false;
  2966. }
  2967. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2968. status.GetMakefile().IssueMessage(
  2969. MessageType::AUTHOR_WARNING,
  2970. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2971. " in project mode. This is probably not what "
  2972. "you intended to do. Instead, please consider"
  2973. " using it in an install(CODE) or "
  2974. "install(SCRIPT) command. For example:"
  2975. "\n install(CODE [["
  2976. "\n file(GET_RUNTIME_DEPENDENCIES"
  2977. "\n # ..."
  2978. "\n )"
  2979. "\n ]])");
  2980. }
  2981. struct Arguments : public ArgumentParser::ParseResult
  2982. {
  2983. std::string ResolvedDependenciesVar;
  2984. std::string UnresolvedDependenciesVar;
  2985. std::string ConflictingDependenciesPrefix;
  2986. std::string RPathPrefix;
  2987. std::string BundleExecutable;
  2988. ArgumentParser::MaybeEmpty<std::vector<std::string>> Executables;
  2989. ArgumentParser::MaybeEmpty<std::vector<std::string>> Libraries;
  2990. ArgumentParser::MaybeEmpty<std::vector<std::string>> Directories;
  2991. ArgumentParser::MaybeEmpty<std::vector<std::string>> Modules;
  2992. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreIncludeRegexes;
  2993. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreExcludeRegexes;
  2994. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeRegexes;
  2995. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeRegexes;
  2996. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeFiles;
  2997. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeFiles;
  2998. ArgumentParser::MaybeEmpty<std::vector<std::string>>
  2999. PostExcludeFilesStrict;
  3000. };
  3001. static auto const parser =
  3002. cmArgumentParser<Arguments>{}
  3003. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  3004. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  3005. &Arguments::UnresolvedDependenciesVar)
  3006. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  3007. &Arguments::ConflictingDependenciesPrefix)
  3008. .Bind("RPATH_PREFIX"_s, &Arguments::RPathPrefix)
  3009. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  3010. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  3011. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  3012. .Bind("MODULES"_s, &Arguments::Modules)
  3013. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  3014. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  3015. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  3016. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  3017. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes)
  3018. .Bind("POST_INCLUDE_FILES"_s, &Arguments::PostIncludeFiles)
  3019. .Bind("POST_EXCLUDE_FILES"_s, &Arguments::PostExcludeFiles)
  3020. .Bind("POST_EXCLUDE_FILES_STRICT"_s, &Arguments::PostExcludeFilesStrict);
  3021. std::vector<std::string> unrecognizedArguments;
  3022. auto parsedArgs =
  3023. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3024. auto argIt = unrecognizedArguments.begin();
  3025. if (argIt != unrecognizedArguments.end()) {
  3026. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3027. cmSystemTools::SetFatalErrorOccurred();
  3028. return false;
  3029. }
  3030. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3031. cmSystemTools::SetFatalErrorOccurred();
  3032. return true;
  3033. }
  3034. cmRuntimeDependencyArchive archive(
  3035. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  3036. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  3037. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes,
  3038. std::move(parsedArgs.PostIncludeFiles),
  3039. std::move(parsedArgs.PostExcludeFiles),
  3040. std::move(parsedArgs.PostExcludeFilesStrict));
  3041. if (!archive.Prepare()) {
  3042. cmSystemTools::SetFatalErrorOccurred();
  3043. return false;
  3044. }
  3045. if (!archive.GetRuntimeDependencies(
  3046. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  3047. cmSystemTools::SetFatalErrorOccurred();
  3048. return false;
  3049. }
  3050. std::vector<std::string> deps;
  3051. std::vector<std::string> unresolvedDeps;
  3052. std::vector<std::string> conflictingDeps;
  3053. for (auto const& val : archive.GetResolvedPaths()) {
  3054. bool unique = true;
  3055. auto it = val.second.begin();
  3056. assert(it != val.second.end());
  3057. auto const& firstPath = *it;
  3058. while (++it != val.second.end()) {
  3059. if (!cmSystemTools::SameFile(firstPath, *it)) {
  3060. unique = false;
  3061. break;
  3062. }
  3063. }
  3064. if (unique) {
  3065. deps.push_back(firstPath);
  3066. if (!parsedArgs.RPathPrefix.empty()) {
  3067. status.GetMakefile().AddDefinition(
  3068. parsedArgs.RPathPrefix + "_" + firstPath,
  3069. cmList::to_string(archive.GetRPaths().at(firstPath)));
  3070. }
  3071. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  3072. conflictingDeps.push_back(val.first);
  3073. std::vector<std::string> paths;
  3074. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  3075. std::string varName =
  3076. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  3077. std::string pathsStr = cmList::to_string(paths);
  3078. status.GetMakefile().AddDefinition(varName, pathsStr);
  3079. } else {
  3080. std::ostringstream e;
  3081. e << "Multiple conflicting paths found for " << val.first << ":";
  3082. for (auto const& path : val.second) {
  3083. e << "\n " << path;
  3084. }
  3085. status.SetError(e.str());
  3086. cmSystemTools::SetFatalErrorOccurred();
  3087. return false;
  3088. }
  3089. }
  3090. if (!archive.GetUnresolvedPaths().empty()) {
  3091. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  3092. unresolvedDeps.insert(unresolvedDeps.begin(),
  3093. archive.GetUnresolvedPaths().begin(),
  3094. archive.GetUnresolvedPaths().end());
  3095. } else {
  3096. std::ostringstream e;
  3097. e << "Could not resolve runtime dependencies:";
  3098. for (auto const& path : archive.GetUnresolvedPaths()) {
  3099. e << "\n " << path;
  3100. }
  3101. status.SetError(e.str());
  3102. cmSystemTools::SetFatalErrorOccurred();
  3103. return false;
  3104. }
  3105. }
  3106. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  3107. std::string val = cmList::to_string(deps);
  3108. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  3109. val);
  3110. }
  3111. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  3112. std::string val = cmList::to_string(unresolvedDeps);
  3113. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  3114. val);
  3115. }
  3116. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  3117. std::string val = cmList::to_string(conflictingDeps);
  3118. status.GetMakefile().AddDefinition(
  3119. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  3120. }
  3121. return true;
  3122. }
  3123. bool HandleConfigureCommand(std::vector<std::string> const& args,
  3124. cmExecutionStatus& status)
  3125. {
  3126. struct Arguments : public ArgumentParser::ParseResult
  3127. {
  3128. cm::optional<std::string> Output;
  3129. cm::optional<std::string> Content;
  3130. bool EscapeQuotes = false;
  3131. bool AtOnly = false;
  3132. // "NEWLINE_STYLE" requires one value, but we use a custom check below.
  3133. ArgumentParser::Maybe<std::string> NewlineStyle;
  3134. };
  3135. static auto const parser =
  3136. cmArgumentParser<Arguments>{}
  3137. .Bind("OUTPUT"_s, &Arguments::Output)
  3138. .Bind("CONTENT"_s, &Arguments::Content)
  3139. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  3140. .Bind("@ONLY"_s, &Arguments::AtOnly)
  3141. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  3142. std::vector<std::string> unrecognizedArguments;
  3143. auto parsedArgs =
  3144. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3145. auto argIt = unrecognizedArguments.begin();
  3146. if (argIt != unrecognizedArguments.end()) {
  3147. status.SetError(
  3148. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  3149. cmSystemTools::SetFatalErrorOccurred();
  3150. return false;
  3151. }
  3152. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3153. cmSystemTools::SetFatalErrorOccurred();
  3154. return true;
  3155. }
  3156. if (!parsedArgs.Output) {
  3157. status.SetError("CONFIGURE OUTPUT option is mandatory.");
  3158. cmSystemTools::SetFatalErrorOccurred();
  3159. return false;
  3160. }
  3161. if (!parsedArgs.Content) {
  3162. status.SetError("CONFIGURE CONTENT option is mandatory.");
  3163. cmSystemTools::SetFatalErrorOccurred();
  3164. return false;
  3165. }
  3166. std::string errorMessage;
  3167. cmNewLineStyle newLineStyle;
  3168. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  3169. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  3170. return false;
  3171. }
  3172. // Check for generator expressions
  3173. std::string outputFile = cmSystemTools::CollapseFullPath(
  3174. *parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  3175. std::string::size_type pos = outputFile.find_first_of("<>");
  3176. if (pos != std::string::npos) {
  3177. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  3178. outputFile[pos],
  3179. "\". This character is not allowed."));
  3180. return false;
  3181. }
  3182. cmMakefile& makeFile = status.GetMakefile();
  3183. if (!makeFile.CanIWriteThisFile(outputFile)) {
  3184. cmSystemTools::Error("Attempt to write file: " + outputFile +
  3185. " into a source directory.");
  3186. return false;
  3187. }
  3188. cmSystemTools::ConvertToUnixSlashes(outputFile);
  3189. // Re-generate if non-temporary outputs are missing.
  3190. // when we finalize the configuration we will remove all
  3191. // output files that now don't exist.
  3192. makeFile.AddCMakeOutputFile(outputFile);
  3193. // Create output directory
  3194. const std::string::size_type slashPos = outputFile.rfind('/');
  3195. if (slashPos != std::string::npos) {
  3196. const std::string path = outputFile.substr(0, slashPos);
  3197. cmSystemTools::MakeDirectory(path);
  3198. }
  3199. std::string newLineCharacters = "\n";
  3200. bool open_with_binary_flag = false;
  3201. if (newLineStyle.IsValid()) {
  3202. newLineCharacters = newLineStyle.GetCharacters();
  3203. open_with_binary_flag = true;
  3204. }
  3205. cmGeneratedFileStream fout;
  3206. fout.Open(outputFile, false, open_with_binary_flag);
  3207. if (!fout) {
  3208. cmSystemTools::Error("Could not open file for write in copy operation " +
  3209. outputFile);
  3210. cmSystemTools::ReportLastSystemError("");
  3211. return false;
  3212. }
  3213. fout.SetCopyIfDifferent(true);
  3214. // copy input to output and expand variables from input at the same time
  3215. std::stringstream sin(*parsedArgs.Content, std::ios::in);
  3216. std::string inLine;
  3217. std::string outLine;
  3218. bool hasNewLine = false;
  3219. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  3220. outLine.clear();
  3221. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  3222. parsedArgs.EscapeQuotes);
  3223. fout << outLine;
  3224. if (hasNewLine || newLineStyle.IsValid()) {
  3225. fout << newLineCharacters;
  3226. }
  3227. }
  3228. // close file before attempting to copy
  3229. fout.close();
  3230. return true;
  3231. }
  3232. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  3233. cmExecutionStatus& status)
  3234. {
  3235. struct Arguments : public ArgumentParser::ParseResult
  3236. {
  3237. std::string Output;
  3238. std::string Format;
  3239. std::string Compression;
  3240. std::string CompressionLevel;
  3241. // "MTIME" should require one value, but it has long been accidentally
  3242. // accepted without one and treated as if an empty value were given.
  3243. // Fixing this would require a policy.
  3244. ArgumentParser::Maybe<std::string> MTime;
  3245. std::string WorkingDirectory;
  3246. bool Verbose = false;
  3247. // "PATHS" requires at least one value, but use a custom check below.
  3248. ArgumentParser::MaybeEmpty<std::vector<std::string>> Paths;
  3249. };
  3250. static auto const parser =
  3251. cmArgumentParser<Arguments>{}
  3252. .Bind("OUTPUT"_s, &Arguments::Output)
  3253. .Bind("FORMAT"_s, &Arguments::Format)
  3254. .Bind("COMPRESSION"_s, &Arguments::Compression)
  3255. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  3256. .Bind("MTIME"_s, &Arguments::MTime)
  3257. .Bind("WORKING_DIRECTORY"_s, &Arguments::WorkingDirectory)
  3258. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3259. .Bind("PATHS"_s, &Arguments::Paths);
  3260. std::vector<std::string> unrecognizedArguments;
  3261. auto parsedArgs =
  3262. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3263. auto argIt = unrecognizedArguments.begin();
  3264. if (argIt != unrecognizedArguments.end()) {
  3265. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3266. cmSystemTools::SetFatalErrorOccurred();
  3267. return false;
  3268. }
  3269. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3270. cmSystemTools::SetFatalErrorOccurred();
  3271. return true;
  3272. }
  3273. const char* knownFormats[] = {
  3274. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  3275. };
  3276. if (!parsedArgs.Format.empty() &&
  3277. !cm::contains(knownFormats, parsedArgs.Format)) {
  3278. status.SetError(
  3279. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  3280. cmSystemTools::SetFatalErrorOccurred();
  3281. return false;
  3282. }
  3283. const char* zipFileFormats[] = { "7zip", "zip" };
  3284. if (!parsedArgs.Compression.empty() &&
  3285. cm::contains(zipFileFormats, parsedArgs.Format)) {
  3286. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  3287. " does not support COMPRESSION arguments"));
  3288. cmSystemTools::SetFatalErrorOccurred();
  3289. return false;
  3290. }
  3291. static std::map<std::string, cmSystemTools::cmTarCompression>
  3292. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  3293. { "BZip2", cmSystemTools::TarCompressBZip2 },
  3294. { "GZip", cmSystemTools::TarCompressGZip },
  3295. { "XZ", cmSystemTools::TarCompressXZ },
  3296. { "Zstd", cmSystemTools::TarCompressZstd } };
  3297. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  3298. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  3299. if (typeIt != compressionTypeMap.end()) {
  3300. compress = typeIt->second;
  3301. } else if (!parsedArgs.Compression.empty()) {
  3302. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  3303. " is not supported"));
  3304. cmSystemTools::SetFatalErrorOccurred();
  3305. return false;
  3306. }
  3307. int compressionLevel = 0;
  3308. int minCompressionLevel = 0;
  3309. int maxCompressionLevel = 9;
  3310. if (compress == cmSystemTools::TarCompressZstd) {
  3311. maxCompressionLevel = 19;
  3312. }
  3313. if (!parsedArgs.CompressionLevel.empty()) {
  3314. if (parsedArgs.CompressionLevel.size() != 1 &&
  3315. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  3316. status.SetError(
  3317. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3318. parsedArgs.Compression, " should be in range ",
  3319. minCompressionLevel, " to ", maxCompressionLevel));
  3320. cmSystemTools::SetFatalErrorOccurred();
  3321. return false;
  3322. }
  3323. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  3324. if (compressionLevel < minCompressionLevel ||
  3325. compressionLevel > maxCompressionLevel) {
  3326. status.SetError(
  3327. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3328. parsedArgs.Compression, " should be in range ",
  3329. minCompressionLevel, " to ", maxCompressionLevel));
  3330. cmSystemTools::SetFatalErrorOccurred();
  3331. return false;
  3332. }
  3333. if (compress == cmSystemTools::TarCompressNone) {
  3334. status.SetError(cmStrCat("compression level is not supported for "
  3335. "compression \"None\"",
  3336. parsedArgs.Compression));
  3337. cmSystemTools::SetFatalErrorOccurred();
  3338. return false;
  3339. }
  3340. }
  3341. if (parsedArgs.Paths.empty()) {
  3342. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  3343. cmSystemTools::SetFatalErrorOccurred();
  3344. return false;
  3345. }
  3346. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths,
  3347. parsedArgs.WorkingDirectory, compress,
  3348. parsedArgs.Verbose, parsedArgs.MTime,
  3349. parsedArgs.Format, compressionLevel)) {
  3350. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  3351. cmSystemTools::SetFatalErrorOccurred();
  3352. return false;
  3353. }
  3354. return true;
  3355. }
  3356. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  3357. cmExecutionStatus& status)
  3358. {
  3359. struct Arguments : public ArgumentParser::ParseResult
  3360. {
  3361. std::string Input;
  3362. bool Verbose = false;
  3363. bool ListOnly = false;
  3364. std::string Destination;
  3365. ArgumentParser::MaybeEmpty<std::vector<std::string>> Patterns;
  3366. bool Touch = false;
  3367. };
  3368. static auto const parser = cmArgumentParser<Arguments>{}
  3369. .Bind("INPUT"_s, &Arguments::Input)
  3370. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3371. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  3372. .Bind("DESTINATION"_s, &Arguments::Destination)
  3373. .Bind("PATTERNS"_s, &Arguments::Patterns)
  3374. .Bind("TOUCH"_s, &Arguments::Touch);
  3375. std::vector<std::string> unrecognizedArguments;
  3376. auto parsedArgs =
  3377. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3378. auto argIt = unrecognizedArguments.begin();
  3379. if (argIt != unrecognizedArguments.end()) {
  3380. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3381. cmSystemTools::SetFatalErrorOccurred();
  3382. return false;
  3383. }
  3384. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3385. cmSystemTools::SetFatalErrorOccurred();
  3386. return true;
  3387. }
  3388. std::string inFile = parsedArgs.Input;
  3389. if (parsedArgs.ListOnly) {
  3390. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3391. parsedArgs.Verbose)) {
  3392. status.SetError(cmStrCat("failed to list: ", inFile));
  3393. cmSystemTools::SetFatalErrorOccurred();
  3394. return false;
  3395. }
  3396. } else {
  3397. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3398. if (!parsedArgs.Destination.empty()) {
  3399. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3400. destDir = parsedArgs.Destination;
  3401. } else {
  3402. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  3403. }
  3404. if (!cmSystemTools::MakeDirectory(destDir)) {
  3405. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3406. cmSystemTools::SetFatalErrorOccurred();
  3407. return false;
  3408. }
  3409. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3410. inFile =
  3411. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  3412. }
  3413. }
  3414. cmWorkingDirectory workdir(destDir);
  3415. if (workdir.Failed()) {
  3416. status.SetError(
  3417. cmStrCat("failed to change working directory to: ", destDir));
  3418. cmSystemTools::SetFatalErrorOccurred();
  3419. return false;
  3420. }
  3421. if (!cmSystemTools::ExtractTar(
  3422. inFile, parsedArgs.Patterns,
  3423. parsedArgs.Touch ? cmSystemTools::cmTarExtractTimestamps::No
  3424. : cmSystemTools::cmTarExtractTimestamps::Yes,
  3425. parsedArgs.Verbose)) {
  3426. status.SetError(cmStrCat("failed to extract: ", inFile));
  3427. cmSystemTools::SetFatalErrorOccurred();
  3428. return false;
  3429. }
  3430. }
  3431. return true;
  3432. }
  3433. bool ValidateAndConvertPermissions(
  3434. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> const&
  3435. permissions,
  3436. mode_t& perms, cmExecutionStatus& status)
  3437. {
  3438. if (!permissions) {
  3439. return true;
  3440. }
  3441. for (const auto& i : *permissions) {
  3442. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3443. status.SetError(i + " is an invalid permission specifier");
  3444. cmSystemTools::SetFatalErrorOccurred();
  3445. return false;
  3446. }
  3447. }
  3448. return true;
  3449. }
  3450. bool SetPermissions(const std::string& filename, const mode_t& perms,
  3451. cmExecutionStatus& status)
  3452. {
  3453. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3454. status.SetError("Failed to set permissions for " + filename);
  3455. cmSystemTools::SetFatalErrorOccurred();
  3456. return false;
  3457. }
  3458. return true;
  3459. }
  3460. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3461. cmExecutionStatus& status)
  3462. {
  3463. mode_t perms = 0;
  3464. mode_t fperms = 0;
  3465. mode_t dperms = 0;
  3466. cmsys::Glob globber;
  3467. globber.SetRecurse(recurse);
  3468. globber.SetRecurseListDirs(recurse);
  3469. struct Arguments : public ArgumentParser::ParseResult
  3470. {
  3471. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3472. Permissions;
  3473. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3474. FilePermissions;
  3475. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3476. DirectoryPermissions;
  3477. };
  3478. static auto const parser =
  3479. cmArgumentParser<Arguments>{}
  3480. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3481. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3482. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3483. std::vector<std::string> pathEntries;
  3484. Arguments parsedArgs =
  3485. parser.Parse(cmMakeRange(args).advance(1), &pathEntries);
  3486. // check validity of arguments
  3487. if (!parsedArgs.Permissions && !parsedArgs.FilePermissions &&
  3488. !parsedArgs.DirectoryPermissions) // no permissions given
  3489. {
  3490. status.SetError("No permissions given");
  3491. cmSystemTools::SetFatalErrorOccurred();
  3492. return false;
  3493. }
  3494. if (parsedArgs.Permissions && parsedArgs.FilePermissions &&
  3495. parsedArgs.DirectoryPermissions) // all keywords are used
  3496. {
  3497. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3498. "DIRECTORY_PERMISSIONS from the invocation");
  3499. cmSystemTools::SetFatalErrorOccurred();
  3500. return false;
  3501. }
  3502. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3503. cmSystemTools::SetFatalErrorOccurred();
  3504. return true;
  3505. }
  3506. // validate permissions
  3507. bool validatePermissions =
  3508. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3509. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3510. status) &&
  3511. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3512. status);
  3513. if (!validatePermissions) {
  3514. return false;
  3515. }
  3516. std::vector<std::string> allPathEntries;
  3517. if (recurse) {
  3518. std::vector<std::string> tempPathEntries;
  3519. for (const auto& i : pathEntries) {
  3520. if (cmSystemTools::FileIsDirectory(i)) {
  3521. globber.FindFiles(i + "/*");
  3522. tempPathEntries = globber.GetFiles();
  3523. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3524. tempPathEntries.end());
  3525. allPathEntries.emplace_back(i);
  3526. } else {
  3527. allPathEntries.emplace_back(i); // We validate path entries below
  3528. }
  3529. }
  3530. } else {
  3531. allPathEntries = std::move(pathEntries);
  3532. }
  3533. // chmod
  3534. for (const auto& i : allPathEntries) {
  3535. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3536. status.SetError(cmStrCat("does not exist:\n ", i));
  3537. cmSystemTools::SetFatalErrorOccurred();
  3538. return false;
  3539. }
  3540. if (cmSystemTools::FileExists(i, true)) {
  3541. bool success = true;
  3542. const mode_t& filePermissions =
  3543. parsedArgs.FilePermissions ? fperms : perms;
  3544. if (filePermissions) {
  3545. success = SetPermissions(i, filePermissions, status);
  3546. }
  3547. if (!success) {
  3548. return false;
  3549. }
  3550. }
  3551. else if (cmSystemTools::FileIsDirectory(i)) {
  3552. bool success = true;
  3553. const mode_t& directoryPermissions =
  3554. parsedArgs.DirectoryPermissions ? dperms : perms;
  3555. if (directoryPermissions) {
  3556. success = SetPermissions(i, directoryPermissions, status);
  3557. }
  3558. if (!success) {
  3559. return false;
  3560. }
  3561. }
  3562. }
  3563. return true;
  3564. }
  3565. bool HandleChmodCommand(std::vector<std::string> const& args,
  3566. cmExecutionStatus& status)
  3567. {
  3568. return HandleChmodCommandImpl(args, false, status);
  3569. }
  3570. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3571. cmExecutionStatus& status)
  3572. {
  3573. return HandleChmodCommandImpl(args, true, status);
  3574. }
  3575. } // namespace
  3576. bool cmFileCommand(std::vector<std::string> const& args,
  3577. cmExecutionStatus& status)
  3578. {
  3579. if (args.empty()) {
  3580. status.SetError(
  3581. "given no arguments, but it requires at least a sub-command.");
  3582. return false;
  3583. }
  3584. static cmSubcommandTable const subcommand{
  3585. { "WRITE"_s, HandleWriteCommand },
  3586. { "APPEND"_s, HandleAppendCommand },
  3587. { "DOWNLOAD"_s, HandleDownloadCommand },
  3588. { "UPLOAD"_s, HandleUploadCommand },
  3589. { "READ"_s, HandleReadCommand },
  3590. { "MD5"_s, HandleHashCommand },
  3591. { "SHA1"_s, HandleHashCommand },
  3592. { "SHA224"_s, HandleHashCommand },
  3593. { "SHA256"_s, HandleHashCommand },
  3594. { "SHA384"_s, HandleHashCommand },
  3595. { "SHA512"_s, HandleHashCommand },
  3596. { "SHA3_224"_s, HandleHashCommand },
  3597. { "SHA3_256"_s, HandleHashCommand },
  3598. { "SHA3_384"_s, HandleHashCommand },
  3599. { "SHA3_512"_s, HandleHashCommand },
  3600. { "STRINGS"_s, HandleStringsCommand },
  3601. { "GLOB"_s, HandleGlobCommand },
  3602. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3603. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3604. { "RENAME"_s, HandleRename },
  3605. { "COPY_FILE"_s, HandleCopyFile },
  3606. { "REMOVE"_s, HandleRemove },
  3607. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3608. { "COPY"_s, HandleCopyCommand },
  3609. { "INSTALL"_s, HandleInstallCommand },
  3610. { "DIFFERENT"_s, HandleDifferentCommand },
  3611. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3612. { "CHRPATH"_s, HandleRPathChangeCommand },
  3613. { "RPATH_SET"_s, HandleRPathSetCommand },
  3614. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3615. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3616. { "READ_ELF"_s, HandleReadElfCommand },
  3617. { "READ_MACHO"_s, HandleReadMachoCommand },
  3618. { "REAL_PATH"_s, HandleRealPathCommand },
  3619. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3620. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3621. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3622. { "TOUCH"_s, HandleTouchCommand },
  3623. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3624. { "TIMESTAMP"_s, HandleTimestampCommand },
  3625. { "GENERATE"_s, HandleGenerateCommand },
  3626. { "LOCK"_s, HandleLockCommand },
  3627. { "SIZE"_s, HandleSizeCommand },
  3628. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3629. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3630. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3631. { "CONFIGURE"_s, HandleConfigureCommand },
  3632. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3633. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3634. { "CHMOD"_s, HandleChmodCommand },
  3635. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3636. };
  3637. return subcommand(args[0], args, status);
  3638. }