cmFileCommand.cxx 119 KB

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