cmFileCommand.cxx 128 KB

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