cmFileCommand.cxx 119 KB

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