cmFileCommand.cxx 127 KB

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