cmFileCommand.cxx 128 KB

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