cmFileCommand.cxx 127 KB

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