cmFileCommand.cxx 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846
  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 non-toolchain portion of runtime path of \"", file,
  935. "\" to \"", *newRPath, '"');
  936. status.GetMakefile().DisplayStatus(message, -1);
  937. }
  938. ft.Store(file);
  939. }
  940. return success;
  941. }
  942. bool HandleRPathSetCommand(std::vector<std::string> const& args,
  943. cmExecutionStatus& status)
  944. {
  945. // Evaluate arguments.
  946. std::string file;
  947. cm::optional<std::string> newRPath;
  948. cmArgumentParser<void> parser;
  949. std::vector<std::string> unknownArgs;
  950. parser.Bind("FILE"_s, file).Bind("NEW_RPATH"_s, newRPath);
  951. ArgumentParser::ParseResult parseResult =
  952. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  953. if (!unknownArgs.empty()) {
  954. status.SetError(cmStrCat("RPATH_SET given unrecognized argument \"",
  955. unknownArgs.front(), "\"."));
  956. return false;
  957. }
  958. if (parseResult.MaybeReportError(status.GetMakefile())) {
  959. return true;
  960. }
  961. if (file.empty()) {
  962. status.SetError("RPATH_SET not given FILE option.");
  963. return false;
  964. }
  965. if (!newRPath) {
  966. status.SetError("RPATH_SET not given NEW_RPATH option.");
  967. return false;
  968. }
  969. if (!cmSystemTools::FileExists(file, true)) {
  970. status.SetError(
  971. cmStrCat("RPATH_SET given FILE \"", file, "\" that does not exist."));
  972. return false;
  973. }
  974. bool success = true;
  975. cmFileTimes const ft(file);
  976. std::string emsg;
  977. bool changed;
  978. if (!cmSystemTools::SetRPath(file, *newRPath, &emsg, &changed)) {
  979. status.SetError(cmStrCat("RPATH_SET could not write new RPATH:\n ",
  980. *newRPath, "\nto the file:\n ", file, "\n",
  981. emsg));
  982. success = false;
  983. }
  984. if (success) {
  985. if (changed) {
  986. std::string message =
  987. cmStrCat("Set non-toolchain portion of runtime path of \"", file,
  988. "\" to \"", *newRPath, '"');
  989. status.GetMakefile().DisplayStatus(message, -1);
  990. }
  991. ft.Store(file);
  992. }
  993. return success;
  994. }
  995. bool HandleRPathRemoveCommand(std::vector<std::string> const& args,
  996. cmExecutionStatus& status)
  997. {
  998. // Evaluate arguments.
  999. std::string file;
  1000. cmArgumentParser<void> parser;
  1001. std::vector<std::string> unknownArgs;
  1002. parser.Bind("FILE"_s, file);
  1003. ArgumentParser::ParseResult parseResult =
  1004. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  1005. if (!unknownArgs.empty()) {
  1006. status.SetError(
  1007. cmStrCat("RPATH_REMOVE given unknown argument ", unknownArgs.front()));
  1008. return false;
  1009. }
  1010. if (parseResult.MaybeReportError(status.GetMakefile())) {
  1011. return true;
  1012. }
  1013. if (file.empty()) {
  1014. status.SetError("RPATH_REMOVE not given FILE option.");
  1015. return false;
  1016. }
  1017. if (!cmSystemTools::FileExists(file, true)) {
  1018. status.SetError(
  1019. cmStrCat("RPATH_REMOVE given FILE \"", file, "\" that does not exist."));
  1020. return false;
  1021. }
  1022. bool success = true;
  1023. cmFileTimes const ft(file);
  1024. std::string emsg;
  1025. bool removed;
  1026. if (!cmSystemTools::RemoveRPath(file, &emsg, &removed)) {
  1027. status.SetError(
  1028. cmStrCat("RPATH_REMOVE could not remove RPATH from file: \n ", file,
  1029. "\n", emsg));
  1030. success = false;
  1031. }
  1032. if (success) {
  1033. if (removed) {
  1034. std::string message =
  1035. cmStrCat("Removed runtime path from \"", file, '"');
  1036. status.GetMakefile().DisplayStatus(message, -1);
  1037. }
  1038. ft.Store(file);
  1039. }
  1040. return success;
  1041. }
  1042. bool HandleRPathCheckCommand(std::vector<std::string> const& args,
  1043. cmExecutionStatus& status)
  1044. {
  1045. // Evaluate arguments.
  1046. std::string file;
  1047. cm::optional<std::string> rpath;
  1048. cmArgumentParser<void> parser;
  1049. std::vector<std::string> unknownArgs;
  1050. parser.Bind("FILE"_s, file).Bind("RPATH"_s, rpath);
  1051. ArgumentParser::ParseResult parseResult =
  1052. parser.Parse(cmMakeRange(args).advance(1), &unknownArgs);
  1053. if (!unknownArgs.empty()) {
  1054. status.SetError(
  1055. cmStrCat("RPATH_CHECK given unknown argument ", unknownArgs.front()));
  1056. return false;
  1057. }
  1058. if (parseResult.MaybeReportError(status.GetMakefile())) {
  1059. return true;
  1060. }
  1061. if (file.empty()) {
  1062. status.SetError("RPATH_CHECK not given FILE option.");
  1063. return false;
  1064. }
  1065. if (!rpath) {
  1066. status.SetError("RPATH_CHECK not given RPATH option.");
  1067. return false;
  1068. }
  1069. // If the file exists but does not have the desired RPath then
  1070. // delete it. This is used during installation to re-install a file
  1071. // if its RPath will change.
  1072. if (cmSystemTools::FileExists(file, true) &&
  1073. !cmSystemTools::CheckRPath(file, *rpath)) {
  1074. cmSystemTools::RemoveFile(file);
  1075. }
  1076. return true;
  1077. }
  1078. bool HandleReadElfCommand(std::vector<std::string> const& args,
  1079. cmExecutionStatus& status)
  1080. {
  1081. if (args.size() < 4) {
  1082. status.SetError("READ_ELF must be called with at least three additional "
  1083. "arguments.");
  1084. return false;
  1085. }
  1086. std::string const& fileNameArg = args[1];
  1087. struct Arguments
  1088. {
  1089. std::string RPath;
  1090. std::string RunPath;
  1091. std::string Error;
  1092. };
  1093. static auto const parser = cmArgumentParser<Arguments>{}
  1094. .Bind("RPATH"_s, &Arguments::RPath)
  1095. .Bind("RUNPATH"_s, &Arguments::RunPath)
  1096. .Bind("CAPTURE_ERROR"_s, &Arguments::Error);
  1097. Arguments const arguments = parser.Parse(cmMakeRange(args).advance(2),
  1098. /*unparsedArguments=*/nullptr);
  1099. if (!cmSystemTools::FileExists(fileNameArg, true)) {
  1100. status.SetError(cmStrCat("READ_ELF given FILE \"", fileNameArg,
  1101. "\" that does not exist."));
  1102. return false;
  1103. }
  1104. cmELF elf(fileNameArg.c_str());
  1105. if (!elf) {
  1106. if (arguments.Error.empty()) {
  1107. status.SetError(cmStrCat("READ_ELF given FILE:\n ", fileNameArg,
  1108. "\nthat is not a valid ELF file."));
  1109. return false;
  1110. }
  1111. status.GetMakefile().AddDefinition(arguments.Error,
  1112. "not a valid ELF file");
  1113. return true;
  1114. }
  1115. if (!arguments.RPath.empty()) {
  1116. if (cmELF::StringEntry const* se_rpath = elf.GetRPath()) {
  1117. std::string rpath(se_rpath->Value);
  1118. std::replace(rpath.begin(), rpath.end(), ':', ';');
  1119. status.GetMakefile().AddDefinition(arguments.RPath, rpath);
  1120. }
  1121. }
  1122. if (!arguments.RunPath.empty()) {
  1123. if (cmELF::StringEntry const* se_runpath = elf.GetRunPath()) {
  1124. std::string runpath(se_runpath->Value);
  1125. std::replace(runpath.begin(), runpath.end(), ':', ';');
  1126. status.GetMakefile().AddDefinition(arguments.RunPath, runpath);
  1127. }
  1128. }
  1129. return true;
  1130. }
  1131. bool HandleInstallCommand(std::vector<std::string> const& args,
  1132. cmExecutionStatus& status)
  1133. {
  1134. cmFileInstaller installer(status);
  1135. return installer.Run(args);
  1136. }
  1137. bool HandleRealPathCommand(std::vector<std::string> const& args,
  1138. cmExecutionStatus& status)
  1139. {
  1140. if (args.size() < 3) {
  1141. status.SetError("REAL_PATH requires a path and an output variable");
  1142. return false;
  1143. }
  1144. struct Arguments : public ArgumentParser::ParseResult
  1145. {
  1146. cm::optional<std::string> BaseDirectory;
  1147. bool ExpandTilde = false;
  1148. };
  1149. static auto const parser =
  1150. cmArgumentParser<Arguments>{}
  1151. .Bind("BASE_DIRECTORY"_s, &Arguments::BaseDirectory)
  1152. .Bind("EXPAND_TILDE"_s, &Arguments::ExpandTilde);
  1153. std::vector<std::string> unparsedArguments;
  1154. auto arguments =
  1155. parser.Parse(cmMakeRange(args).advance(3), &unparsedArguments);
  1156. if (!unparsedArguments.empty()) {
  1157. status.SetError("REAL_PATH called with unexpected arguments");
  1158. return false;
  1159. }
  1160. if (arguments.MaybeReportError(status.GetMakefile())) {
  1161. return true;
  1162. }
  1163. if (!arguments.BaseDirectory) {
  1164. arguments.BaseDirectory = status.GetMakefile().GetCurrentSourceDirectory();
  1165. }
  1166. auto input = args[1];
  1167. if (arguments.ExpandTilde && !input.empty()) {
  1168. if (input[0] == '~' && (input.length() == 1 || input[1] == '/')) {
  1169. std::string home;
  1170. if (
  1171. #if defined(_WIN32) && !defined(__CYGWIN__)
  1172. cmSystemTools::GetEnv("USERPROFILE", home) ||
  1173. #endif
  1174. cmSystemTools::GetEnv("HOME", home)) {
  1175. input.replace(0, 1, home);
  1176. }
  1177. }
  1178. }
  1179. bool warnAbout152 = false;
  1180. bool use152New = true;
  1181. cmPolicies::PolicyStatus policyStatus =
  1182. status.GetMakefile().GetPolicyStatus(cmPolicies::CMP0152);
  1183. switch (policyStatus) {
  1184. case cmPolicies::REQUIRED_IF_USED:
  1185. case cmPolicies::REQUIRED_ALWAYS:
  1186. case cmPolicies::NEW:
  1187. break;
  1188. case cmPolicies::WARN:
  1189. use152New = false;
  1190. warnAbout152 = true;
  1191. break;
  1192. case cmPolicies::OLD:
  1193. use152New = false;
  1194. warnAbout152 = false;
  1195. break;
  1196. }
  1197. auto computeNewPath = [=](std::string const& in, std::string& result) {
  1198. auto path = cmCMakePath{ in };
  1199. if (path.IsRelative()) {
  1200. auto basePath = cmCMakePath{ *arguments.BaseDirectory };
  1201. path = basePath.Append(path);
  1202. }
  1203. result = cmSystemTools::GetActualCaseForPath(
  1204. cmSystemTools::GetRealPath(path.String()));
  1205. };
  1206. std::string realPath;
  1207. if (use152New) {
  1208. computeNewPath(input, realPath);
  1209. } else {
  1210. std::string oldPolicyPath =
  1211. cmSystemTools::CollapseFullPath(input, *arguments.BaseDirectory);
  1212. oldPolicyPath = cmSystemTools::GetRealPath(oldPolicyPath);
  1213. if (warnAbout152) {
  1214. computeNewPath(input, realPath);
  1215. if (oldPolicyPath != realPath) {
  1216. status.GetMakefile().IssueMessage(
  1217. MessageType::AUTHOR_WARNING,
  1218. cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0152),
  1219. "\n"
  1220. "From input path:\n ",
  1221. input, "\nthe policy OLD behavior produces path:\n ",
  1222. oldPolicyPath,
  1223. "\nbut the policy NEW behavior produces path:\n ",
  1224. realPath,
  1225. "\nSince the policy is not set, CMake is using the OLD "
  1226. "behavior for compatibility."));
  1227. }
  1228. }
  1229. realPath = oldPolicyPath;
  1230. }
  1231. status.GetMakefile().AddDefinition(args[2], realPath);
  1232. return true;
  1233. }
  1234. bool HandleRelativePathCommand(std::vector<std::string> const& args,
  1235. cmExecutionStatus& status)
  1236. {
  1237. if (args.size() != 4) {
  1238. status.SetError("RELATIVE_PATH called with incorrect number of arguments");
  1239. return false;
  1240. }
  1241. const std::string& outVar = args[1];
  1242. const std::string& directoryName = args[2];
  1243. const std::string& fileName = args[3];
  1244. if (!cmSystemTools::FileIsFullPath(directoryName)) {
  1245. std::string errstring =
  1246. "RELATIVE_PATH must be passed a full path to the directory: " +
  1247. directoryName;
  1248. status.SetError(errstring);
  1249. return false;
  1250. }
  1251. if (!cmSystemTools::FileIsFullPath(fileName)) {
  1252. std::string errstring =
  1253. "RELATIVE_PATH must be passed a full path to the file: " + fileName;
  1254. status.SetError(errstring);
  1255. return false;
  1256. }
  1257. std::string res = cmSystemTools::RelativePath(directoryName, fileName);
  1258. status.GetMakefile().AddDefinition(outVar, res);
  1259. return true;
  1260. }
  1261. bool HandleRename(std::vector<std::string> const& args,
  1262. cmExecutionStatus& status)
  1263. {
  1264. if (args.size() < 3) {
  1265. status.SetError("RENAME must be called with at least two additional "
  1266. "arguments");
  1267. return false;
  1268. }
  1269. // Compute full path for old and new names.
  1270. std::string oldname = args[1];
  1271. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1272. oldname =
  1273. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1274. }
  1275. std::string newname = args[2];
  1276. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1277. newname =
  1278. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1279. }
  1280. struct Arguments
  1281. {
  1282. bool NoReplace = false;
  1283. std::string Result;
  1284. };
  1285. static auto const parser = cmArgumentParser<Arguments>{}
  1286. .Bind("NO_REPLACE"_s, &Arguments::NoReplace)
  1287. .Bind("RESULT"_s, &Arguments::Result);
  1288. std::vector<std::string> unconsumedArgs;
  1289. Arguments const arguments =
  1290. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1291. if (!unconsumedArgs.empty()) {
  1292. status.SetError("RENAME unknown argument:\n " + unconsumedArgs.front());
  1293. return false;
  1294. }
  1295. std::string err;
  1296. switch (cmSystemTools::RenameFile(oldname, newname,
  1297. arguments.NoReplace
  1298. ? cmSystemTools::Replace::No
  1299. : cmSystemTools::Replace::Yes,
  1300. &err)) {
  1301. case cmSystemTools::RenameResult::Success:
  1302. if (!arguments.Result.empty()) {
  1303. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1304. }
  1305. return true;
  1306. case cmSystemTools::RenameResult::NoReplace:
  1307. if (!arguments.Result.empty()) {
  1308. err = "NO_REPLACE";
  1309. } else {
  1310. err = "path not replaced";
  1311. }
  1312. CM_FALLTHROUGH;
  1313. case cmSystemTools::RenameResult::Failure:
  1314. if (!arguments.Result.empty()) {
  1315. status.GetMakefile().AddDefinition(arguments.Result, err);
  1316. return true;
  1317. }
  1318. break;
  1319. }
  1320. status.SetError(cmStrCat("RENAME failed to rename\n ", oldname, "\nto\n ",
  1321. newname, "\nbecause: ", err, "\n"));
  1322. return false;
  1323. }
  1324. bool HandleCopyFile(std::vector<std::string> const& args,
  1325. cmExecutionStatus& status)
  1326. {
  1327. if (args.size() < 3) {
  1328. status.SetError("COPY_FILE must be called with at least two additional "
  1329. "arguments");
  1330. return false;
  1331. }
  1332. // Compute full path for old and new names.
  1333. std::string oldname = args[1];
  1334. if (!cmsys::SystemTools::FileIsFullPath(oldname)) {
  1335. oldname =
  1336. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[1]);
  1337. }
  1338. std::string newname = args[2];
  1339. if (!cmsys::SystemTools::FileIsFullPath(newname)) {
  1340. newname =
  1341. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', args[2]);
  1342. }
  1343. struct Arguments
  1344. {
  1345. bool InputMayBeRecent = false;
  1346. bool OnlyIfDifferent = false;
  1347. std::string Result;
  1348. };
  1349. static auto const parser =
  1350. cmArgumentParser<Arguments>{}
  1351. .Bind("INPUT_MAY_BE_RECENT"_s, &Arguments::InputMayBeRecent)
  1352. .Bind("ONLY_IF_DIFFERENT"_s, &Arguments::OnlyIfDifferent)
  1353. .Bind("RESULT"_s, &Arguments::Result);
  1354. std::vector<std::string> unconsumedArgs;
  1355. Arguments const arguments =
  1356. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  1357. if (!unconsumedArgs.empty()) {
  1358. status.SetError("COPY_FILE unknown argument:\n " +
  1359. unconsumedArgs.front());
  1360. return false;
  1361. }
  1362. bool result = true;
  1363. if (cmsys::SystemTools::FileIsDirectory(oldname)) {
  1364. if (!arguments.Result.empty()) {
  1365. status.GetMakefile().AddDefinition(arguments.Result,
  1366. "cannot copy a directory");
  1367. } else {
  1368. status.SetError(
  1369. cmStrCat("COPY_FILE cannot copy a directory\n ", oldname));
  1370. result = false;
  1371. }
  1372. return result;
  1373. }
  1374. if (cmsys::SystemTools::FileIsDirectory(newname)) {
  1375. if (!arguments.Result.empty()) {
  1376. status.GetMakefile().AddDefinition(arguments.Result,
  1377. "cannot copy to a directory");
  1378. } else {
  1379. status.SetError(
  1380. cmStrCat("COPY_FILE cannot copy to a directory\n ", newname));
  1381. result = false;
  1382. }
  1383. return result;
  1384. }
  1385. cmSystemTools::CopyWhen when;
  1386. if (arguments.OnlyIfDifferent) {
  1387. when = cmSystemTools::CopyWhen::OnlyIfDifferent;
  1388. } else {
  1389. when = cmSystemTools::CopyWhen::Always;
  1390. }
  1391. cmSystemTools::CopyInputRecent const inputRecent = arguments.InputMayBeRecent
  1392. ? cmSystemTools::CopyInputRecent::Yes
  1393. : cmSystemTools::CopyInputRecent::No;
  1394. std::string err;
  1395. if (cmSystemTools::CopySingleFile(oldname, newname, when, inputRecent,
  1396. &err) ==
  1397. cmSystemTools::CopyResult::Success) {
  1398. if (!arguments.Result.empty()) {
  1399. status.GetMakefile().AddDefinition(arguments.Result, "0");
  1400. }
  1401. } else {
  1402. if (!arguments.Result.empty()) {
  1403. status.GetMakefile().AddDefinition(arguments.Result, err);
  1404. } else {
  1405. status.SetError(cmStrCat("COPY_FILE failed to copy\n ", oldname,
  1406. "\nto\n ", newname, "\nbecause: ", err, "\n"));
  1407. result = false;
  1408. }
  1409. }
  1410. return result;
  1411. }
  1412. bool HandleRemoveImpl(std::vector<std::string> const& args, bool recurse,
  1413. cmExecutionStatus& status)
  1414. {
  1415. for (std::string const& arg :
  1416. cmMakeRange(args).advance(1)) // Get rid of subcommand
  1417. {
  1418. std::string fileName = arg;
  1419. if (fileName.empty()) {
  1420. std::string const r = recurse ? "REMOVE_RECURSE" : "REMOVE";
  1421. status.GetMakefile().IssueMessage(
  1422. MessageType::AUTHOR_WARNING, "Ignoring empty file name in " + r + ".");
  1423. continue;
  1424. }
  1425. if (!cmsys::SystemTools::FileIsFullPath(fileName)) {
  1426. fileName =
  1427. cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/', arg);
  1428. }
  1429. if (cmSystemTools::FileIsDirectory(fileName) &&
  1430. !cmSystemTools::FileIsSymlink(fileName) && recurse) {
  1431. cmSystemTools::RepeatedRemoveDirectory(fileName);
  1432. } else {
  1433. cmSystemTools::RemoveFile(fileName);
  1434. }
  1435. }
  1436. return true;
  1437. }
  1438. bool HandleRemove(std::vector<std::string> const& args,
  1439. cmExecutionStatus& status)
  1440. {
  1441. return HandleRemoveImpl(args, false, status);
  1442. }
  1443. bool HandleRemoveRecurse(std::vector<std::string> const& args,
  1444. cmExecutionStatus& status)
  1445. {
  1446. return HandleRemoveImpl(args, true, status);
  1447. }
  1448. std::string ToNativePath(const std::string& path)
  1449. {
  1450. const auto& outPath = cmSystemTools::ConvertToOutputPath(path);
  1451. if (outPath.size() > 1 && outPath.front() == '\"' &&
  1452. outPath.back() == '\"') {
  1453. return outPath.substr(1, outPath.size() - 2);
  1454. }
  1455. return outPath;
  1456. }
  1457. std::string ToCMakePath(const std::string& path)
  1458. {
  1459. auto temp = path;
  1460. cmSystemTools::ConvertToUnixSlashes(temp);
  1461. return temp;
  1462. }
  1463. bool HandlePathCommand(std::vector<std::string> const& args,
  1464. std::string (*convert)(std::string const&),
  1465. cmExecutionStatus& status)
  1466. {
  1467. if (args.size() != 3) {
  1468. status.SetError("FILE([TO_CMAKE_PATH|TO_NATIVE_PATH] path result) must be "
  1469. "called with exactly three arguments.");
  1470. return false;
  1471. }
  1472. #if defined(_WIN32) && !defined(__CYGWIN__)
  1473. char pathSep = ';';
  1474. #else
  1475. char pathSep = ':';
  1476. #endif
  1477. std::vector<std::string> path = cmSystemTools::SplitString(args[1], pathSep);
  1478. std::string value = cmList::to_string(cmMakeRange(path).transform(convert));
  1479. status.GetMakefile().AddDefinition(args[2], value);
  1480. return true;
  1481. }
  1482. bool HandleCMakePathCommand(std::vector<std::string> const& args,
  1483. cmExecutionStatus& status)
  1484. {
  1485. return HandlePathCommand(args, ToCMakePath, status);
  1486. }
  1487. bool HandleNativePathCommand(std::vector<std::string> const& args,
  1488. cmExecutionStatus& status)
  1489. {
  1490. return HandlePathCommand(args, ToNativePath, status);
  1491. }
  1492. #if !defined(CMAKE_BOOTSTRAP)
  1493. // Stuff for curl download/upload
  1494. using cmFileCommandVectorOfChar = std::vector<char>;
  1495. size_t cmWriteToFileCallback(void* ptr, size_t size, size_t nmemb, void* data)
  1496. {
  1497. int realsize = static_cast<int>(size * nmemb);
  1498. cmsys::ofstream* fout = static_cast<cmsys::ofstream*>(data);
  1499. if (fout) {
  1500. const char* chPtr = static_cast<char*>(ptr);
  1501. fout->write(chPtr, realsize);
  1502. }
  1503. return realsize;
  1504. }
  1505. size_t cmWriteToMemoryCallback(void* ptr, size_t size, size_t nmemb,
  1506. void* data)
  1507. {
  1508. int realsize = static_cast<int>(size * nmemb);
  1509. const char* chPtr = static_cast<char*>(ptr);
  1510. cm::append(*static_cast<cmFileCommandVectorOfChar*>(data), chPtr,
  1511. chPtr + realsize);
  1512. return realsize;
  1513. }
  1514. int cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
  1515. size_t size, void* data)
  1516. {
  1517. cmFileCommandVectorOfChar& vec =
  1518. *static_cast<cmFileCommandVectorOfChar*>(data);
  1519. switch (type) {
  1520. case CURLINFO_TEXT:
  1521. case CURLINFO_HEADER_IN:
  1522. case CURLINFO_HEADER_OUT:
  1523. cm::append(vec, chPtr, chPtr + size);
  1524. break;
  1525. case CURLINFO_DATA_IN:
  1526. case CURLINFO_DATA_OUT:
  1527. case CURLINFO_SSL_DATA_IN:
  1528. case CURLINFO_SSL_DATA_OUT: {
  1529. char buf[128];
  1530. int n =
  1531. snprintf(buf, sizeof(buf), "[%" KWIML_INT_PRIu64 " bytes data]\n",
  1532. static_cast<KWIML_INT_uint64_t>(size));
  1533. if (n > 0) {
  1534. cm::append(vec, buf, buf + n);
  1535. }
  1536. } break;
  1537. default:
  1538. break;
  1539. }
  1540. return 0;
  1541. }
  1542. # if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM >= 0x072000
  1543. const CURLoption CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_XFERINFOFUNCTION;
  1544. using cm_curl_off_t = curl_off_t;
  1545. # else
  1546. const CURLoption CM_CURLOPT_XFERINFOFUNCTION = CURLOPT_PROGRESSFUNCTION;
  1547. using cm_curl_off_t = double;
  1548. # endif
  1549. class cURLProgressHelper
  1550. {
  1551. public:
  1552. cURLProgressHelper(cmMakefile* mf, const char* text)
  1553. : Makefile(mf)
  1554. , Text(text)
  1555. {
  1556. }
  1557. bool UpdatePercentage(cm_curl_off_t value, cm_curl_off_t total,
  1558. std::string& status)
  1559. {
  1560. long OldPercentage = this->CurrentPercentage;
  1561. if (total > 0) {
  1562. this->CurrentPercentage = std::lround(
  1563. static_cast<double>(value) / static_cast<double>(total) * 100.0);
  1564. if (this->CurrentPercentage > 100) {
  1565. // Avoid extra progress reports for unexpected data beyond total.
  1566. this->CurrentPercentage = 100;
  1567. }
  1568. }
  1569. bool updated = (OldPercentage != this->CurrentPercentage);
  1570. if (updated) {
  1571. status =
  1572. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1573. }
  1574. return updated;
  1575. }
  1576. cmMakefile* GetMakefile() { return this->Makefile; }
  1577. private:
  1578. long CurrentPercentage = -1;
  1579. cmMakefile* Makefile;
  1580. std::string Text;
  1581. };
  1582. int cmFileDownloadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1583. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1584. cm_curl_off_t ulnow)
  1585. {
  1586. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1587. static_cast<void>(ultotal);
  1588. static_cast<void>(ulnow);
  1589. std::string status;
  1590. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1591. cmMakefile* mf = helper->GetMakefile();
  1592. mf->DisplayStatus(status, -1);
  1593. }
  1594. return 0;
  1595. }
  1596. int cmFileUploadProgressCallback(void* clientp, cm_curl_off_t dltotal,
  1597. cm_curl_off_t dlnow, cm_curl_off_t ultotal,
  1598. cm_curl_off_t ulnow)
  1599. {
  1600. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1601. static_cast<void>(dltotal);
  1602. static_cast<void>(dlnow);
  1603. std::string status;
  1604. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1605. cmMakefile* mf = helper->GetMakefile();
  1606. mf->DisplayStatus(status, -1);
  1607. }
  1608. return 0;
  1609. }
  1610. class cURLEasyGuard
  1611. {
  1612. public:
  1613. cURLEasyGuard(CURL* easy)
  1614. : Easy(easy)
  1615. {
  1616. }
  1617. ~cURLEasyGuard()
  1618. {
  1619. if (this->Easy) {
  1620. ::curl_easy_cleanup(this->Easy);
  1621. }
  1622. }
  1623. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1624. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1625. void release() { this->Easy = nullptr; }
  1626. private:
  1627. ::CURL* Easy;
  1628. };
  1629. #endif
  1630. #define check_curl_result(result, errstr) \
  1631. do { \
  1632. if (result != CURLE_OK) { \
  1633. std::string e(errstr); \
  1634. e += ::curl_easy_strerror(result); \
  1635. status.SetError(e); \
  1636. return false; \
  1637. } \
  1638. } while (false)
  1639. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1640. cmExecutionStatus& status)
  1641. {
  1642. #if !defined(CMAKE_BOOTSTRAP)
  1643. auto i = args.begin();
  1644. if (args.size() < 2) {
  1645. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1646. return false;
  1647. }
  1648. ++i; // Get rid of subcommand
  1649. std::string url = *i;
  1650. ++i;
  1651. std::string file;
  1652. long timeout = 0;
  1653. long inactivity_timeout = 0;
  1654. std::string logVar;
  1655. std::string statusVar;
  1656. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1657. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1658. std::string netrc_level =
  1659. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1660. std::string netrc_file =
  1661. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1662. std::string expectedHash;
  1663. std::string hashMatchMSG;
  1664. std::unique_ptr<cmCryptoHash> hash;
  1665. bool showProgress = false;
  1666. std::string userpwd;
  1667. std::vector<std::string> curl_headers;
  1668. std::vector<std::pair<std::string, cm::optional<std::string>>> curl_ranges;
  1669. while (i != args.end()) {
  1670. if (*i == "TIMEOUT") {
  1671. ++i;
  1672. if (i != args.end()) {
  1673. timeout = atol(i->c_str());
  1674. } else {
  1675. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1676. return false;
  1677. }
  1678. } else if (*i == "INACTIVITY_TIMEOUT") {
  1679. ++i;
  1680. if (i != args.end()) {
  1681. inactivity_timeout = atol(i->c_str());
  1682. } else {
  1683. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1684. return false;
  1685. }
  1686. } else if (*i == "LOG") {
  1687. ++i;
  1688. if (i == args.end()) {
  1689. status.SetError("DOWNLOAD missing VAR for LOG.");
  1690. return false;
  1691. }
  1692. logVar = *i;
  1693. } else if (*i == "STATUS") {
  1694. ++i;
  1695. if (i == args.end()) {
  1696. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1697. return false;
  1698. }
  1699. statusVar = *i;
  1700. } else if (*i == "TLS_VERIFY") {
  1701. ++i;
  1702. if (i != args.end()) {
  1703. tls_verify = cmIsOn(*i);
  1704. } else {
  1705. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1706. return false;
  1707. }
  1708. } else if (*i == "TLS_CAINFO") {
  1709. ++i;
  1710. if (i != args.end()) {
  1711. cainfo = cmValue(*i);
  1712. } else {
  1713. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1714. return false;
  1715. }
  1716. } else if (*i == "NETRC_FILE") {
  1717. ++i;
  1718. if (i != args.end()) {
  1719. netrc_file = *i;
  1720. } else {
  1721. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1722. return false;
  1723. }
  1724. } else if (*i == "NETRC") {
  1725. ++i;
  1726. if (i != args.end()) {
  1727. netrc_level = *i;
  1728. } else {
  1729. status.SetError("DOWNLOAD missing level value for NETRC.");
  1730. return false;
  1731. }
  1732. } else if (*i == "EXPECTED_MD5") {
  1733. ++i;
  1734. if (i == args.end()) {
  1735. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1736. return false;
  1737. }
  1738. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1739. hashMatchMSG = "MD5 sum";
  1740. expectedHash = cmSystemTools::LowerCase(*i);
  1741. } else if (*i == "SHOW_PROGRESS") {
  1742. showProgress = true;
  1743. } else if (*i == "EXPECTED_HASH") {
  1744. ++i;
  1745. if (i == args.end()) {
  1746. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1747. return false;
  1748. }
  1749. std::string::size_type pos = i->find("=");
  1750. if (pos == std::string::npos) {
  1751. std::string err =
  1752. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1753. status.SetError(err);
  1754. return false;
  1755. }
  1756. std::string algo = i->substr(0, pos);
  1757. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1758. hash = cmCryptoHash::New(algo);
  1759. if (!hash) {
  1760. std::string err =
  1761. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1762. status.SetError(err);
  1763. return false;
  1764. }
  1765. hashMatchMSG = algo + " hash";
  1766. } else if (*i == "USERPWD") {
  1767. ++i;
  1768. if (i == args.end()) {
  1769. status.SetError("DOWNLOAD missing string for USERPWD.");
  1770. return false;
  1771. }
  1772. userpwd = *i;
  1773. } else if (*i == "HTTPHEADER") {
  1774. ++i;
  1775. if (i == args.end()) {
  1776. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1777. return false;
  1778. }
  1779. curl_headers.push_back(*i);
  1780. } else if (*i == "RANGE_START") {
  1781. ++i;
  1782. if (i == args.end()) {
  1783. status.SetError("DOWNLOAD missing value for RANGE_START.");
  1784. return false;
  1785. }
  1786. curl_ranges.emplace_back(*i, cm::nullopt);
  1787. } else if (*i == "RANGE_END") {
  1788. ++i;
  1789. if (curl_ranges.empty()) {
  1790. curl_ranges.emplace_back("0", *i);
  1791. } else {
  1792. auto& last_range = curl_ranges.back();
  1793. if (!last_range.second.has_value()) {
  1794. last_range.second = *i;
  1795. } else {
  1796. status.SetError("Multiple RANGE_END values is provided without "
  1797. "the corresponding RANGE_START.");
  1798. return false;
  1799. }
  1800. }
  1801. } else if (file.empty()) {
  1802. file = *i;
  1803. } else {
  1804. // Do not return error for compatibility reason.
  1805. std::string err = cmStrCat("Unexpected argument: ", *i);
  1806. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1807. }
  1808. ++i;
  1809. }
  1810. // Can't calculate hash if we don't save the file.
  1811. // TODO Incrementally calculate hash in the write callback as the file is
  1812. // being downloaded so this check can be relaxed.
  1813. if (file.empty() && hash) {
  1814. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1815. return false;
  1816. }
  1817. // If file exists already, and caller specified an expected md5 or sha,
  1818. // and the existing file already has the expected hash, then simply
  1819. // return.
  1820. //
  1821. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1822. std::string msg;
  1823. std::string actualHash = hash->HashFile(file);
  1824. if (actualHash == expectedHash) {
  1825. msg = cmStrCat("skipping download as file already exists with expected ",
  1826. hashMatchMSG, '"');
  1827. if (!statusVar.empty()) {
  1828. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1829. }
  1830. return true;
  1831. }
  1832. }
  1833. // Make sure parent directory exists so we can write to the file
  1834. // as we receive downloaded bits from curl...
  1835. //
  1836. if (!file.empty()) {
  1837. std::string dir = cmSystemTools::GetFilenamePath(file);
  1838. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1839. !cmSystemTools::MakeDirectory(dir)) {
  1840. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1841. dir +
  1842. "' - Specify file by full path name and verify that you "
  1843. "have directory creation and file write privileges.";
  1844. status.SetError(errstring);
  1845. return false;
  1846. }
  1847. }
  1848. cmsys::ofstream fout;
  1849. if (!file.empty()) {
  1850. fout.open(file.c_str(), std::ios::binary);
  1851. if (!fout) {
  1852. status.SetError("DOWNLOAD cannot open file for write.");
  1853. return false;
  1854. }
  1855. }
  1856. url = cmCurlFixFileURL(url);
  1857. ::CURL* curl;
  1858. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1859. curl = ::curl_easy_init();
  1860. if (!curl) {
  1861. status.SetError("DOWNLOAD error initializing curl.");
  1862. return false;
  1863. }
  1864. cURLEasyGuard g_curl(curl);
  1865. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1866. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1867. // enable HTTP ERROR parsing
  1868. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1869. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1870. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1871. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1872. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1873. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1874. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1875. cmFileCommandCurlDebugCallback);
  1876. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1877. // check to see if TLS verification is requested
  1878. if (tls_verify) {
  1879. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1880. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  1881. } else {
  1882. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1883. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  1884. }
  1885. for (const auto& range : curl_ranges) {
  1886. std::string curl_range = range.first + '-' +
  1887. (range.second.has_value() ? range.second.value() : "");
  1888. res = ::curl_easy_setopt(curl, CURLOPT_RANGE, curl_range.c_str());
  1889. check_curl_result(res, "DOWNLOAD cannot set range: ");
  1890. }
  1891. // check to see if a CAINFO file has been specified
  1892. // command arg comes first
  1893. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1894. if (!cainfo_err.empty()) {
  1895. status.SetError(cainfo_err);
  1896. return false;
  1897. }
  1898. // check to see if netrc parameters have been specified
  1899. // local command args takes precedence over CMAKE_NETRC*
  1900. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1901. std::string const& netrc_option_err =
  1902. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1903. if (!netrc_option_err.empty()) {
  1904. status.SetError(netrc_option_err);
  1905. return false;
  1906. }
  1907. cmFileCommandVectorOfChar chunkDebug;
  1908. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  1909. file.empty() ? nullptr : &fout);
  1910. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1911. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1912. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1913. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1914. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1915. if (!logVar.empty()) {
  1916. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1917. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1918. }
  1919. if (timeout > 0) {
  1920. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1921. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1922. }
  1923. if (inactivity_timeout > 0) {
  1924. // Give up if there is no progress for a long time.
  1925. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1926. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1927. }
  1928. // Need the progress helper's scope to last through the duration of
  1929. // the curl_easy_perform call... so this object is declared at function
  1930. // scope intentionally, rather than inside the "if(showProgress)"
  1931. // block...
  1932. //
  1933. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1934. if (showProgress) {
  1935. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1936. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1937. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  1938. cmFileDownloadProgressCallback);
  1939. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1940. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1941. reinterpret_cast<void*>(&helper));
  1942. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1943. }
  1944. if (!userpwd.empty()) {
  1945. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1946. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1947. }
  1948. struct curl_slist* headers = nullptr;
  1949. for (std::string const& h : curl_headers) {
  1950. headers = ::curl_slist_append(headers, h.c_str());
  1951. }
  1952. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1953. res = ::curl_easy_perform(curl);
  1954. ::curl_slist_free_all(headers);
  1955. /* always cleanup */
  1956. g_curl.release();
  1957. ::curl_easy_cleanup(curl);
  1958. if (!statusVar.empty()) {
  1959. status.GetMakefile().AddDefinition(
  1960. statusVar,
  1961. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1962. }
  1963. ::curl_global_cleanup();
  1964. // Ensure requested curl logs are returned (especially in case of failure)
  1965. //
  1966. if (!logVar.empty()) {
  1967. chunkDebug.push_back(0);
  1968. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1969. }
  1970. // Explicitly flush/close so we can measure the md5 accurately.
  1971. //
  1972. if (!file.empty()) {
  1973. fout.flush();
  1974. fout.close();
  1975. }
  1976. // Verify MD5 sum if requested:
  1977. //
  1978. if (hash) {
  1979. if (res != CURLE_OK) {
  1980. status.SetError(cmStrCat(
  1981. "DOWNLOAD cannot compute hash on failed download\n"
  1982. " status: [",
  1983. static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\"]"));
  1984. return false;
  1985. }
  1986. std::string actualHash = hash->HashFile(file);
  1987. if (actualHash.empty()) {
  1988. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1989. return false;
  1990. }
  1991. if (expectedHash != actualHash) {
  1992. if (!statusVar.empty() && res == 0) {
  1993. status.GetMakefile().AddDefinition(statusVar,
  1994. "1;HASH mismatch: "
  1995. "expected: " +
  1996. expectedHash +
  1997. " actual: " + actualHash);
  1998. }
  1999. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  2000. " for file: [",
  2001. file,
  2002. "]\n"
  2003. " expected hash: [",
  2004. expectedHash,
  2005. "]\n"
  2006. " actual hash: [",
  2007. actualHash, "]\n"));
  2008. return false;
  2009. }
  2010. }
  2011. return true;
  2012. #else
  2013. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  2014. return false;
  2015. #endif
  2016. }
  2017. bool HandleUploadCommand(std::vector<std::string> const& args,
  2018. cmExecutionStatus& status)
  2019. {
  2020. #if !defined(CMAKE_BOOTSTRAP)
  2021. if (args.size() < 3) {
  2022. status.SetError("UPLOAD must be called with at least three arguments.");
  2023. return false;
  2024. }
  2025. auto i = args.begin();
  2026. ++i;
  2027. std::string filename = *i;
  2028. ++i;
  2029. std::string url = *i;
  2030. ++i;
  2031. long timeout = 0;
  2032. long inactivity_timeout = 0;
  2033. std::string logVar;
  2034. std::string statusVar;
  2035. bool showProgress = false;
  2036. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  2037. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  2038. std::string userpwd;
  2039. std::string netrc_level =
  2040. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  2041. std::string netrc_file =
  2042. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  2043. std::vector<std::string> curl_headers;
  2044. while (i != args.end()) {
  2045. if (*i == "TIMEOUT") {
  2046. ++i;
  2047. if (i != args.end()) {
  2048. timeout = atol(i->c_str());
  2049. } else {
  2050. status.SetError("UPLOAD missing time for TIMEOUT.");
  2051. return false;
  2052. }
  2053. } else if (*i == "INACTIVITY_TIMEOUT") {
  2054. ++i;
  2055. if (i != args.end()) {
  2056. inactivity_timeout = atol(i->c_str());
  2057. } else {
  2058. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  2059. return false;
  2060. }
  2061. } else if (*i == "LOG") {
  2062. ++i;
  2063. if (i == args.end()) {
  2064. status.SetError("UPLOAD missing VAR for LOG.");
  2065. return false;
  2066. }
  2067. logVar = *i;
  2068. } else if (*i == "STATUS") {
  2069. ++i;
  2070. if (i == args.end()) {
  2071. status.SetError("UPLOAD missing VAR for STATUS.");
  2072. return false;
  2073. }
  2074. statusVar = *i;
  2075. } else if (*i == "SHOW_PROGRESS") {
  2076. showProgress = true;
  2077. } else if (*i == "TLS_VERIFY") {
  2078. ++i;
  2079. if (i != args.end()) {
  2080. tls_verify = cmIsOn(*i);
  2081. } else {
  2082. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  2083. return false;
  2084. }
  2085. } else if (*i == "TLS_CAINFO") {
  2086. ++i;
  2087. if (i != args.end()) {
  2088. cainfo = cmValue(*i);
  2089. } else {
  2090. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  2091. return false;
  2092. }
  2093. } else if (*i == "NETRC_FILE") {
  2094. ++i;
  2095. if (i != args.end()) {
  2096. netrc_file = *i;
  2097. } else {
  2098. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  2099. return false;
  2100. }
  2101. } else if (*i == "NETRC") {
  2102. ++i;
  2103. if (i != args.end()) {
  2104. netrc_level = *i;
  2105. } else {
  2106. status.SetError("UPLOAD missing level value for NETRC.");
  2107. return false;
  2108. }
  2109. } else if (*i == "USERPWD") {
  2110. ++i;
  2111. if (i == args.end()) {
  2112. status.SetError("UPLOAD missing string for USERPWD.");
  2113. return false;
  2114. }
  2115. userpwd = *i;
  2116. } else if (*i == "HTTPHEADER") {
  2117. ++i;
  2118. if (i == args.end()) {
  2119. status.SetError("UPLOAD missing string for HTTPHEADER.");
  2120. return false;
  2121. }
  2122. curl_headers.push_back(*i);
  2123. } else {
  2124. // Do not return error for compatibility reason.
  2125. std::string err = cmStrCat("Unexpected argument: ", *i);
  2126. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  2127. }
  2128. ++i;
  2129. }
  2130. // Open file for reading:
  2131. //
  2132. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2133. if (!fin) {
  2134. std::string errStr =
  2135. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  2136. status.SetError(errStr);
  2137. return false;
  2138. }
  2139. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2140. url = cmCurlFixFileURL(url);
  2141. ::CURL* curl;
  2142. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2143. curl = ::curl_easy_init();
  2144. if (!curl) {
  2145. status.SetError("UPLOAD error initializing curl.");
  2146. fclose(fin);
  2147. return false;
  2148. }
  2149. cURLEasyGuard g_curl(curl);
  2150. // enable HTTP ERROR parsing
  2151. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2152. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2153. // enable uploading
  2154. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2155. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2156. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2157. check_curl_result(res, "UPLOAD cannot set url: ");
  2158. res =
  2159. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2160. check_curl_result(res, "UPLOAD cannot set write function: ");
  2161. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2162. cmFileCommandCurlDebugCallback);
  2163. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2164. // check to see if TLS verification is requested
  2165. if (tls_verify) {
  2166. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2167. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  2168. } else {
  2169. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2170. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  2171. }
  2172. // check to see if a CAINFO file has been specified
  2173. // command arg comes first
  2174. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2175. if (!cainfo_err.empty()) {
  2176. status.SetError(cainfo_err);
  2177. return false;
  2178. }
  2179. cmFileCommandVectorOfChar chunkResponse;
  2180. cmFileCommandVectorOfChar chunkDebug;
  2181. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2182. check_curl_result(res, "UPLOAD cannot set write data: ");
  2183. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2184. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2185. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2186. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2187. if (!logVar.empty()) {
  2188. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2189. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2190. }
  2191. if (timeout > 0) {
  2192. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2193. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2194. }
  2195. if (inactivity_timeout > 0) {
  2196. // Give up if there is no progress for a long time.
  2197. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2198. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2199. }
  2200. // Need the progress helper's scope to last through the duration of
  2201. // the curl_easy_perform call... so this object is declared at function
  2202. // scope intentionally, rather than inside the "if(showProgress)"
  2203. // block...
  2204. //
  2205. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2206. if (showProgress) {
  2207. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2208. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2209. res = ::curl_easy_setopt(curl, CM_CURLOPT_XFERINFOFUNCTION,
  2210. cmFileUploadProgressCallback);
  2211. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2212. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2213. reinterpret_cast<void*>(&helper));
  2214. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2215. }
  2216. // now specify which file to upload
  2217. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2218. check_curl_result(res, "UPLOAD cannot set input file: ");
  2219. // and give the size of the upload (optional)
  2220. res =
  2221. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2222. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2223. if (!userpwd.empty()) {
  2224. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2225. check_curl_result(res, "UPLOAD cannot set user password: ");
  2226. }
  2227. // check to see if netrc parameters have been specified
  2228. // local command args takes precedence over CMAKE_NETRC*
  2229. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2230. std::string const& netrc_option_err =
  2231. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2232. if (!netrc_option_err.empty()) {
  2233. status.SetError(netrc_option_err);
  2234. return false;
  2235. }
  2236. struct curl_slist* headers = nullptr;
  2237. for (std::string const& h : curl_headers) {
  2238. headers = ::curl_slist_append(headers, h.c_str());
  2239. }
  2240. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2241. res = ::curl_easy_perform(curl);
  2242. ::curl_slist_free_all(headers);
  2243. /* always cleanup */
  2244. g_curl.release();
  2245. ::curl_easy_cleanup(curl);
  2246. if (!statusVar.empty()) {
  2247. status.GetMakefile().AddDefinition(
  2248. statusVar,
  2249. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2250. }
  2251. ::curl_global_cleanup();
  2252. fclose(fin);
  2253. fin = nullptr;
  2254. if (!logVar.empty()) {
  2255. std::string log;
  2256. if (!chunkResponse.empty()) {
  2257. chunkResponse.push_back(0);
  2258. log += "Response:\n";
  2259. log += chunkResponse.data();
  2260. log += "\n";
  2261. }
  2262. if (!chunkDebug.empty()) {
  2263. chunkDebug.push_back(0);
  2264. log += "Debug:\n";
  2265. log += chunkDebug.data();
  2266. log += "\n";
  2267. }
  2268. status.GetMakefile().AddDefinition(logVar, log);
  2269. }
  2270. return true;
  2271. #else
  2272. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2273. return false;
  2274. #endif
  2275. }
  2276. void AddEvaluationFile(const std::string& inputName,
  2277. const std::string& targetName,
  2278. const std::string& outputExpr,
  2279. const std::string& condition, bool inputIsContent,
  2280. const std::string& newLineCharacter, mode_t permissions,
  2281. cmExecutionStatus& status)
  2282. {
  2283. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2284. cmGeneratorExpression outputGe(*status.GetMakefile().GetCMakeInstance(),
  2285. lfbt);
  2286. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2287. outputGe.Parse(outputExpr);
  2288. cmGeneratorExpression conditionGe(*status.GetMakefile().GetCMakeInstance(),
  2289. lfbt);
  2290. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2291. conditionGe.Parse(condition);
  2292. status.GetMakefile().AddEvaluationFile(
  2293. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2294. newLineCharacter, permissions, inputIsContent);
  2295. }
  2296. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2297. cmExecutionStatus& status)
  2298. {
  2299. if (args.size() < 5) {
  2300. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2301. return false;
  2302. }
  2303. struct Arguments : public ArgumentParser::ParseResult
  2304. {
  2305. cm::optional<std::string> Output;
  2306. cm::optional<std::string> Input;
  2307. cm::optional<std::string> Content;
  2308. cm::optional<std::string> Condition;
  2309. cm::optional<std::string> Target;
  2310. cm::optional<std::string> NewLineStyle;
  2311. bool NoSourcePermissions = false;
  2312. bool UseSourcePermissions = false;
  2313. ArgumentParser::NonEmpty<std::vector<std::string>> FilePermissions;
  2314. std::vector<cm::string_view> ParsedKeywords;
  2315. };
  2316. static auto const parser =
  2317. cmArgumentParser<Arguments>{}
  2318. .Bind("OUTPUT"_s, &Arguments::Output)
  2319. .Bind("INPUT"_s, &Arguments::Input)
  2320. .Bind("CONTENT"_s, &Arguments::Content)
  2321. .Bind("CONDITION"_s, &Arguments::Condition)
  2322. .Bind("TARGET"_s, &Arguments::Target)
  2323. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2324. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2325. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2326. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle)
  2327. .BindParsedKeywords(&Arguments::ParsedKeywords);
  2328. std::vector<std::string> unparsedArguments;
  2329. Arguments const arguments =
  2330. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments);
  2331. if (arguments.MaybeReportError(status.GetMakefile())) {
  2332. return true;
  2333. }
  2334. if (!unparsedArguments.empty()) {
  2335. status.SetError("Unknown argument to GENERATE subcommand.");
  2336. return false;
  2337. }
  2338. if (!arguments.Output || arguments.ParsedKeywords[0] != "OUTPUT"_s) {
  2339. status.SetError("GENERATE requires OUTPUT as first option.");
  2340. return false;
  2341. }
  2342. std::string const& output = *arguments.Output;
  2343. if (!arguments.Input && !arguments.Content) {
  2344. status.SetError("GENERATE requires INPUT or CONTENT option.");
  2345. return false;
  2346. }
  2347. const bool inputIsContent = arguments.ParsedKeywords[1] == "CONTENT"_s;
  2348. if (!inputIsContent && arguments.ParsedKeywords[1] != "INPUT") {
  2349. status.SetError("Unknown argument to GENERATE subcommand.");
  2350. return false;
  2351. }
  2352. std::string const& input =
  2353. inputIsContent ? *arguments.Content : *arguments.Input;
  2354. if (arguments.Condition && arguments.Condition->empty()) {
  2355. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2356. "if specified.");
  2357. return false;
  2358. }
  2359. std::string const& condition =
  2360. arguments.Condition ? *arguments.Condition : std::string();
  2361. if (arguments.Target && arguments.Target->empty()) {
  2362. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2363. "if specified.");
  2364. return false;
  2365. }
  2366. std::string const& target =
  2367. arguments.Target ? *arguments.Target : std::string();
  2368. cmNewLineStyle newLineStyle;
  2369. if (arguments.NewLineStyle) {
  2370. std::string errorMessage;
  2371. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2372. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2373. return false;
  2374. }
  2375. }
  2376. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2377. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2378. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2379. return false;
  2380. }
  2381. if (!arguments.FilePermissions.empty()) {
  2382. if (arguments.NoSourcePermissions) {
  2383. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2384. "FILE_PERMISSIONS. Only one option allowed.");
  2385. return false;
  2386. }
  2387. if (arguments.UseSourcePermissions) {
  2388. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2389. "FILE_PERMISSIONS. Only one option allowed.");
  2390. return false;
  2391. }
  2392. }
  2393. if (arguments.UseSourcePermissions) {
  2394. if (inputIsContent) {
  2395. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2396. return false;
  2397. }
  2398. }
  2399. mode_t permissions = 0;
  2400. if (arguments.NoSourcePermissions) {
  2401. permissions |= cmFSPermissions::mode_owner_read;
  2402. permissions |= cmFSPermissions::mode_owner_write;
  2403. permissions |= cmFSPermissions::mode_group_read;
  2404. permissions |= cmFSPermissions::mode_world_read;
  2405. }
  2406. if (!arguments.FilePermissions.empty()) {
  2407. std::vector<std::string> invalidOptions;
  2408. for (auto const& e : arguments.FilePermissions) {
  2409. if (!cmFSPermissions::stringToModeT(e, permissions)) {
  2410. invalidOptions.push_back(e);
  2411. }
  2412. }
  2413. if (!invalidOptions.empty()) {
  2414. std::ostringstream oss;
  2415. oss << "given invalid permission ";
  2416. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2417. if (i == 0u) {
  2418. oss << "\"" << invalidOptions[i] << "\"";
  2419. } else {
  2420. oss << ",\"" << invalidOptions[i] << "\"";
  2421. }
  2422. }
  2423. oss << ".";
  2424. status.SetError(oss.str());
  2425. return false;
  2426. }
  2427. }
  2428. AddEvaluationFile(input, target, output, condition, inputIsContent,
  2429. newLineStyle.GetCharacters(), permissions, status);
  2430. return true;
  2431. }
  2432. bool HandleLockCommand(std::vector<std::string> const& args,
  2433. cmExecutionStatus& status)
  2434. {
  2435. #if !defined(CMAKE_BOOTSTRAP)
  2436. // Default values
  2437. bool directory = false;
  2438. bool release = false;
  2439. enum Guard
  2440. {
  2441. GUARD_FUNCTION,
  2442. GUARD_FILE,
  2443. GUARD_PROCESS
  2444. };
  2445. Guard guard = GUARD_PROCESS;
  2446. std::string resultVariable;
  2447. unsigned long timeout = static_cast<unsigned long>(-1);
  2448. // Parse arguments
  2449. if (args.size() < 2) {
  2450. status.GetMakefile().IssueMessage(
  2451. MessageType::FATAL_ERROR,
  2452. "sub-command LOCK requires at least two arguments.");
  2453. return false;
  2454. }
  2455. std::string path = args[1];
  2456. for (unsigned i = 2; i < args.size(); ++i) {
  2457. if (args[i] == "DIRECTORY") {
  2458. directory = true;
  2459. } else if (args[i] == "RELEASE") {
  2460. release = true;
  2461. } else if (args[i] == "GUARD") {
  2462. ++i;
  2463. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2464. if (i >= args.size()) {
  2465. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2466. return false;
  2467. }
  2468. if (args[i] == "FUNCTION") {
  2469. guard = GUARD_FUNCTION;
  2470. } else if (args[i] == "FILE") {
  2471. guard = GUARD_FILE;
  2472. } else if (args[i] == "PROCESS") {
  2473. guard = GUARD_PROCESS;
  2474. } else {
  2475. status.GetMakefile().IssueMessage(
  2476. MessageType::FATAL_ERROR,
  2477. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2478. return false;
  2479. }
  2480. } else if (args[i] == "RESULT_VARIABLE") {
  2481. ++i;
  2482. if (i >= args.size()) {
  2483. status.GetMakefile().IssueMessage(
  2484. MessageType::FATAL_ERROR,
  2485. "expected variable name after RESULT_VARIABLE");
  2486. return false;
  2487. }
  2488. resultVariable = args[i];
  2489. } else if (args[i] == "TIMEOUT") {
  2490. ++i;
  2491. if (i >= args.size()) {
  2492. status.GetMakefile().IssueMessage(
  2493. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2494. return false;
  2495. }
  2496. long scanned;
  2497. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2498. status.GetMakefile().IssueMessage(
  2499. MessageType::FATAL_ERROR,
  2500. cmStrCat("TIMEOUT value \"", args[i],
  2501. "\" is not an unsigned integer."));
  2502. return false;
  2503. }
  2504. timeout = static_cast<unsigned long>(scanned);
  2505. } else {
  2506. status.GetMakefile().IssueMessage(
  2507. MessageType::FATAL_ERROR,
  2508. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2509. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2510. return false;
  2511. }
  2512. }
  2513. if (directory) {
  2514. path += "/cmake.lock";
  2515. }
  2516. // Unify path (remove '//', '/../', ...)
  2517. path = cmSystemTools::CollapseFullPath(
  2518. path, status.GetMakefile().GetCurrentSourceDirectory());
  2519. // Create file and directories if needed
  2520. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2521. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2522. status.GetMakefile().IssueMessage(
  2523. MessageType::FATAL_ERROR,
  2524. cmStrCat("directory\n \"", parentDir,
  2525. "\"\ncreation failed (check permissions)."));
  2526. cmSystemTools::SetFatalErrorOccurred();
  2527. return false;
  2528. }
  2529. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2530. if (!file) {
  2531. status.GetMakefile().IssueMessage(
  2532. MessageType::FATAL_ERROR,
  2533. cmStrCat("file\n \"", path,
  2534. "\"\ncreation failed (check permissions)."));
  2535. cmSystemTools::SetFatalErrorOccurred();
  2536. return false;
  2537. }
  2538. fclose(file);
  2539. // Actual lock/unlock
  2540. cmFileLockPool& lockPool =
  2541. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2542. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2543. if (release) {
  2544. fileLockResult = lockPool.Release(path);
  2545. } else {
  2546. switch (guard) {
  2547. case GUARD_FUNCTION:
  2548. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2549. break;
  2550. case GUARD_FILE:
  2551. fileLockResult = lockPool.LockFileScope(path, timeout);
  2552. break;
  2553. case GUARD_PROCESS:
  2554. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2555. break;
  2556. default:
  2557. cmSystemTools::SetFatalErrorOccurred();
  2558. return false;
  2559. }
  2560. }
  2561. const std::string result = fileLockResult.GetOutputMessage();
  2562. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2563. status.GetMakefile().IssueMessage(
  2564. MessageType::FATAL_ERROR,
  2565. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2566. cmSystemTools::SetFatalErrorOccurred();
  2567. return false;
  2568. }
  2569. if (!resultVariable.empty()) {
  2570. status.GetMakefile().AddDefinition(resultVariable, result);
  2571. }
  2572. return true;
  2573. #else
  2574. static_cast<void>(args);
  2575. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2576. return false;
  2577. #endif
  2578. }
  2579. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2580. cmExecutionStatus& status)
  2581. {
  2582. if (args.size() < 3) {
  2583. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2584. return false;
  2585. }
  2586. if (args.size() > 5) {
  2587. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2588. return false;
  2589. }
  2590. unsigned int argsIndex = 1;
  2591. std::string filename = args[argsIndex++];
  2592. if (!cmsys::SystemTools::FileIsFullPath(filename)) {
  2593. filename = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  2594. filename);
  2595. }
  2596. const std::string& outputVariable = args[argsIndex++];
  2597. std::string formatString;
  2598. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2599. formatString = args[argsIndex++];
  2600. }
  2601. bool utcFlag = false;
  2602. if (args.size() > argsIndex) {
  2603. if (args[argsIndex] == "UTC") {
  2604. utcFlag = true;
  2605. } else {
  2606. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2607. args[argsIndex] + ".";
  2608. status.SetError(e);
  2609. return false;
  2610. }
  2611. }
  2612. cmTimestamp timestamp;
  2613. std::string result =
  2614. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2615. status.GetMakefile().AddDefinition(outputVariable, result);
  2616. return true;
  2617. }
  2618. bool HandleSizeCommand(std::vector<std::string> const& args,
  2619. cmExecutionStatus& status)
  2620. {
  2621. if (args.size() != 3) {
  2622. status.SetError(
  2623. cmStrCat(args[0], " requires a file name and output variable"));
  2624. return false;
  2625. }
  2626. unsigned int argsIndex = 1;
  2627. const std::string& filename = args[argsIndex++];
  2628. const std::string& outputVariable = args[argsIndex++];
  2629. if (!cmSystemTools::FileExists(filename, true)) {
  2630. status.SetError(
  2631. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2632. return false;
  2633. }
  2634. status.GetMakefile().AddDefinition(
  2635. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2636. return true;
  2637. }
  2638. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2639. cmExecutionStatus& status)
  2640. {
  2641. if (args.size() != 3) {
  2642. status.SetError(
  2643. cmStrCat(args[0], " requires a file name and output variable"));
  2644. return false;
  2645. }
  2646. const std::string& filename = args[1];
  2647. const std::string& outputVariable = args[2];
  2648. std::string result;
  2649. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2650. status.SetError(cmStrCat(
  2651. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2652. return false;
  2653. }
  2654. status.GetMakefile().AddDefinition(outputVariable, result);
  2655. return true;
  2656. }
  2657. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2658. cmExecutionStatus& status)
  2659. {
  2660. if (args.size() < 3) {
  2661. status.SetError("CREATE_LINK must be called with at least two additional "
  2662. "arguments");
  2663. return false;
  2664. }
  2665. std::string const& fileName = args[1];
  2666. std::string const& newFileName = args[2];
  2667. struct Arguments
  2668. {
  2669. std::string Result;
  2670. bool CopyOnError = false;
  2671. bool Symbolic = false;
  2672. };
  2673. static auto const parser =
  2674. cmArgumentParser<Arguments>{}
  2675. .Bind("RESULT"_s, &Arguments::Result)
  2676. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2677. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2678. std::vector<std::string> unconsumedArgs;
  2679. Arguments const arguments =
  2680. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2681. if (!unconsumedArgs.empty()) {
  2682. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2683. return false;
  2684. }
  2685. // The system error message generated in the operation.
  2686. std::string result;
  2687. // Check if the paths are distinct.
  2688. if (fileName == newFileName) {
  2689. result = "CREATE_LINK cannot use same file and newfile";
  2690. if (!arguments.Result.empty()) {
  2691. status.GetMakefile().AddDefinition(arguments.Result, result);
  2692. return true;
  2693. }
  2694. status.SetError(result);
  2695. return false;
  2696. }
  2697. // Hard link requires original file to exist.
  2698. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2699. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2700. if (!arguments.Result.empty()) {
  2701. status.GetMakefile().AddDefinition(arguments.Result, result);
  2702. return true;
  2703. }
  2704. status.SetError(result);
  2705. return false;
  2706. }
  2707. // Check if the new file already exists and remove it.
  2708. if (cmSystemTools::PathExists(newFileName) &&
  2709. !cmSystemTools::RemoveFile(newFileName)) {
  2710. std::ostringstream e;
  2711. e << "Failed to create link '" << newFileName
  2712. << "' because existing path cannot be removed: "
  2713. << cmSystemTools::GetLastSystemError() << "\n";
  2714. if (!arguments.Result.empty()) {
  2715. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2716. return true;
  2717. }
  2718. status.SetError(e.str());
  2719. return false;
  2720. }
  2721. // Whether the operation completed successfully.
  2722. bool completed = false;
  2723. // Check if the command requires a symbolic link.
  2724. if (arguments.Symbolic) {
  2725. cmsys::Status linked =
  2726. cmSystemTools::CreateSymlinkQuietly(fileName, newFileName);
  2727. if (linked) {
  2728. completed = true;
  2729. } else {
  2730. result = cmStrCat("failed to create symbolic link '", newFileName,
  2731. "': ", linked.GetString());
  2732. }
  2733. } else {
  2734. cmsys::Status linked =
  2735. cmSystemTools::CreateLinkQuietly(fileName, newFileName);
  2736. if (linked) {
  2737. completed = true;
  2738. } else {
  2739. result = cmStrCat("failed to create link '", newFileName,
  2740. "': ", linked.GetString());
  2741. }
  2742. }
  2743. // Check if copy-on-error is enabled in the arguments.
  2744. if (!completed && arguments.CopyOnError) {
  2745. cmsys::Status copied =
  2746. cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2747. if (copied) {
  2748. completed = true;
  2749. } else {
  2750. result = "Copy failed: " + copied.GetString();
  2751. }
  2752. }
  2753. // Check if the operation was successful.
  2754. if (completed) {
  2755. result = "0";
  2756. } else if (arguments.Result.empty()) {
  2757. // The operation failed and the result is not reported in a variable.
  2758. status.SetError(result);
  2759. return false;
  2760. }
  2761. if (!arguments.Result.empty()) {
  2762. status.GetMakefile().AddDefinition(arguments.Result, result);
  2763. }
  2764. return true;
  2765. }
  2766. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2767. cmExecutionStatus& status)
  2768. {
  2769. std::string platform =
  2770. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2771. if (!cmRuntimeDependencyArchive::PlatformSupportsRuntimeDependencies(
  2772. platform)) {
  2773. status.SetError(
  2774. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2775. platform, "\""));
  2776. cmSystemTools::SetFatalErrorOccurred();
  2777. return false;
  2778. }
  2779. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2780. status.GetMakefile().IssueMessage(
  2781. MessageType::AUTHOR_WARNING,
  2782. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2783. " in project mode. This is probably not what "
  2784. "you intended to do. Instead, please consider"
  2785. " using it in an install(CODE) or "
  2786. "install(SCRIPT) command. For example:"
  2787. "\n install(CODE [["
  2788. "\n file(GET_RUNTIME_DEPENDENCIES"
  2789. "\n # ..."
  2790. "\n )"
  2791. "\n ]])");
  2792. }
  2793. struct Arguments : public ArgumentParser::ParseResult
  2794. {
  2795. std::string ResolvedDependenciesVar;
  2796. std::string UnresolvedDependenciesVar;
  2797. std::string ConflictingDependenciesPrefix;
  2798. std::string RPathPrefix;
  2799. std::string BundleExecutable;
  2800. ArgumentParser::MaybeEmpty<std::vector<std::string>> Executables;
  2801. ArgumentParser::MaybeEmpty<std::vector<std::string>> Libraries;
  2802. ArgumentParser::MaybeEmpty<std::vector<std::string>> Directories;
  2803. ArgumentParser::MaybeEmpty<std::vector<std::string>> Modules;
  2804. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreIncludeRegexes;
  2805. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreExcludeRegexes;
  2806. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeRegexes;
  2807. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeRegexes;
  2808. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeFiles;
  2809. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeFiles;
  2810. ArgumentParser::MaybeEmpty<std::vector<std::string>>
  2811. PostExcludeFilesStrict;
  2812. };
  2813. static auto const parser =
  2814. cmArgumentParser<Arguments>{}
  2815. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2816. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2817. &Arguments::UnresolvedDependenciesVar)
  2818. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2819. &Arguments::ConflictingDependenciesPrefix)
  2820. .Bind("RPATH_PREFIX"_s, &Arguments::RPathPrefix)
  2821. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2822. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2823. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2824. .Bind("MODULES"_s, &Arguments::Modules)
  2825. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2826. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2827. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2828. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2829. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes)
  2830. .Bind("POST_INCLUDE_FILES"_s, &Arguments::PostIncludeFiles)
  2831. .Bind("POST_EXCLUDE_FILES"_s, &Arguments::PostExcludeFiles)
  2832. .Bind("POST_EXCLUDE_FILES_STRICT"_s, &Arguments::PostExcludeFilesStrict);
  2833. std::vector<std::string> unrecognizedArguments;
  2834. auto parsedArgs =
  2835. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2836. auto argIt = unrecognizedArguments.begin();
  2837. if (argIt != unrecognizedArguments.end()) {
  2838. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2839. cmSystemTools::SetFatalErrorOccurred();
  2840. return false;
  2841. }
  2842. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2843. cmSystemTools::SetFatalErrorOccurred();
  2844. return true;
  2845. }
  2846. cmRuntimeDependencyArchive archive(
  2847. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2848. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2849. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes,
  2850. std::move(parsedArgs.PostIncludeFiles),
  2851. std::move(parsedArgs.PostExcludeFiles),
  2852. std::move(parsedArgs.PostExcludeFilesStrict));
  2853. if (!archive.Prepare()) {
  2854. cmSystemTools::SetFatalErrorOccurred();
  2855. return false;
  2856. }
  2857. if (!archive.GetRuntimeDependencies(
  2858. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2859. cmSystemTools::SetFatalErrorOccurred();
  2860. return false;
  2861. }
  2862. std::vector<std::string> deps;
  2863. std::vector<std::string> unresolvedDeps;
  2864. std::vector<std::string> conflictingDeps;
  2865. for (auto const& val : archive.GetResolvedPaths()) {
  2866. bool unique = true;
  2867. auto it = val.second.begin();
  2868. assert(it != val.second.end());
  2869. auto const& firstPath = *it;
  2870. while (++it != val.second.end()) {
  2871. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2872. unique = false;
  2873. break;
  2874. }
  2875. }
  2876. if (unique) {
  2877. deps.push_back(firstPath);
  2878. if (!parsedArgs.RPathPrefix.empty()) {
  2879. status.GetMakefile().AddDefinition(
  2880. parsedArgs.RPathPrefix + "_" + firstPath,
  2881. cmList::to_string(archive.GetRPaths().at(firstPath)));
  2882. }
  2883. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2884. conflictingDeps.push_back(val.first);
  2885. std::vector<std::string> paths;
  2886. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2887. std::string varName =
  2888. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2889. std::string pathsStr = cmList::to_string(paths);
  2890. status.GetMakefile().AddDefinition(varName, pathsStr);
  2891. } else {
  2892. std::ostringstream e;
  2893. e << "Multiple conflicting paths found for " << val.first << ":";
  2894. for (auto const& path : val.second) {
  2895. e << "\n " << path;
  2896. }
  2897. status.SetError(e.str());
  2898. cmSystemTools::SetFatalErrorOccurred();
  2899. return false;
  2900. }
  2901. }
  2902. if (!archive.GetUnresolvedPaths().empty()) {
  2903. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2904. unresolvedDeps.insert(unresolvedDeps.begin(),
  2905. archive.GetUnresolvedPaths().begin(),
  2906. archive.GetUnresolvedPaths().end());
  2907. } else {
  2908. std::ostringstream e;
  2909. e << "Could not resolve runtime dependencies:";
  2910. for (auto const& path : archive.GetUnresolvedPaths()) {
  2911. e << "\n " << path;
  2912. }
  2913. status.SetError(e.str());
  2914. cmSystemTools::SetFatalErrorOccurred();
  2915. return false;
  2916. }
  2917. }
  2918. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2919. std::string val = cmList::to_string(deps);
  2920. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2921. val);
  2922. }
  2923. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2924. std::string val = cmList::to_string(unresolvedDeps);
  2925. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2926. val);
  2927. }
  2928. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2929. std::string val = cmList::to_string(conflictingDeps);
  2930. status.GetMakefile().AddDefinition(
  2931. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2932. }
  2933. return true;
  2934. }
  2935. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2936. cmExecutionStatus& status)
  2937. {
  2938. struct Arguments : public ArgumentParser::ParseResult
  2939. {
  2940. cm::optional<std::string> Output;
  2941. cm::optional<std::string> Content;
  2942. bool EscapeQuotes = false;
  2943. bool AtOnly = false;
  2944. // "NEWLINE_STYLE" requires one value, but we use a custom check below.
  2945. ArgumentParser::Maybe<std::string> NewlineStyle;
  2946. };
  2947. static auto const parser =
  2948. cmArgumentParser<Arguments>{}
  2949. .Bind("OUTPUT"_s, &Arguments::Output)
  2950. .Bind("CONTENT"_s, &Arguments::Content)
  2951. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  2952. .Bind("@ONLY"_s, &Arguments::AtOnly)
  2953. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  2954. std::vector<std::string> unrecognizedArguments;
  2955. auto parsedArgs =
  2956. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2957. auto argIt = unrecognizedArguments.begin();
  2958. if (argIt != unrecognizedArguments.end()) {
  2959. status.SetError(
  2960. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  2961. cmSystemTools::SetFatalErrorOccurred();
  2962. return false;
  2963. }
  2964. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2965. cmSystemTools::SetFatalErrorOccurred();
  2966. return true;
  2967. }
  2968. if (!parsedArgs.Output) {
  2969. status.SetError("CONFIGURE OUTPUT option is mandatory.");
  2970. cmSystemTools::SetFatalErrorOccurred();
  2971. return false;
  2972. }
  2973. if (!parsedArgs.Content) {
  2974. status.SetError("CONFIGURE CONTENT option is mandatory.");
  2975. cmSystemTools::SetFatalErrorOccurred();
  2976. return false;
  2977. }
  2978. std::string errorMessage;
  2979. cmNewLineStyle newLineStyle;
  2980. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2981. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2982. return false;
  2983. }
  2984. // Check for generator expressions
  2985. std::string outputFile = cmSystemTools::CollapseFullPath(
  2986. *parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  2987. std::string::size_type pos = outputFile.find_first_of("<>");
  2988. if (pos != std::string::npos) {
  2989. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2990. outputFile[pos],
  2991. "\". This character is not allowed."));
  2992. return false;
  2993. }
  2994. cmMakefile& makeFile = status.GetMakefile();
  2995. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2996. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2997. " into a source directory.");
  2998. return false;
  2999. }
  3000. cmSystemTools::ConvertToUnixSlashes(outputFile);
  3001. // Re-generate if non-temporary outputs are missing.
  3002. // when we finalize the configuration we will remove all
  3003. // output files that now don't exist.
  3004. makeFile.AddCMakeOutputFile(outputFile);
  3005. // Create output directory
  3006. const std::string::size_type slashPos = outputFile.rfind('/');
  3007. if (slashPos != std::string::npos) {
  3008. const std::string path = outputFile.substr(0, slashPos);
  3009. cmSystemTools::MakeDirectory(path);
  3010. }
  3011. std::string newLineCharacters = "\n";
  3012. bool open_with_binary_flag = false;
  3013. if (newLineStyle.IsValid()) {
  3014. newLineCharacters = newLineStyle.GetCharacters();
  3015. open_with_binary_flag = true;
  3016. }
  3017. cmGeneratedFileStream fout;
  3018. fout.Open(outputFile, false, open_with_binary_flag);
  3019. if (!fout) {
  3020. cmSystemTools::Error("Could not open file for write in copy operation " +
  3021. outputFile);
  3022. cmSystemTools::ReportLastSystemError("");
  3023. return false;
  3024. }
  3025. fout.SetCopyIfDifferent(true);
  3026. // copy input to output and expand variables from input at the same time
  3027. std::stringstream sin(*parsedArgs.Content, std::ios::in);
  3028. std::string inLine;
  3029. std::string outLine;
  3030. bool hasNewLine = false;
  3031. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  3032. outLine.clear();
  3033. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  3034. parsedArgs.EscapeQuotes);
  3035. fout << outLine;
  3036. if (hasNewLine || newLineStyle.IsValid()) {
  3037. fout << newLineCharacters;
  3038. }
  3039. }
  3040. // close file before attempting to copy
  3041. fout.close();
  3042. return true;
  3043. }
  3044. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  3045. cmExecutionStatus& status)
  3046. {
  3047. struct Arguments : public ArgumentParser::ParseResult
  3048. {
  3049. std::string Output;
  3050. std::string Format;
  3051. std::string Compression;
  3052. std::string CompressionLevel;
  3053. // "MTIME" should require one value, but it has long been accidentally
  3054. // accepted without one and treated as if an empty value were given.
  3055. // Fixing this would require a policy.
  3056. ArgumentParser::Maybe<std::string> MTime;
  3057. bool Verbose = false;
  3058. // "PATHS" requires at least one value, but use a custom check below.
  3059. ArgumentParser::MaybeEmpty<std::vector<std::string>> Paths;
  3060. };
  3061. static auto const parser =
  3062. cmArgumentParser<Arguments>{}
  3063. .Bind("OUTPUT"_s, &Arguments::Output)
  3064. .Bind("FORMAT"_s, &Arguments::Format)
  3065. .Bind("COMPRESSION"_s, &Arguments::Compression)
  3066. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  3067. .Bind("MTIME"_s, &Arguments::MTime)
  3068. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3069. .Bind("PATHS"_s, &Arguments::Paths);
  3070. std::vector<std::string> unrecognizedArguments;
  3071. auto parsedArgs =
  3072. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3073. auto argIt = unrecognizedArguments.begin();
  3074. if (argIt != unrecognizedArguments.end()) {
  3075. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3076. cmSystemTools::SetFatalErrorOccurred();
  3077. return false;
  3078. }
  3079. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3080. cmSystemTools::SetFatalErrorOccurred();
  3081. return true;
  3082. }
  3083. const char* knownFormats[] = {
  3084. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  3085. };
  3086. if (!parsedArgs.Format.empty() &&
  3087. !cm::contains(knownFormats, parsedArgs.Format)) {
  3088. status.SetError(
  3089. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  3090. cmSystemTools::SetFatalErrorOccurred();
  3091. return false;
  3092. }
  3093. const char* zipFileFormats[] = { "7zip", "zip" };
  3094. if (!parsedArgs.Compression.empty() &&
  3095. cm::contains(zipFileFormats, parsedArgs.Format)) {
  3096. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  3097. " does not support COMPRESSION arguments"));
  3098. cmSystemTools::SetFatalErrorOccurred();
  3099. return false;
  3100. }
  3101. static std::map<std::string, cmSystemTools::cmTarCompression>
  3102. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  3103. { "BZip2", cmSystemTools::TarCompressBZip2 },
  3104. { "GZip", cmSystemTools::TarCompressGZip },
  3105. { "XZ", cmSystemTools::TarCompressXZ },
  3106. { "Zstd", cmSystemTools::TarCompressZstd } };
  3107. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  3108. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  3109. if (typeIt != compressionTypeMap.end()) {
  3110. compress = typeIt->second;
  3111. } else if (!parsedArgs.Compression.empty()) {
  3112. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  3113. " is not supported"));
  3114. cmSystemTools::SetFatalErrorOccurred();
  3115. return false;
  3116. }
  3117. int compressionLevel = 0;
  3118. int minCompressionLevel = 0;
  3119. int maxCompressionLevel = 9;
  3120. if (compress == cmSystemTools::TarCompressZstd) {
  3121. maxCompressionLevel = 19;
  3122. }
  3123. if (!parsedArgs.CompressionLevel.empty()) {
  3124. if (parsedArgs.CompressionLevel.size() != 1 &&
  3125. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  3126. status.SetError(
  3127. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3128. parsedArgs.Compression, " should be in range ",
  3129. minCompressionLevel, " to ", maxCompressionLevel));
  3130. cmSystemTools::SetFatalErrorOccurred();
  3131. return false;
  3132. }
  3133. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  3134. if (compressionLevel < minCompressionLevel ||
  3135. compressionLevel > maxCompressionLevel) {
  3136. status.SetError(
  3137. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3138. parsedArgs.Compression, " should be in range ",
  3139. minCompressionLevel, " to ", maxCompressionLevel));
  3140. cmSystemTools::SetFatalErrorOccurred();
  3141. return false;
  3142. }
  3143. if (compress == cmSystemTools::TarCompressNone) {
  3144. status.SetError(cmStrCat("compression level is not supported for "
  3145. "compression \"None\"",
  3146. parsedArgs.Compression));
  3147. cmSystemTools::SetFatalErrorOccurred();
  3148. return false;
  3149. }
  3150. }
  3151. if (parsedArgs.Paths.empty()) {
  3152. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  3153. cmSystemTools::SetFatalErrorOccurred();
  3154. return false;
  3155. }
  3156. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths, compress,
  3157. parsedArgs.Verbose, parsedArgs.MTime,
  3158. parsedArgs.Format, compressionLevel)) {
  3159. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  3160. cmSystemTools::SetFatalErrorOccurred();
  3161. return false;
  3162. }
  3163. return true;
  3164. }
  3165. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  3166. cmExecutionStatus& status)
  3167. {
  3168. struct Arguments : public ArgumentParser::ParseResult
  3169. {
  3170. std::string Input;
  3171. bool Verbose = false;
  3172. bool ListOnly = false;
  3173. std::string Destination;
  3174. ArgumentParser::MaybeEmpty<std::vector<std::string>> Patterns;
  3175. bool Touch = false;
  3176. };
  3177. static auto const parser = cmArgumentParser<Arguments>{}
  3178. .Bind("INPUT"_s, &Arguments::Input)
  3179. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3180. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  3181. .Bind("DESTINATION"_s, &Arguments::Destination)
  3182. .Bind("PATTERNS"_s, &Arguments::Patterns)
  3183. .Bind("TOUCH"_s, &Arguments::Touch);
  3184. std::vector<std::string> unrecognizedArguments;
  3185. auto parsedArgs =
  3186. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3187. auto argIt = unrecognizedArguments.begin();
  3188. if (argIt != unrecognizedArguments.end()) {
  3189. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3190. cmSystemTools::SetFatalErrorOccurred();
  3191. return false;
  3192. }
  3193. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3194. cmSystemTools::SetFatalErrorOccurred();
  3195. return true;
  3196. }
  3197. std::string inFile = parsedArgs.Input;
  3198. if (parsedArgs.ListOnly) {
  3199. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3200. parsedArgs.Verbose)) {
  3201. status.SetError(cmStrCat("failed to list: ", inFile));
  3202. cmSystemTools::SetFatalErrorOccurred();
  3203. return false;
  3204. }
  3205. } else {
  3206. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3207. if (!parsedArgs.Destination.empty()) {
  3208. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3209. destDir = parsedArgs.Destination;
  3210. } else {
  3211. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  3212. }
  3213. if (!cmSystemTools::MakeDirectory(destDir)) {
  3214. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3215. cmSystemTools::SetFatalErrorOccurred();
  3216. return false;
  3217. }
  3218. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3219. inFile =
  3220. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  3221. }
  3222. }
  3223. cmWorkingDirectory workdir(destDir);
  3224. if (workdir.Failed()) {
  3225. status.SetError(
  3226. cmStrCat("failed to change working directory to: ", destDir));
  3227. cmSystemTools::SetFatalErrorOccurred();
  3228. return false;
  3229. }
  3230. if (!cmSystemTools::ExtractTar(
  3231. inFile, parsedArgs.Patterns,
  3232. parsedArgs.Touch ? cmSystemTools::cmTarExtractTimestamps::No
  3233. : cmSystemTools::cmTarExtractTimestamps::Yes,
  3234. parsedArgs.Verbose)) {
  3235. status.SetError(cmStrCat("failed to extract: ", inFile));
  3236. cmSystemTools::SetFatalErrorOccurred();
  3237. return false;
  3238. }
  3239. }
  3240. return true;
  3241. }
  3242. bool ValidateAndConvertPermissions(
  3243. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> const&
  3244. permissions,
  3245. mode_t& perms, cmExecutionStatus& status)
  3246. {
  3247. if (!permissions) {
  3248. return true;
  3249. }
  3250. for (const auto& i : *permissions) {
  3251. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3252. status.SetError(i + " is an invalid permission specifier");
  3253. cmSystemTools::SetFatalErrorOccurred();
  3254. return false;
  3255. }
  3256. }
  3257. return true;
  3258. }
  3259. bool SetPermissions(const std::string& filename, const mode_t& perms,
  3260. cmExecutionStatus& status)
  3261. {
  3262. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3263. status.SetError("Failed to set permissions for " + filename);
  3264. cmSystemTools::SetFatalErrorOccurred();
  3265. return false;
  3266. }
  3267. return true;
  3268. }
  3269. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3270. cmExecutionStatus& status)
  3271. {
  3272. mode_t perms = 0;
  3273. mode_t fperms = 0;
  3274. mode_t dperms = 0;
  3275. cmsys::Glob globber;
  3276. globber.SetRecurse(recurse);
  3277. globber.SetRecurseListDirs(recurse);
  3278. struct Arguments : public ArgumentParser::ParseResult
  3279. {
  3280. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3281. Permissions;
  3282. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3283. FilePermissions;
  3284. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3285. DirectoryPermissions;
  3286. };
  3287. static auto const parser =
  3288. cmArgumentParser<Arguments>{}
  3289. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3290. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3291. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3292. std::vector<std::string> pathEntries;
  3293. Arguments parsedArgs =
  3294. parser.Parse(cmMakeRange(args).advance(1), &pathEntries);
  3295. // check validity of arguments
  3296. if (!parsedArgs.Permissions && !parsedArgs.FilePermissions &&
  3297. !parsedArgs.DirectoryPermissions) // no permissions given
  3298. {
  3299. status.SetError("No permissions given");
  3300. cmSystemTools::SetFatalErrorOccurred();
  3301. return false;
  3302. }
  3303. if (parsedArgs.Permissions && parsedArgs.FilePermissions &&
  3304. parsedArgs.DirectoryPermissions) // all keywords are used
  3305. {
  3306. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3307. "DIRECTORY_PERMISSIONS from the invocation");
  3308. cmSystemTools::SetFatalErrorOccurred();
  3309. return false;
  3310. }
  3311. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3312. cmSystemTools::SetFatalErrorOccurred();
  3313. return true;
  3314. }
  3315. // validate permissions
  3316. bool validatePermissions =
  3317. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3318. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3319. status) &&
  3320. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3321. status);
  3322. if (!validatePermissions) {
  3323. return false;
  3324. }
  3325. std::vector<std::string> allPathEntries;
  3326. if (recurse) {
  3327. std::vector<std::string> tempPathEntries;
  3328. for (const auto& i : pathEntries) {
  3329. if (cmSystemTools::FileIsDirectory(i)) {
  3330. globber.FindFiles(i + "/*");
  3331. tempPathEntries = globber.GetFiles();
  3332. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3333. tempPathEntries.end());
  3334. allPathEntries.emplace_back(i);
  3335. } else {
  3336. allPathEntries.emplace_back(i); // We validate path entries below
  3337. }
  3338. }
  3339. } else {
  3340. allPathEntries = std::move(pathEntries);
  3341. }
  3342. // chmod
  3343. for (const auto& i : allPathEntries) {
  3344. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3345. status.SetError(cmStrCat("does not exist:\n ", i));
  3346. cmSystemTools::SetFatalErrorOccurred();
  3347. return false;
  3348. }
  3349. if (cmSystemTools::FileExists(i, true)) {
  3350. bool success = true;
  3351. const mode_t& filePermissions =
  3352. parsedArgs.FilePermissions ? fperms : perms;
  3353. if (filePermissions) {
  3354. success = SetPermissions(i, filePermissions, status);
  3355. }
  3356. if (!success) {
  3357. return false;
  3358. }
  3359. }
  3360. else if (cmSystemTools::FileIsDirectory(i)) {
  3361. bool success = true;
  3362. const mode_t& directoryPermissions =
  3363. parsedArgs.DirectoryPermissions ? dperms : perms;
  3364. if (directoryPermissions) {
  3365. success = SetPermissions(i, directoryPermissions, status);
  3366. }
  3367. if (!success) {
  3368. return false;
  3369. }
  3370. }
  3371. }
  3372. return true;
  3373. }
  3374. bool HandleChmodCommand(std::vector<std::string> const& args,
  3375. cmExecutionStatus& status)
  3376. {
  3377. return HandleChmodCommandImpl(args, false, status);
  3378. }
  3379. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3380. cmExecutionStatus& status)
  3381. {
  3382. return HandleChmodCommandImpl(args, true, status);
  3383. }
  3384. } // namespace
  3385. bool cmFileCommand(std::vector<std::string> const& args,
  3386. cmExecutionStatus& status)
  3387. {
  3388. if (args.size() < 2) {
  3389. status.SetError("must be called with at least two arguments.");
  3390. return false;
  3391. }
  3392. static cmSubcommandTable const subcommand{
  3393. { "WRITE"_s, HandleWriteCommand },
  3394. { "APPEND"_s, HandleAppendCommand },
  3395. { "DOWNLOAD"_s, HandleDownloadCommand },
  3396. { "UPLOAD"_s, HandleUploadCommand },
  3397. { "READ"_s, HandleReadCommand },
  3398. { "MD5"_s, HandleHashCommand },
  3399. { "SHA1"_s, HandleHashCommand },
  3400. { "SHA224"_s, HandleHashCommand },
  3401. { "SHA256"_s, HandleHashCommand },
  3402. { "SHA384"_s, HandleHashCommand },
  3403. { "SHA512"_s, HandleHashCommand },
  3404. { "SHA3_224"_s, HandleHashCommand },
  3405. { "SHA3_256"_s, HandleHashCommand },
  3406. { "SHA3_384"_s, HandleHashCommand },
  3407. { "SHA3_512"_s, HandleHashCommand },
  3408. { "STRINGS"_s, HandleStringsCommand },
  3409. { "GLOB"_s, HandleGlobCommand },
  3410. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3411. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3412. { "RENAME"_s, HandleRename },
  3413. { "COPY_FILE"_s, HandleCopyFile },
  3414. { "REMOVE"_s, HandleRemove },
  3415. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3416. { "COPY"_s, HandleCopyCommand },
  3417. { "INSTALL"_s, HandleInstallCommand },
  3418. { "DIFFERENT"_s, HandleDifferentCommand },
  3419. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3420. { "CHRPATH"_s, HandleRPathChangeCommand },
  3421. { "RPATH_SET"_s, HandleRPathSetCommand },
  3422. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3423. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3424. { "READ_ELF"_s, HandleReadElfCommand },
  3425. { "REAL_PATH"_s, HandleRealPathCommand },
  3426. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3427. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3428. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3429. { "TOUCH"_s, HandleTouchCommand },
  3430. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3431. { "TIMESTAMP"_s, HandleTimestampCommand },
  3432. { "GENERATE"_s, HandleGenerateCommand },
  3433. { "LOCK"_s, HandleLockCommand },
  3434. { "SIZE"_s, HandleSizeCommand },
  3435. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3436. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3437. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3438. { "CONFIGURE"_s, HandleConfigureCommand },
  3439. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3440. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3441. { "CHMOD"_s, HandleChmodCommand },
  3442. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3443. };
  3444. return subcommand(args[0], args, status);
  3445. }