cmFileCommand.cxx 118 KB

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