cmFileCommand.cxx 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780
  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. class cURLProgressHelper
  1491. {
  1492. public:
  1493. cURLProgressHelper(cmMakefile* mf, const char* text)
  1494. : Makefile(mf)
  1495. , Text(text)
  1496. {
  1497. }
  1498. bool UpdatePercentage(double value, double total, std::string& status)
  1499. {
  1500. long OldPercentage = this->CurrentPercentage;
  1501. if (total > 0.0) {
  1502. this->CurrentPercentage = std::lround(value / total * 100.0);
  1503. if (this->CurrentPercentage > 100) {
  1504. // Avoid extra progress reports for unexpected data beyond total.
  1505. this->CurrentPercentage = 100;
  1506. }
  1507. }
  1508. bool updated = (OldPercentage != this->CurrentPercentage);
  1509. if (updated) {
  1510. status =
  1511. cmStrCat("[", this->Text, " ", this->CurrentPercentage, "% complete]");
  1512. }
  1513. return updated;
  1514. }
  1515. cmMakefile* GetMakefile() { return this->Makefile; }
  1516. private:
  1517. long CurrentPercentage = -1;
  1518. cmMakefile* Makefile;
  1519. std::string Text;
  1520. };
  1521. int cmFileDownloadProgressCallback(void* clientp, double dltotal, double dlnow,
  1522. double ultotal, double ulnow)
  1523. {
  1524. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1525. static_cast<void>(ultotal);
  1526. static_cast<void>(ulnow);
  1527. std::string status;
  1528. if (helper->UpdatePercentage(dlnow, dltotal, status)) {
  1529. cmMakefile* mf = helper->GetMakefile();
  1530. mf->DisplayStatus(status, -1);
  1531. }
  1532. return 0;
  1533. }
  1534. int cmFileUploadProgressCallback(void* clientp, double dltotal, double dlnow,
  1535. double ultotal, double ulnow)
  1536. {
  1537. cURLProgressHelper* helper = reinterpret_cast<cURLProgressHelper*>(clientp);
  1538. static_cast<void>(dltotal);
  1539. static_cast<void>(dlnow);
  1540. std::string status;
  1541. if (helper->UpdatePercentage(ulnow, ultotal, status)) {
  1542. cmMakefile* mf = helper->GetMakefile();
  1543. mf->DisplayStatus(status, -1);
  1544. }
  1545. return 0;
  1546. }
  1547. class cURLEasyGuard
  1548. {
  1549. public:
  1550. cURLEasyGuard(CURL* easy)
  1551. : Easy(easy)
  1552. {
  1553. }
  1554. ~cURLEasyGuard()
  1555. {
  1556. if (this->Easy) {
  1557. ::curl_easy_cleanup(this->Easy);
  1558. }
  1559. }
  1560. cURLEasyGuard(const cURLEasyGuard&) = delete;
  1561. cURLEasyGuard& operator=(const cURLEasyGuard&) = delete;
  1562. void release() { this->Easy = nullptr; }
  1563. private:
  1564. ::CURL* Easy;
  1565. };
  1566. #endif
  1567. #define check_curl_result(result, errstr) \
  1568. do { \
  1569. if (result != CURLE_OK) { \
  1570. std::string e(errstr); \
  1571. e += ::curl_easy_strerror(result); \
  1572. status.SetError(e); \
  1573. return false; \
  1574. } \
  1575. } while (false)
  1576. bool HandleDownloadCommand(std::vector<std::string> const& args,
  1577. cmExecutionStatus& status)
  1578. {
  1579. #if !defined(CMAKE_BOOTSTRAP)
  1580. auto i = args.begin();
  1581. if (args.size() < 2) {
  1582. status.SetError("DOWNLOAD must be called with at least two arguments.");
  1583. return false;
  1584. }
  1585. ++i; // Get rid of subcommand
  1586. std::string url = *i;
  1587. ++i;
  1588. std::string file;
  1589. long timeout = 0;
  1590. long inactivity_timeout = 0;
  1591. std::string logVar;
  1592. std::string statusVar;
  1593. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1594. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1595. std::string netrc_level =
  1596. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1597. std::string netrc_file =
  1598. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1599. std::string expectedHash;
  1600. std::string hashMatchMSG;
  1601. std::unique_ptr<cmCryptoHash> hash;
  1602. bool showProgress = false;
  1603. std::string userpwd;
  1604. std::vector<std::string> curl_headers;
  1605. std::vector<std::pair<std::string, cm::optional<std::string>>> curl_ranges;
  1606. while (i != args.end()) {
  1607. if (*i == "TIMEOUT") {
  1608. ++i;
  1609. if (i != args.end()) {
  1610. timeout = atol(i->c_str());
  1611. } else {
  1612. status.SetError("DOWNLOAD missing time for TIMEOUT.");
  1613. return false;
  1614. }
  1615. } else if (*i == "INACTIVITY_TIMEOUT") {
  1616. ++i;
  1617. if (i != args.end()) {
  1618. inactivity_timeout = atol(i->c_str());
  1619. } else {
  1620. status.SetError("DOWNLOAD missing time for INACTIVITY_TIMEOUT.");
  1621. return false;
  1622. }
  1623. } else if (*i == "LOG") {
  1624. ++i;
  1625. if (i == args.end()) {
  1626. status.SetError("DOWNLOAD missing VAR for LOG.");
  1627. return false;
  1628. }
  1629. logVar = *i;
  1630. } else if (*i == "STATUS") {
  1631. ++i;
  1632. if (i == args.end()) {
  1633. status.SetError("DOWNLOAD missing VAR for STATUS.");
  1634. return false;
  1635. }
  1636. statusVar = *i;
  1637. } else if (*i == "TLS_VERIFY") {
  1638. ++i;
  1639. if (i != args.end()) {
  1640. tls_verify = cmIsOn(*i);
  1641. } else {
  1642. status.SetError("DOWNLOAD missing bool value for TLS_VERIFY.");
  1643. return false;
  1644. }
  1645. } else if (*i == "TLS_CAINFO") {
  1646. ++i;
  1647. if (i != args.end()) {
  1648. cainfo = cmValue(*i);
  1649. } else {
  1650. status.SetError("DOWNLOAD missing file value for TLS_CAINFO.");
  1651. return false;
  1652. }
  1653. } else if (*i == "NETRC_FILE") {
  1654. ++i;
  1655. if (i != args.end()) {
  1656. netrc_file = *i;
  1657. } else {
  1658. status.SetError("DOWNLOAD missing file value for NETRC_FILE.");
  1659. return false;
  1660. }
  1661. } else if (*i == "NETRC") {
  1662. ++i;
  1663. if (i != args.end()) {
  1664. netrc_level = *i;
  1665. } else {
  1666. status.SetError("DOWNLOAD missing level value for NETRC.");
  1667. return false;
  1668. }
  1669. } else if (*i == "EXPECTED_MD5") {
  1670. ++i;
  1671. if (i == args.end()) {
  1672. status.SetError("DOWNLOAD missing sum value for EXPECTED_MD5.");
  1673. return false;
  1674. }
  1675. hash = cm::make_unique<cmCryptoHash>(cmCryptoHash::AlgoMD5);
  1676. hashMatchMSG = "MD5 sum";
  1677. expectedHash = cmSystemTools::LowerCase(*i);
  1678. } else if (*i == "SHOW_PROGRESS") {
  1679. showProgress = true;
  1680. } else if (*i == "EXPECTED_HASH") {
  1681. ++i;
  1682. if (i == args.end()) {
  1683. status.SetError("DOWNLOAD missing ALGO=value for EXPECTED_HASH.");
  1684. return false;
  1685. }
  1686. std::string::size_type pos = i->find("=");
  1687. if (pos == std::string::npos) {
  1688. std::string err =
  1689. cmStrCat("DOWNLOAD EXPECTED_HASH expects ALGO=value but got: ", *i);
  1690. status.SetError(err);
  1691. return false;
  1692. }
  1693. std::string algo = i->substr(0, pos);
  1694. expectedHash = cmSystemTools::LowerCase(i->substr(pos + 1));
  1695. hash = cmCryptoHash::New(algo);
  1696. if (!hash) {
  1697. std::string err =
  1698. cmStrCat("DOWNLOAD EXPECTED_HASH given unknown ALGO: ", algo);
  1699. status.SetError(err);
  1700. return false;
  1701. }
  1702. hashMatchMSG = algo + " hash";
  1703. } else if (*i == "USERPWD") {
  1704. ++i;
  1705. if (i == args.end()) {
  1706. status.SetError("DOWNLOAD missing string for USERPWD.");
  1707. return false;
  1708. }
  1709. userpwd = *i;
  1710. } else if (*i == "HTTPHEADER") {
  1711. ++i;
  1712. if (i == args.end()) {
  1713. status.SetError("DOWNLOAD missing string for HTTPHEADER.");
  1714. return false;
  1715. }
  1716. curl_headers.push_back(*i);
  1717. } else if (*i == "RANGE_START") {
  1718. ++i;
  1719. if (i == args.end()) {
  1720. status.SetError("DOWNLOAD missing value for RANGE_START.");
  1721. return false;
  1722. }
  1723. curl_ranges.emplace_back(*i, cm::nullopt);
  1724. } else if (*i == "RANGE_END") {
  1725. ++i;
  1726. if (curl_ranges.empty()) {
  1727. curl_ranges.emplace_back("0", *i);
  1728. } else {
  1729. auto& last_range = curl_ranges.back();
  1730. if (!last_range.second.has_value()) {
  1731. last_range.second = *i;
  1732. } else {
  1733. status.SetError("Multiple RANGE_END values is provided without "
  1734. "the corresponding RANGE_START.");
  1735. return false;
  1736. }
  1737. }
  1738. } else if (file.empty()) {
  1739. file = *i;
  1740. } else {
  1741. // Do not return error for compatibility reason.
  1742. std::string err = cmStrCat("Unexpected argument: ", *i);
  1743. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  1744. }
  1745. ++i;
  1746. }
  1747. // Can't calculate hash if we don't save the file.
  1748. // TODO Incrementally calculate hash in the write callback as the file is
  1749. // being downloaded so this check can be relaxed.
  1750. if (file.empty() && hash) {
  1751. status.SetError("DOWNLOAD cannot calculate hash if file is not saved.");
  1752. return false;
  1753. }
  1754. // If file exists already, and caller specified an expected md5 or sha,
  1755. // and the existing file already has the expected hash, then simply
  1756. // return.
  1757. //
  1758. if (!file.empty() && cmSystemTools::FileExists(file) && hash.get()) {
  1759. std::string msg;
  1760. std::string actualHash = hash->HashFile(file);
  1761. if (actualHash == expectedHash) {
  1762. msg = cmStrCat("skipping download as file already exists with expected ",
  1763. hashMatchMSG, '"');
  1764. if (!statusVar.empty()) {
  1765. status.GetMakefile().AddDefinition(statusVar, cmStrCat(0, ";\"", msg));
  1766. }
  1767. return true;
  1768. }
  1769. }
  1770. // Make sure parent directory exists so we can write to the file
  1771. // as we receive downloaded bits from curl...
  1772. //
  1773. if (!file.empty()) {
  1774. std::string dir = cmSystemTools::GetFilenamePath(file);
  1775. if (!dir.empty() && !cmSystemTools::FileExists(dir) &&
  1776. !cmSystemTools::MakeDirectory(dir)) {
  1777. std::string errstring = "DOWNLOAD error: cannot create directory '" +
  1778. dir +
  1779. "' - Specify file by full path name and verify that you "
  1780. "have directory creation and file write privileges.";
  1781. status.SetError(errstring);
  1782. return false;
  1783. }
  1784. }
  1785. cmsys::ofstream fout;
  1786. if (!file.empty()) {
  1787. fout.open(file.c_str(), std::ios::binary);
  1788. if (!fout) {
  1789. status.SetError("DOWNLOAD cannot open file for write.");
  1790. return false;
  1791. }
  1792. }
  1793. url = cmCurlFixFileURL(url);
  1794. ::CURL* curl;
  1795. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  1796. curl = ::curl_easy_init();
  1797. if (!curl) {
  1798. status.SetError("DOWNLOAD error initializing curl.");
  1799. return false;
  1800. }
  1801. cURLEasyGuard g_curl(curl);
  1802. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1803. check_curl_result(res, "DOWNLOAD cannot set url: ");
  1804. // enable HTTP ERROR parsing
  1805. res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  1806. check_curl_result(res, "DOWNLOAD cannot set http failure option: ");
  1807. res = ::curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/" LIBCURL_VERSION);
  1808. check_curl_result(res, "DOWNLOAD cannot set user agent option: ");
  1809. res = ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToFileCallback);
  1810. check_curl_result(res, "DOWNLOAD cannot set write function: ");
  1811. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  1812. cmFileCommandCurlDebugCallback);
  1813. check_curl_result(res, "DOWNLOAD cannot set debug function: ");
  1814. // check to see if TLS verification is requested
  1815. if (tls_verify) {
  1816. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  1817. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify on: ");
  1818. } else {
  1819. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  1820. check_curl_result(res, "DOWNLOAD cannot set TLS/SSL Verify off: ");
  1821. }
  1822. for (const auto& range : curl_ranges) {
  1823. std::string curl_range = range.first + '-' +
  1824. (range.second.has_value() ? range.second.value() : "");
  1825. res = ::curl_easy_setopt(curl, CURLOPT_RANGE, curl_range.c_str());
  1826. check_curl_result(res, "DOWNLOAD cannot set range: ");
  1827. }
  1828. // check to see if a CAINFO file has been specified
  1829. // command arg comes first
  1830. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  1831. if (!cainfo_err.empty()) {
  1832. status.SetError(cainfo_err);
  1833. return false;
  1834. }
  1835. // check to see if netrc parameters have been specified
  1836. // local command args takes precedence over CMAKE_NETRC*
  1837. netrc_level = cmSystemTools::UpperCase(netrc_level);
  1838. std::string const& netrc_option_err =
  1839. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  1840. if (!netrc_option_err.empty()) {
  1841. status.SetError(netrc_option_err);
  1842. return false;
  1843. }
  1844. cmFileCommandVectorOfChar chunkDebug;
  1845. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA,
  1846. file.empty() ? nullptr : &fout);
  1847. check_curl_result(res, "DOWNLOAD cannot set write data: ");
  1848. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  1849. check_curl_result(res, "DOWNLOAD cannot set debug data: ");
  1850. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1851. check_curl_result(res, "DOWNLOAD cannot set follow-redirect option: ");
  1852. if (!logVar.empty()) {
  1853. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1854. check_curl_result(res, "DOWNLOAD cannot set verbose: ");
  1855. }
  1856. if (timeout > 0) {
  1857. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1858. check_curl_result(res, "DOWNLOAD cannot set timeout: ");
  1859. }
  1860. if (inactivity_timeout > 0) {
  1861. // Give up if there is no progress for a long time.
  1862. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  1863. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  1864. }
  1865. // Need the progress helper's scope to last through the duration of
  1866. // the curl_easy_perform call... so this object is declared at function
  1867. // scope intentionally, rather than inside the "if(showProgress)"
  1868. // block...
  1869. //
  1870. cURLProgressHelper helper(&status.GetMakefile(), "download");
  1871. if (showProgress) {
  1872. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  1873. check_curl_result(res, "DOWNLOAD cannot set noprogress value: ");
  1874. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  1875. cmFileDownloadProgressCallback);
  1876. check_curl_result(res, "DOWNLOAD cannot set progress function: ");
  1877. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  1878. reinterpret_cast<void*>(&helper));
  1879. check_curl_result(res, "DOWNLOAD cannot set progress data: ");
  1880. }
  1881. if (!userpwd.empty()) {
  1882. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  1883. check_curl_result(res, "DOWNLOAD cannot set user password: ");
  1884. }
  1885. struct curl_slist* headers = nullptr;
  1886. for (std::string const& h : curl_headers) {
  1887. headers = ::curl_slist_append(headers, h.c_str());
  1888. }
  1889. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  1890. res = ::curl_easy_perform(curl);
  1891. ::curl_slist_free_all(headers);
  1892. /* always cleanup */
  1893. g_curl.release();
  1894. ::curl_easy_cleanup(curl);
  1895. if (!statusVar.empty()) {
  1896. status.GetMakefile().AddDefinition(
  1897. statusVar,
  1898. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  1899. }
  1900. ::curl_global_cleanup();
  1901. // Ensure requested curl logs are returned (especially in case of failure)
  1902. //
  1903. if (!logVar.empty()) {
  1904. chunkDebug.push_back(0);
  1905. status.GetMakefile().AddDefinition(logVar, chunkDebug.data());
  1906. }
  1907. // Explicitly flush/close so we can measure the md5 accurately.
  1908. //
  1909. if (!file.empty()) {
  1910. fout.flush();
  1911. fout.close();
  1912. }
  1913. // Verify MD5 sum if requested:
  1914. //
  1915. if (hash) {
  1916. if (res != CURLE_OK) {
  1917. status.SetError(cmStrCat(
  1918. "DOWNLOAD cannot compute hash on failed download\n"
  1919. " status: [",
  1920. static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\"]"));
  1921. return false;
  1922. }
  1923. std::string actualHash = hash->HashFile(file);
  1924. if (actualHash.empty()) {
  1925. status.SetError("DOWNLOAD cannot compute hash on downloaded file");
  1926. return false;
  1927. }
  1928. if (expectedHash != actualHash) {
  1929. if (!statusVar.empty() && res == 0) {
  1930. status.GetMakefile().AddDefinition(statusVar,
  1931. "1;HASH mismatch: "
  1932. "expected: " +
  1933. expectedHash +
  1934. " actual: " + actualHash);
  1935. }
  1936. status.SetError(cmStrCat("DOWNLOAD HASH mismatch\n"
  1937. " for file: [",
  1938. file,
  1939. "]\n"
  1940. " expected hash: [",
  1941. expectedHash,
  1942. "]\n"
  1943. " actual hash: [",
  1944. actualHash, "]\n"));
  1945. return false;
  1946. }
  1947. }
  1948. return true;
  1949. #else
  1950. status.SetError("DOWNLOAD not supported by bootstrap cmake.");
  1951. return false;
  1952. #endif
  1953. }
  1954. bool HandleUploadCommand(std::vector<std::string> const& args,
  1955. cmExecutionStatus& status)
  1956. {
  1957. #if !defined(CMAKE_BOOTSTRAP)
  1958. if (args.size() < 3) {
  1959. status.SetError("UPLOAD must be called with at least three arguments.");
  1960. return false;
  1961. }
  1962. auto i = args.begin();
  1963. ++i;
  1964. std::string filename = *i;
  1965. ++i;
  1966. std::string url = *i;
  1967. ++i;
  1968. long timeout = 0;
  1969. long inactivity_timeout = 0;
  1970. std::string logVar;
  1971. std::string statusVar;
  1972. bool showProgress = false;
  1973. bool tls_verify = status.GetMakefile().IsOn("CMAKE_TLS_VERIFY");
  1974. cmValue cainfo = status.GetMakefile().GetDefinition("CMAKE_TLS_CAINFO");
  1975. std::string userpwd;
  1976. std::string netrc_level =
  1977. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC");
  1978. std::string netrc_file =
  1979. status.GetMakefile().GetSafeDefinition("CMAKE_NETRC_FILE");
  1980. std::vector<std::string> curl_headers;
  1981. while (i != args.end()) {
  1982. if (*i == "TIMEOUT") {
  1983. ++i;
  1984. if (i != args.end()) {
  1985. timeout = atol(i->c_str());
  1986. } else {
  1987. status.SetError("UPLOAD missing time for TIMEOUT.");
  1988. return false;
  1989. }
  1990. } else if (*i == "INACTIVITY_TIMEOUT") {
  1991. ++i;
  1992. if (i != args.end()) {
  1993. inactivity_timeout = atol(i->c_str());
  1994. } else {
  1995. status.SetError("UPLOAD missing time for INACTIVITY_TIMEOUT.");
  1996. return false;
  1997. }
  1998. } else if (*i == "LOG") {
  1999. ++i;
  2000. if (i == args.end()) {
  2001. status.SetError("UPLOAD missing VAR for LOG.");
  2002. return false;
  2003. }
  2004. logVar = *i;
  2005. } else if (*i == "STATUS") {
  2006. ++i;
  2007. if (i == args.end()) {
  2008. status.SetError("UPLOAD missing VAR for STATUS.");
  2009. return false;
  2010. }
  2011. statusVar = *i;
  2012. } else if (*i == "SHOW_PROGRESS") {
  2013. showProgress = true;
  2014. } else if (*i == "TLS_VERIFY") {
  2015. ++i;
  2016. if (i != args.end()) {
  2017. tls_verify = cmIsOn(*i);
  2018. } else {
  2019. status.SetError("UPLOAD missing bool value for TLS_VERIFY.");
  2020. return false;
  2021. }
  2022. } else if (*i == "TLS_CAINFO") {
  2023. ++i;
  2024. if (i != args.end()) {
  2025. cainfo = cmValue(*i);
  2026. } else {
  2027. status.SetError("UPLOAD missing file value for TLS_CAINFO.");
  2028. return false;
  2029. }
  2030. } else if (*i == "NETRC_FILE") {
  2031. ++i;
  2032. if (i != args.end()) {
  2033. netrc_file = *i;
  2034. } else {
  2035. status.SetError("UPLOAD missing file value for NETRC_FILE.");
  2036. return false;
  2037. }
  2038. } else if (*i == "NETRC") {
  2039. ++i;
  2040. if (i != args.end()) {
  2041. netrc_level = *i;
  2042. } else {
  2043. status.SetError("UPLOAD missing level value for NETRC.");
  2044. return false;
  2045. }
  2046. } else if (*i == "USERPWD") {
  2047. ++i;
  2048. if (i == args.end()) {
  2049. status.SetError("UPLOAD missing string for USERPWD.");
  2050. return false;
  2051. }
  2052. userpwd = *i;
  2053. } else if (*i == "HTTPHEADER") {
  2054. ++i;
  2055. if (i == args.end()) {
  2056. status.SetError("UPLOAD missing string for HTTPHEADER.");
  2057. return false;
  2058. }
  2059. curl_headers.push_back(*i);
  2060. } else {
  2061. // Do not return error for compatibility reason.
  2062. std::string err = cmStrCat("Unexpected argument: ", *i);
  2063. status.GetMakefile().IssueMessage(MessageType::AUTHOR_WARNING, err);
  2064. }
  2065. ++i;
  2066. }
  2067. // Open file for reading:
  2068. //
  2069. FILE* fin = cmsys::SystemTools::Fopen(filename, "rb");
  2070. if (!fin) {
  2071. std::string errStr =
  2072. cmStrCat("UPLOAD cannot open file '", filename, "' for reading.");
  2073. status.SetError(errStr);
  2074. return false;
  2075. }
  2076. unsigned long file_size = cmsys::SystemTools::FileLength(filename);
  2077. url = cmCurlFixFileURL(url);
  2078. ::CURL* curl;
  2079. ::curl_global_init(CURL_GLOBAL_DEFAULT);
  2080. curl = ::curl_easy_init();
  2081. if (!curl) {
  2082. status.SetError("UPLOAD error initializing curl.");
  2083. fclose(fin);
  2084. return false;
  2085. }
  2086. cURLEasyGuard g_curl(curl);
  2087. // enable HTTP ERROR parsing
  2088. ::CURLcode res = ::curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  2089. check_curl_result(res, "UPLOAD cannot set fail on error flag: ");
  2090. // enable uploading
  2091. res = ::curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  2092. check_curl_result(res, "UPLOAD cannot set upload flag: ");
  2093. res = ::curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  2094. check_curl_result(res, "UPLOAD cannot set url: ");
  2095. res =
  2096. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cmWriteToMemoryCallback);
  2097. check_curl_result(res, "UPLOAD cannot set write function: ");
  2098. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  2099. cmFileCommandCurlDebugCallback);
  2100. check_curl_result(res, "UPLOAD cannot set debug function: ");
  2101. // check to see if TLS verification is requested
  2102. if (tls_verify) {
  2103. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1);
  2104. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify on: ");
  2105. } else {
  2106. res = ::curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  2107. check_curl_result(res, "UPLOAD cannot set TLS/SSL Verify off: ");
  2108. }
  2109. // check to see if a CAINFO file has been specified
  2110. // command arg comes first
  2111. std::string const& cainfo_err = cmCurlSetCAInfo(curl, cainfo);
  2112. if (!cainfo_err.empty()) {
  2113. status.SetError(cainfo_err);
  2114. return false;
  2115. }
  2116. cmFileCommandVectorOfChar chunkResponse;
  2117. cmFileCommandVectorOfChar chunkDebug;
  2118. res = ::curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunkResponse);
  2119. check_curl_result(res, "UPLOAD cannot set write data: ");
  2120. res = ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  2121. check_curl_result(res, "UPLOAD cannot set debug data: ");
  2122. res = ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  2123. check_curl_result(res, "UPLOAD cannot set follow-redirect option: ");
  2124. if (!logVar.empty()) {
  2125. res = ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  2126. check_curl_result(res, "UPLOAD cannot set verbose: ");
  2127. }
  2128. if (timeout > 0) {
  2129. res = ::curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2130. check_curl_result(res, "UPLOAD cannot set timeout: ");
  2131. }
  2132. if (inactivity_timeout > 0) {
  2133. // Give up if there is no progress for a long time.
  2134. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  2135. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, inactivity_timeout);
  2136. }
  2137. // Need the progress helper's scope to last through the duration of
  2138. // the curl_easy_perform call... so this object is declared at function
  2139. // scope intentionally, rather than inside the "if(showProgress)"
  2140. // block...
  2141. //
  2142. cURLProgressHelper helper(&status.GetMakefile(), "upload");
  2143. if (showProgress) {
  2144. res = ::curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0);
  2145. check_curl_result(res, "UPLOAD cannot set noprogress value: ");
  2146. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION,
  2147. cmFileUploadProgressCallback);
  2148. check_curl_result(res, "UPLOAD cannot set progress function: ");
  2149. res = ::curl_easy_setopt(curl, CURLOPT_PROGRESSDATA,
  2150. reinterpret_cast<void*>(&helper));
  2151. check_curl_result(res, "UPLOAD cannot set progress data: ");
  2152. }
  2153. // now specify which file to upload
  2154. res = ::curl_easy_setopt(curl, CURLOPT_INFILE, fin);
  2155. check_curl_result(res, "UPLOAD cannot set input file: ");
  2156. // and give the size of the upload (optional)
  2157. res =
  2158. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(file_size));
  2159. check_curl_result(res, "UPLOAD cannot set input file size: ");
  2160. if (!userpwd.empty()) {
  2161. res = ::curl_easy_setopt(curl, CURLOPT_USERPWD, userpwd.c_str());
  2162. check_curl_result(res, "UPLOAD cannot set user password: ");
  2163. }
  2164. // check to see if netrc parameters have been specified
  2165. // local command args takes precedence over CMAKE_NETRC*
  2166. netrc_level = cmSystemTools::UpperCase(netrc_level);
  2167. std::string const& netrc_option_err =
  2168. cmCurlSetNETRCOption(curl, netrc_level, netrc_file);
  2169. if (!netrc_option_err.empty()) {
  2170. status.SetError(netrc_option_err);
  2171. return false;
  2172. }
  2173. struct curl_slist* headers = nullptr;
  2174. for (std::string const& h : curl_headers) {
  2175. headers = ::curl_slist_append(headers, h.c_str());
  2176. }
  2177. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  2178. res = ::curl_easy_perform(curl);
  2179. ::curl_slist_free_all(headers);
  2180. /* always cleanup */
  2181. g_curl.release();
  2182. ::curl_easy_cleanup(curl);
  2183. if (!statusVar.empty()) {
  2184. status.GetMakefile().AddDefinition(
  2185. statusVar,
  2186. cmStrCat(static_cast<int>(res), ";\"", ::curl_easy_strerror(res), "\""));
  2187. }
  2188. ::curl_global_cleanup();
  2189. fclose(fin);
  2190. fin = nullptr;
  2191. if (!logVar.empty()) {
  2192. std::string log;
  2193. if (!chunkResponse.empty()) {
  2194. chunkResponse.push_back(0);
  2195. log += "Response:\n";
  2196. log += chunkResponse.data();
  2197. log += "\n";
  2198. }
  2199. if (!chunkDebug.empty()) {
  2200. chunkDebug.push_back(0);
  2201. log += "Debug:\n";
  2202. log += chunkDebug.data();
  2203. log += "\n";
  2204. }
  2205. status.GetMakefile().AddDefinition(logVar, log);
  2206. }
  2207. return true;
  2208. #else
  2209. status.SetError("UPLOAD not supported by bootstrap cmake.");
  2210. return false;
  2211. #endif
  2212. }
  2213. void AddEvaluationFile(const std::string& inputName,
  2214. const std::string& targetName,
  2215. const std::string& outputExpr,
  2216. const std::string& condition, bool inputIsContent,
  2217. const std::string& newLineCharacter, mode_t permissions,
  2218. cmExecutionStatus& status)
  2219. {
  2220. cmListFileBacktrace lfbt = status.GetMakefile().GetBacktrace();
  2221. cmGeneratorExpression outputGe(*status.GetMakefile().GetCMakeInstance(),
  2222. lfbt);
  2223. std::unique_ptr<cmCompiledGeneratorExpression> outputCge =
  2224. outputGe.Parse(outputExpr);
  2225. cmGeneratorExpression conditionGe(*status.GetMakefile().GetCMakeInstance(),
  2226. lfbt);
  2227. std::unique_ptr<cmCompiledGeneratorExpression> conditionCge =
  2228. conditionGe.Parse(condition);
  2229. status.GetMakefile().AddEvaluationFile(
  2230. inputName, targetName, std::move(outputCge), std::move(conditionCge),
  2231. newLineCharacter, permissions, inputIsContent);
  2232. }
  2233. bool HandleGenerateCommand(std::vector<std::string> const& args,
  2234. cmExecutionStatus& status)
  2235. {
  2236. if (args.size() < 5) {
  2237. status.SetError("Incorrect arguments to GENERATE subcommand.");
  2238. return false;
  2239. }
  2240. struct Arguments : public ArgumentParser::ParseResult
  2241. {
  2242. cm::optional<std::string> Output;
  2243. cm::optional<std::string> Input;
  2244. cm::optional<std::string> Content;
  2245. cm::optional<std::string> Condition;
  2246. cm::optional<std::string> Target;
  2247. cm::optional<std::string> NewLineStyle;
  2248. bool NoSourcePermissions = false;
  2249. bool UseSourcePermissions = false;
  2250. ArgumentParser::NonEmpty<std::vector<std::string>> FilePermissions;
  2251. std::vector<cm::string_view> ParsedKeywords;
  2252. };
  2253. static auto const parser =
  2254. cmArgumentParser<Arguments>{}
  2255. .Bind("OUTPUT"_s, &Arguments::Output)
  2256. .Bind("INPUT"_s, &Arguments::Input)
  2257. .Bind("CONTENT"_s, &Arguments::Content)
  2258. .Bind("CONDITION"_s, &Arguments::Condition)
  2259. .Bind("TARGET"_s, &Arguments::Target)
  2260. .Bind("NO_SOURCE_PERMISSIONS"_s, &Arguments::NoSourcePermissions)
  2261. .Bind("USE_SOURCE_PERMISSIONS"_s, &Arguments::UseSourcePermissions)
  2262. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  2263. .Bind("NEWLINE_STYLE"_s, &Arguments::NewLineStyle)
  2264. .BindParsedKeywords(&Arguments::ParsedKeywords);
  2265. std::vector<std::string> unparsedArguments;
  2266. Arguments const arguments =
  2267. parser.Parse(cmMakeRange(args).advance(1), &unparsedArguments);
  2268. if (arguments.MaybeReportError(status.GetMakefile())) {
  2269. return true;
  2270. }
  2271. if (!unparsedArguments.empty()) {
  2272. status.SetError("Unknown argument to GENERATE subcommand.");
  2273. return false;
  2274. }
  2275. if (!arguments.Output || arguments.ParsedKeywords[0] != "OUTPUT"_s) {
  2276. status.SetError("GENERATE requires OUTPUT as first option.");
  2277. return false;
  2278. }
  2279. std::string const& output = *arguments.Output;
  2280. if (!arguments.Input && !arguments.Content) {
  2281. status.SetError("GENERATE requires INPUT or CONTENT option.");
  2282. return false;
  2283. }
  2284. const bool inputIsContent = arguments.ParsedKeywords[1] == "CONTENT"_s;
  2285. if (!inputIsContent && arguments.ParsedKeywords[1] == "INPUT") {
  2286. status.SetError("Unknown argument to GENERATE subcommand.");
  2287. }
  2288. std::string const& input =
  2289. inputIsContent ? *arguments.Content : *arguments.Input;
  2290. if (arguments.Condition && arguments.Condition->empty()) {
  2291. status.SetError("CONDITION of sub-command GENERATE must not be empty "
  2292. "if specified.");
  2293. return false;
  2294. }
  2295. std::string const& condition =
  2296. arguments.Condition ? *arguments.Condition : std::string();
  2297. if (arguments.Target && arguments.Target->empty()) {
  2298. status.SetError("TARGET of sub-command GENERATE must not be empty "
  2299. "if specified.");
  2300. return false;
  2301. }
  2302. std::string const& target =
  2303. arguments.Target ? *arguments.Target : std::string();
  2304. cmNewLineStyle newLineStyle;
  2305. if (arguments.NewLineStyle) {
  2306. std::string errorMessage;
  2307. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2308. status.SetError(cmStrCat("GENERATE ", errorMessage));
  2309. return false;
  2310. }
  2311. }
  2312. if (arguments.NoSourcePermissions && arguments.UseSourcePermissions) {
  2313. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2314. "USE_SOURCE_PERMISSIONS. Only one option allowed.");
  2315. return false;
  2316. }
  2317. if (!arguments.FilePermissions.empty()) {
  2318. if (arguments.NoSourcePermissions) {
  2319. status.SetError("given both NO_SOURCE_PERMISSIONS and "
  2320. "FILE_PERMISSIONS. Only one option allowed.");
  2321. return false;
  2322. }
  2323. if (arguments.UseSourcePermissions) {
  2324. status.SetError("given both USE_SOURCE_PERMISSIONS and "
  2325. "FILE_PERMISSIONS. Only one option allowed.");
  2326. return false;
  2327. }
  2328. }
  2329. if (arguments.UseSourcePermissions) {
  2330. if (inputIsContent) {
  2331. status.SetError("given USE_SOURCE_PERMISSIONS without a file INPUT.");
  2332. return false;
  2333. }
  2334. }
  2335. mode_t permissions = 0;
  2336. if (arguments.NoSourcePermissions) {
  2337. permissions |= cmFSPermissions::mode_owner_read;
  2338. permissions |= cmFSPermissions::mode_owner_write;
  2339. permissions |= cmFSPermissions::mode_group_read;
  2340. permissions |= cmFSPermissions::mode_world_read;
  2341. }
  2342. if (!arguments.FilePermissions.empty()) {
  2343. std::vector<std::string> invalidOptions;
  2344. for (auto const& e : arguments.FilePermissions) {
  2345. if (!cmFSPermissions::stringToModeT(e, permissions)) {
  2346. invalidOptions.push_back(e);
  2347. }
  2348. }
  2349. if (!invalidOptions.empty()) {
  2350. std::ostringstream oss;
  2351. oss << "given invalid permission ";
  2352. for (auto i = 0u; i < invalidOptions.size(); i++) {
  2353. if (i == 0u) {
  2354. oss << "\"" << invalidOptions[i] << "\"";
  2355. } else {
  2356. oss << ",\"" << invalidOptions[i] << "\"";
  2357. }
  2358. }
  2359. oss << ".";
  2360. status.SetError(oss.str());
  2361. return false;
  2362. }
  2363. }
  2364. AddEvaluationFile(input, target, output, condition, inputIsContent,
  2365. newLineStyle.GetCharacters(), permissions, status);
  2366. return true;
  2367. }
  2368. bool HandleLockCommand(std::vector<std::string> const& args,
  2369. cmExecutionStatus& status)
  2370. {
  2371. #if !defined(CMAKE_BOOTSTRAP)
  2372. // Default values
  2373. bool directory = false;
  2374. bool release = false;
  2375. enum Guard
  2376. {
  2377. GUARD_FUNCTION,
  2378. GUARD_FILE,
  2379. GUARD_PROCESS
  2380. };
  2381. Guard guard = GUARD_PROCESS;
  2382. std::string resultVariable;
  2383. unsigned long timeout = static_cast<unsigned long>(-1);
  2384. // Parse arguments
  2385. if (args.size() < 2) {
  2386. status.GetMakefile().IssueMessage(
  2387. MessageType::FATAL_ERROR,
  2388. "sub-command LOCK requires at least two arguments.");
  2389. return false;
  2390. }
  2391. std::string path = args[1];
  2392. for (unsigned i = 2; i < args.size(); ++i) {
  2393. if (args[i] == "DIRECTORY") {
  2394. directory = true;
  2395. } else if (args[i] == "RELEASE") {
  2396. release = true;
  2397. } else if (args[i] == "GUARD") {
  2398. ++i;
  2399. const char* merr = "expected FUNCTION, FILE or PROCESS after GUARD";
  2400. if (i >= args.size()) {
  2401. status.GetMakefile().IssueMessage(MessageType::FATAL_ERROR, merr);
  2402. return false;
  2403. }
  2404. if (args[i] == "FUNCTION") {
  2405. guard = GUARD_FUNCTION;
  2406. } else if (args[i] == "FILE") {
  2407. guard = GUARD_FILE;
  2408. } else if (args[i] == "PROCESS") {
  2409. guard = GUARD_PROCESS;
  2410. } else {
  2411. status.GetMakefile().IssueMessage(
  2412. MessageType::FATAL_ERROR,
  2413. cmStrCat(merr, ", but got:\n \"", args[i], "\"."));
  2414. return false;
  2415. }
  2416. } else if (args[i] == "RESULT_VARIABLE") {
  2417. ++i;
  2418. if (i >= args.size()) {
  2419. status.GetMakefile().IssueMessage(
  2420. MessageType::FATAL_ERROR,
  2421. "expected variable name after RESULT_VARIABLE");
  2422. return false;
  2423. }
  2424. resultVariable = args[i];
  2425. } else if (args[i] == "TIMEOUT") {
  2426. ++i;
  2427. if (i >= args.size()) {
  2428. status.GetMakefile().IssueMessage(
  2429. MessageType::FATAL_ERROR, "expected timeout value after TIMEOUT");
  2430. return false;
  2431. }
  2432. long scanned;
  2433. if (!cmStrToLong(args[i], &scanned) || scanned < 0) {
  2434. status.GetMakefile().IssueMessage(
  2435. MessageType::FATAL_ERROR,
  2436. cmStrCat("TIMEOUT value \"", args[i],
  2437. "\" is not an unsigned integer."));
  2438. return false;
  2439. }
  2440. timeout = static_cast<unsigned long>(scanned);
  2441. } else {
  2442. status.GetMakefile().IssueMessage(
  2443. MessageType::FATAL_ERROR,
  2444. cmStrCat("expected DIRECTORY, RELEASE, GUARD, RESULT_VARIABLE or ",
  2445. "TIMEOUT\nbut got: \"", args[i], "\"."));
  2446. return false;
  2447. }
  2448. }
  2449. if (directory) {
  2450. path += "/cmake.lock";
  2451. }
  2452. // Unify path (remove '//', '/../', ...)
  2453. path = cmSystemTools::CollapseFullPath(
  2454. path, status.GetMakefile().GetCurrentSourceDirectory());
  2455. // Create file and directories if needed
  2456. std::string parentDir = cmSystemTools::GetParentDirectory(path);
  2457. if (!cmSystemTools::MakeDirectory(parentDir)) {
  2458. status.GetMakefile().IssueMessage(
  2459. MessageType::FATAL_ERROR,
  2460. cmStrCat("directory\n \"", parentDir,
  2461. "\"\ncreation failed (check permissions)."));
  2462. cmSystemTools::SetFatalErrorOccurred();
  2463. return false;
  2464. }
  2465. FILE* file = cmsys::SystemTools::Fopen(path, "w");
  2466. if (!file) {
  2467. status.GetMakefile().IssueMessage(
  2468. MessageType::FATAL_ERROR,
  2469. cmStrCat("file\n \"", path,
  2470. "\"\ncreation failed (check permissions)."));
  2471. cmSystemTools::SetFatalErrorOccurred();
  2472. return false;
  2473. }
  2474. fclose(file);
  2475. // Actual lock/unlock
  2476. cmFileLockPool& lockPool =
  2477. status.GetMakefile().GetGlobalGenerator()->GetFileLockPool();
  2478. cmFileLockResult fileLockResult(cmFileLockResult::MakeOk());
  2479. if (release) {
  2480. fileLockResult = lockPool.Release(path);
  2481. } else {
  2482. switch (guard) {
  2483. case GUARD_FUNCTION:
  2484. fileLockResult = lockPool.LockFunctionScope(path, timeout);
  2485. break;
  2486. case GUARD_FILE:
  2487. fileLockResult = lockPool.LockFileScope(path, timeout);
  2488. break;
  2489. case GUARD_PROCESS:
  2490. fileLockResult = lockPool.LockProcessScope(path, timeout);
  2491. break;
  2492. default:
  2493. cmSystemTools::SetFatalErrorOccurred();
  2494. return false;
  2495. }
  2496. }
  2497. const std::string result = fileLockResult.GetOutputMessage();
  2498. if (resultVariable.empty() && !fileLockResult.IsOk()) {
  2499. status.GetMakefile().IssueMessage(
  2500. MessageType::FATAL_ERROR,
  2501. cmStrCat("error locking file\n \"", path, "\"\n", result, "."));
  2502. cmSystemTools::SetFatalErrorOccurred();
  2503. return false;
  2504. }
  2505. if (!resultVariable.empty()) {
  2506. status.GetMakefile().AddDefinition(resultVariable, result);
  2507. }
  2508. return true;
  2509. #else
  2510. static_cast<void>(args);
  2511. status.SetError("sub-command LOCK not implemented in bootstrap cmake");
  2512. return false;
  2513. #endif
  2514. }
  2515. bool HandleTimestampCommand(std::vector<std::string> const& args,
  2516. cmExecutionStatus& status)
  2517. {
  2518. if (args.size() < 3) {
  2519. status.SetError("sub-command TIMESTAMP requires at least two arguments.");
  2520. return false;
  2521. }
  2522. if (args.size() > 5) {
  2523. status.SetError("sub-command TIMESTAMP takes at most four arguments.");
  2524. return false;
  2525. }
  2526. unsigned int argsIndex = 1;
  2527. std::string filename = args[argsIndex++];
  2528. if (!cmsys::SystemTools::FileIsFullPath(filename)) {
  2529. filename = cmStrCat(status.GetMakefile().GetCurrentSourceDirectory(), '/',
  2530. filename);
  2531. }
  2532. const std::string& outputVariable = args[argsIndex++];
  2533. std::string formatString;
  2534. if (args.size() > argsIndex && args[argsIndex] != "UTC") {
  2535. formatString = args[argsIndex++];
  2536. }
  2537. bool utcFlag = false;
  2538. if (args.size() > argsIndex) {
  2539. if (args[argsIndex] == "UTC") {
  2540. utcFlag = true;
  2541. } else {
  2542. std::string e = " TIMESTAMP sub-command does not recognize option " +
  2543. args[argsIndex] + ".";
  2544. status.SetError(e);
  2545. return false;
  2546. }
  2547. }
  2548. cmTimestamp timestamp;
  2549. std::string result =
  2550. timestamp.FileModificationTime(filename.c_str(), formatString, utcFlag);
  2551. status.GetMakefile().AddDefinition(outputVariable, result);
  2552. return true;
  2553. }
  2554. bool HandleSizeCommand(std::vector<std::string> const& args,
  2555. cmExecutionStatus& status)
  2556. {
  2557. if (args.size() != 3) {
  2558. status.SetError(
  2559. cmStrCat(args[0], " requires a file name and output variable"));
  2560. return false;
  2561. }
  2562. unsigned int argsIndex = 1;
  2563. const std::string& filename = args[argsIndex++];
  2564. const std::string& outputVariable = args[argsIndex++];
  2565. if (!cmSystemTools::FileExists(filename, true)) {
  2566. status.SetError(
  2567. cmStrCat("SIZE requested of path that is not readable:\n ", filename));
  2568. return false;
  2569. }
  2570. status.GetMakefile().AddDefinition(
  2571. outputVariable, std::to_string(cmSystemTools::FileLength(filename)));
  2572. return true;
  2573. }
  2574. bool HandleReadSymlinkCommand(std::vector<std::string> const& args,
  2575. cmExecutionStatus& status)
  2576. {
  2577. if (args.size() != 3) {
  2578. status.SetError(
  2579. cmStrCat(args[0], " requires a file name and output variable"));
  2580. return false;
  2581. }
  2582. const std::string& filename = args[1];
  2583. const std::string& outputVariable = args[2];
  2584. std::string result;
  2585. if (!cmSystemTools::ReadSymlink(filename, result)) {
  2586. status.SetError(cmStrCat(
  2587. "READ_SYMLINK requested of path that is not a symlink:\n ", filename));
  2588. return false;
  2589. }
  2590. status.GetMakefile().AddDefinition(outputVariable, result);
  2591. return true;
  2592. }
  2593. bool HandleCreateLinkCommand(std::vector<std::string> const& args,
  2594. cmExecutionStatus& status)
  2595. {
  2596. if (args.size() < 3) {
  2597. status.SetError("CREATE_LINK must be called with at least two additional "
  2598. "arguments");
  2599. return false;
  2600. }
  2601. std::string const& fileName = args[1];
  2602. std::string const& newFileName = args[2];
  2603. struct Arguments
  2604. {
  2605. std::string Result;
  2606. bool CopyOnError = false;
  2607. bool Symbolic = false;
  2608. };
  2609. static auto const parser =
  2610. cmArgumentParser<Arguments>{}
  2611. .Bind("RESULT"_s, &Arguments::Result)
  2612. .Bind("COPY_ON_ERROR"_s, &Arguments::CopyOnError)
  2613. .Bind("SYMBOLIC"_s, &Arguments::Symbolic);
  2614. std::vector<std::string> unconsumedArgs;
  2615. Arguments const arguments =
  2616. parser.Parse(cmMakeRange(args).advance(3), &unconsumedArgs);
  2617. if (!unconsumedArgs.empty()) {
  2618. status.SetError("unknown argument: \"" + unconsumedArgs.front() + '\"');
  2619. return false;
  2620. }
  2621. // The system error message generated in the operation.
  2622. std::string result;
  2623. // Check if the paths are distinct.
  2624. if (fileName == newFileName) {
  2625. result = "CREATE_LINK cannot use same file and newfile";
  2626. if (!arguments.Result.empty()) {
  2627. status.GetMakefile().AddDefinition(arguments.Result, result);
  2628. return true;
  2629. }
  2630. status.SetError(result);
  2631. return false;
  2632. }
  2633. // Hard link requires original file to exist.
  2634. if (!arguments.Symbolic && !cmSystemTools::FileExists(fileName)) {
  2635. result = "Cannot hard link \'" + fileName + "\' as it does not exist.";
  2636. if (!arguments.Result.empty()) {
  2637. status.GetMakefile().AddDefinition(arguments.Result, result);
  2638. return true;
  2639. }
  2640. status.SetError(result);
  2641. return false;
  2642. }
  2643. // Check if the new file already exists and remove it.
  2644. if ((cmSystemTools::FileExists(newFileName) ||
  2645. cmSystemTools::FileIsSymlink(newFileName)) &&
  2646. !cmSystemTools::RemoveFile(newFileName)) {
  2647. std::ostringstream e;
  2648. e << "Failed to create link '" << newFileName
  2649. << "' because existing path cannot be removed: "
  2650. << cmSystemTools::GetLastSystemError() << "\n";
  2651. if (!arguments.Result.empty()) {
  2652. status.GetMakefile().AddDefinition(arguments.Result, e.str());
  2653. return true;
  2654. }
  2655. status.SetError(e.str());
  2656. return false;
  2657. }
  2658. // Whether the operation completed successfully.
  2659. bool completed = false;
  2660. // Check if the command requires a symbolic link.
  2661. if (arguments.Symbolic) {
  2662. cmsys::Status linked =
  2663. cmSystemTools::CreateSymlinkQuietly(fileName, newFileName);
  2664. if (linked) {
  2665. completed = true;
  2666. } else {
  2667. result = cmStrCat("failed to create symbolic link '", newFileName,
  2668. "': ", linked.GetString());
  2669. }
  2670. } else {
  2671. cmsys::Status linked =
  2672. cmSystemTools::CreateLinkQuietly(fileName, newFileName);
  2673. if (linked) {
  2674. completed = true;
  2675. } else {
  2676. result = cmStrCat("failed to create link '", newFileName,
  2677. "': ", linked.GetString());
  2678. }
  2679. }
  2680. // Check if copy-on-error is enabled in the arguments.
  2681. if (!completed && arguments.CopyOnError) {
  2682. cmsys::Status copied =
  2683. cmsys::SystemTools::CopyFileAlways(fileName, newFileName);
  2684. if (copied) {
  2685. completed = true;
  2686. } else {
  2687. result = "Copy failed: " + copied.GetString();
  2688. }
  2689. }
  2690. // Check if the operation was successful.
  2691. if (completed) {
  2692. result = "0";
  2693. } else if (arguments.Result.empty()) {
  2694. // The operation failed and the result is not reported in a variable.
  2695. status.SetError(result);
  2696. return false;
  2697. }
  2698. if (!arguments.Result.empty()) {
  2699. status.GetMakefile().AddDefinition(arguments.Result, result);
  2700. }
  2701. return true;
  2702. }
  2703. bool HandleGetRuntimeDependenciesCommand(std::vector<std::string> const& args,
  2704. cmExecutionStatus& status)
  2705. {
  2706. std::string platform =
  2707. status.GetMakefile().GetSafeDefinition("CMAKE_HOST_SYSTEM_NAME");
  2708. if (!cmRuntimeDependencyArchive::PlatformSupportsRuntimeDependencies(
  2709. platform)) {
  2710. status.SetError(
  2711. cmStrCat("GET_RUNTIME_DEPENDENCIES is not supported on system \"",
  2712. platform, "\""));
  2713. cmSystemTools::SetFatalErrorOccurred();
  2714. return false;
  2715. }
  2716. if (status.GetMakefile().GetState()->GetMode() == cmState::Project) {
  2717. status.GetMakefile().IssueMessage(
  2718. MessageType::AUTHOR_WARNING,
  2719. "You have used file(GET_RUNTIME_DEPENDENCIES)"
  2720. " in project mode. This is probably not what "
  2721. "you intended to do. Instead, please consider"
  2722. " using it in an install(CODE) or "
  2723. "install(SCRIPT) command. For example:"
  2724. "\n install(CODE [["
  2725. "\n file(GET_RUNTIME_DEPENDENCIES"
  2726. "\n # ..."
  2727. "\n )"
  2728. "\n ]])");
  2729. }
  2730. struct Arguments : public ArgumentParser::ParseResult
  2731. {
  2732. std::string ResolvedDependenciesVar;
  2733. std::string UnresolvedDependenciesVar;
  2734. std::string ConflictingDependenciesPrefix;
  2735. std::string RPathPrefix;
  2736. std::string BundleExecutable;
  2737. ArgumentParser::MaybeEmpty<std::vector<std::string>> Executables;
  2738. ArgumentParser::MaybeEmpty<std::vector<std::string>> Libraries;
  2739. ArgumentParser::MaybeEmpty<std::vector<std::string>> Directories;
  2740. ArgumentParser::MaybeEmpty<std::vector<std::string>> Modules;
  2741. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreIncludeRegexes;
  2742. ArgumentParser::MaybeEmpty<std::vector<std::string>> PreExcludeRegexes;
  2743. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeRegexes;
  2744. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeRegexes;
  2745. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostIncludeFiles;
  2746. ArgumentParser::MaybeEmpty<std::vector<std::string>> PostExcludeFiles;
  2747. ArgumentParser::MaybeEmpty<std::vector<std::string>>
  2748. PostExcludeFilesStrict;
  2749. };
  2750. static auto const parser =
  2751. cmArgumentParser<Arguments>{}
  2752. .Bind("RESOLVED_DEPENDENCIES_VAR"_s, &Arguments::ResolvedDependenciesVar)
  2753. .Bind("UNRESOLVED_DEPENDENCIES_VAR"_s,
  2754. &Arguments::UnresolvedDependenciesVar)
  2755. .Bind("CONFLICTING_DEPENDENCIES_PREFIX"_s,
  2756. &Arguments::ConflictingDependenciesPrefix)
  2757. .Bind("RPATH_PREFIX"_s, &Arguments::RPathPrefix)
  2758. .Bind("BUNDLE_EXECUTABLE"_s, &Arguments::BundleExecutable)
  2759. .Bind("EXECUTABLES"_s, &Arguments::Executables)
  2760. .Bind("LIBRARIES"_s, &Arguments::Libraries)
  2761. .Bind("MODULES"_s, &Arguments::Modules)
  2762. .Bind("DIRECTORIES"_s, &Arguments::Directories)
  2763. .Bind("PRE_INCLUDE_REGEXES"_s, &Arguments::PreIncludeRegexes)
  2764. .Bind("PRE_EXCLUDE_REGEXES"_s, &Arguments::PreExcludeRegexes)
  2765. .Bind("POST_INCLUDE_REGEXES"_s, &Arguments::PostIncludeRegexes)
  2766. .Bind("POST_EXCLUDE_REGEXES"_s, &Arguments::PostExcludeRegexes)
  2767. .Bind("POST_INCLUDE_FILES"_s, &Arguments::PostIncludeFiles)
  2768. .Bind("POST_EXCLUDE_FILES"_s, &Arguments::PostExcludeFiles)
  2769. .Bind("POST_EXCLUDE_FILES_STRICT"_s, &Arguments::PostExcludeFilesStrict);
  2770. std::vector<std::string> unrecognizedArguments;
  2771. auto parsedArgs =
  2772. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2773. auto argIt = unrecognizedArguments.begin();
  2774. if (argIt != unrecognizedArguments.end()) {
  2775. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  2776. cmSystemTools::SetFatalErrorOccurred();
  2777. return false;
  2778. }
  2779. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2780. cmSystemTools::SetFatalErrorOccurred();
  2781. return true;
  2782. }
  2783. cmRuntimeDependencyArchive archive(
  2784. status, parsedArgs.Directories, parsedArgs.BundleExecutable,
  2785. parsedArgs.PreIncludeRegexes, parsedArgs.PreExcludeRegexes,
  2786. parsedArgs.PostIncludeRegexes, parsedArgs.PostExcludeRegexes,
  2787. std::move(parsedArgs.PostIncludeFiles),
  2788. std::move(parsedArgs.PostExcludeFiles),
  2789. std::move(parsedArgs.PostExcludeFilesStrict));
  2790. if (!archive.Prepare()) {
  2791. cmSystemTools::SetFatalErrorOccurred();
  2792. return false;
  2793. }
  2794. if (!archive.GetRuntimeDependencies(
  2795. parsedArgs.Executables, parsedArgs.Libraries, parsedArgs.Modules)) {
  2796. cmSystemTools::SetFatalErrorOccurred();
  2797. return false;
  2798. }
  2799. std::vector<std::string> deps;
  2800. std::vector<std::string> unresolvedDeps;
  2801. std::vector<std::string> conflictingDeps;
  2802. for (auto const& val : archive.GetResolvedPaths()) {
  2803. bool unique = true;
  2804. auto it = val.second.begin();
  2805. assert(it != val.second.end());
  2806. auto const& firstPath = *it;
  2807. while (++it != val.second.end()) {
  2808. if (!cmSystemTools::SameFile(firstPath, *it)) {
  2809. unique = false;
  2810. break;
  2811. }
  2812. }
  2813. if (unique) {
  2814. deps.push_back(firstPath);
  2815. if (!parsedArgs.RPathPrefix.empty()) {
  2816. status.GetMakefile().AddDefinition(
  2817. parsedArgs.RPathPrefix + "_" + firstPath,
  2818. cmJoin(archive.GetRPaths().at(firstPath), ";"));
  2819. }
  2820. } else if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2821. conflictingDeps.push_back(val.first);
  2822. std::vector<std::string> paths;
  2823. paths.insert(paths.begin(), val.second.begin(), val.second.end());
  2824. std::string varName =
  2825. parsedArgs.ConflictingDependenciesPrefix + "_" + val.first;
  2826. std::string pathsStr = cmJoin(paths, ";");
  2827. status.GetMakefile().AddDefinition(varName, pathsStr);
  2828. } else {
  2829. std::ostringstream e;
  2830. e << "Multiple conflicting paths found for " << val.first << ":";
  2831. for (auto const& path : val.second) {
  2832. e << "\n " << path;
  2833. }
  2834. status.SetError(e.str());
  2835. cmSystemTools::SetFatalErrorOccurred();
  2836. return false;
  2837. }
  2838. }
  2839. if (!archive.GetUnresolvedPaths().empty()) {
  2840. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2841. unresolvedDeps.insert(unresolvedDeps.begin(),
  2842. archive.GetUnresolvedPaths().begin(),
  2843. archive.GetUnresolvedPaths().end());
  2844. } else {
  2845. std::ostringstream e;
  2846. e << "Could not resolve runtime dependencies:";
  2847. for (auto const& path : archive.GetUnresolvedPaths()) {
  2848. e << "\n " << path;
  2849. }
  2850. status.SetError(e.str());
  2851. cmSystemTools::SetFatalErrorOccurred();
  2852. return false;
  2853. }
  2854. }
  2855. if (!parsedArgs.ResolvedDependenciesVar.empty()) {
  2856. std::string val = cmJoin(deps, ";");
  2857. status.GetMakefile().AddDefinition(parsedArgs.ResolvedDependenciesVar,
  2858. val);
  2859. }
  2860. if (!parsedArgs.UnresolvedDependenciesVar.empty()) {
  2861. std::string val = cmJoin(unresolvedDeps, ";");
  2862. status.GetMakefile().AddDefinition(parsedArgs.UnresolvedDependenciesVar,
  2863. val);
  2864. }
  2865. if (!parsedArgs.ConflictingDependenciesPrefix.empty()) {
  2866. std::string val = cmJoin(conflictingDeps, ";");
  2867. status.GetMakefile().AddDefinition(
  2868. parsedArgs.ConflictingDependenciesPrefix + "_FILENAMES", val);
  2869. }
  2870. return true;
  2871. }
  2872. bool HandleConfigureCommand(std::vector<std::string> const& args,
  2873. cmExecutionStatus& status)
  2874. {
  2875. struct Arguments : public ArgumentParser::ParseResult
  2876. {
  2877. cm::optional<std::string> Output;
  2878. cm::optional<std::string> Content;
  2879. bool EscapeQuotes = false;
  2880. bool AtOnly = false;
  2881. // "NEWLINE_STYLE" requires one value, but we use a custom check below.
  2882. ArgumentParser::Maybe<std::string> NewlineStyle;
  2883. };
  2884. static auto const parser =
  2885. cmArgumentParser<Arguments>{}
  2886. .Bind("OUTPUT"_s, &Arguments::Output)
  2887. .Bind("CONTENT"_s, &Arguments::Content)
  2888. .Bind("ESCAPE_QUOTES"_s, &Arguments::EscapeQuotes)
  2889. .Bind("@ONLY"_s, &Arguments::AtOnly)
  2890. .Bind("NEWLINE_STYLE"_s, &Arguments::NewlineStyle);
  2891. std::vector<std::string> unrecognizedArguments;
  2892. auto parsedArgs =
  2893. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  2894. auto argIt = unrecognizedArguments.begin();
  2895. if (argIt != unrecognizedArguments.end()) {
  2896. status.SetError(
  2897. cmStrCat("CONFIGURE Unrecognized argument: \"", *argIt, "\""));
  2898. cmSystemTools::SetFatalErrorOccurred();
  2899. return false;
  2900. }
  2901. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  2902. cmSystemTools::SetFatalErrorOccurred();
  2903. return true;
  2904. }
  2905. if (!parsedArgs.Output) {
  2906. status.SetError("CONFIGURE OUTPUT option is mandatory.");
  2907. cmSystemTools::SetFatalErrorOccurred();
  2908. return false;
  2909. }
  2910. if (!parsedArgs.Content) {
  2911. status.SetError("CONFIGURE CONTENT option is mandatory.");
  2912. cmSystemTools::SetFatalErrorOccurred();
  2913. return false;
  2914. }
  2915. std::string errorMessage;
  2916. cmNewLineStyle newLineStyle;
  2917. if (!newLineStyle.ReadFromArguments(args, errorMessage)) {
  2918. status.SetError(cmStrCat("CONFIGURE ", errorMessage));
  2919. return false;
  2920. }
  2921. // Check for generator expressions
  2922. std::string outputFile = cmSystemTools::CollapseFullPath(
  2923. *parsedArgs.Output, status.GetMakefile().GetCurrentBinaryDirectory());
  2924. std::string::size_type pos = outputFile.find_first_of("<>");
  2925. if (pos != std::string::npos) {
  2926. status.SetError(cmStrCat("CONFIGURE called with OUTPUT containing a \"",
  2927. outputFile[pos],
  2928. "\". This character is not allowed."));
  2929. return false;
  2930. }
  2931. cmMakefile& makeFile = status.GetMakefile();
  2932. if (!makeFile.CanIWriteThisFile(outputFile)) {
  2933. cmSystemTools::Error("Attempt to write file: " + outputFile +
  2934. " into a source directory.");
  2935. return false;
  2936. }
  2937. cmSystemTools::ConvertToUnixSlashes(outputFile);
  2938. // Re-generate if non-temporary outputs are missing.
  2939. // when we finalize the configuration we will remove all
  2940. // output files that now don't exist.
  2941. makeFile.AddCMakeOutputFile(outputFile);
  2942. // Create output directory
  2943. const std::string::size_type slashPos = outputFile.rfind('/');
  2944. if (slashPos != std::string::npos) {
  2945. const std::string path = outputFile.substr(0, slashPos);
  2946. cmSystemTools::MakeDirectory(path);
  2947. }
  2948. std::string newLineCharacters = "\n";
  2949. bool open_with_binary_flag = false;
  2950. if (newLineStyle.IsValid()) {
  2951. newLineCharacters = newLineStyle.GetCharacters();
  2952. open_with_binary_flag = true;
  2953. }
  2954. cmGeneratedFileStream fout;
  2955. fout.Open(outputFile, false, open_with_binary_flag);
  2956. if (!fout) {
  2957. cmSystemTools::Error("Could not open file for write in copy operation " +
  2958. outputFile);
  2959. cmSystemTools::ReportLastSystemError("");
  2960. return false;
  2961. }
  2962. fout.SetCopyIfDifferent(true);
  2963. // copy input to output and expand variables from input at the same time
  2964. std::stringstream sin(*parsedArgs.Content, std::ios::in);
  2965. std::string inLine;
  2966. std::string outLine;
  2967. bool hasNewLine = false;
  2968. while (cmSystemTools::GetLineFromStream(sin, inLine, &hasNewLine)) {
  2969. outLine.clear();
  2970. makeFile.ConfigureString(inLine, outLine, parsedArgs.AtOnly,
  2971. parsedArgs.EscapeQuotes);
  2972. fout << outLine;
  2973. if (hasNewLine || newLineStyle.IsValid()) {
  2974. fout << newLineCharacters;
  2975. }
  2976. }
  2977. // close file before attempting to copy
  2978. fout.close();
  2979. return true;
  2980. }
  2981. bool HandleArchiveCreateCommand(std::vector<std::string> const& args,
  2982. cmExecutionStatus& status)
  2983. {
  2984. struct Arguments : public ArgumentParser::ParseResult
  2985. {
  2986. std::string Output;
  2987. std::string Format;
  2988. std::string Compression;
  2989. std::string CompressionLevel;
  2990. // "MTIME" should require one value, but it has long been accidentally
  2991. // accepted without one and treated as if an empty value were given.
  2992. // Fixing this would require a policy.
  2993. ArgumentParser::Maybe<std::string> MTime;
  2994. bool Verbose = false;
  2995. // "PATHS" requires at least one value, but use a custom check below.
  2996. ArgumentParser::MaybeEmpty<std::vector<std::string>> Paths;
  2997. };
  2998. static auto const parser =
  2999. cmArgumentParser<Arguments>{}
  3000. .Bind("OUTPUT"_s, &Arguments::Output)
  3001. .Bind("FORMAT"_s, &Arguments::Format)
  3002. .Bind("COMPRESSION"_s, &Arguments::Compression)
  3003. .Bind("COMPRESSION_LEVEL"_s, &Arguments::CompressionLevel)
  3004. .Bind("MTIME"_s, &Arguments::MTime)
  3005. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3006. .Bind("PATHS"_s, &Arguments::Paths);
  3007. std::vector<std::string> unrecognizedArguments;
  3008. auto parsedArgs =
  3009. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3010. auto argIt = unrecognizedArguments.begin();
  3011. if (argIt != unrecognizedArguments.end()) {
  3012. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3013. cmSystemTools::SetFatalErrorOccurred();
  3014. return false;
  3015. }
  3016. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3017. cmSystemTools::SetFatalErrorOccurred();
  3018. return true;
  3019. }
  3020. const char* knownFormats[] = {
  3021. "7zip", "gnutar", "pax", "paxr", "raw", "zip"
  3022. };
  3023. if (!parsedArgs.Format.empty() &&
  3024. !cm::contains(knownFormats, parsedArgs.Format)) {
  3025. status.SetError(
  3026. cmStrCat("archive format ", parsedArgs.Format, " not supported"));
  3027. cmSystemTools::SetFatalErrorOccurred();
  3028. return false;
  3029. }
  3030. const char* zipFileFormats[] = { "7zip", "zip" };
  3031. if (!parsedArgs.Compression.empty() &&
  3032. cm::contains(zipFileFormats, parsedArgs.Format)) {
  3033. status.SetError(cmStrCat("archive format ", parsedArgs.Format,
  3034. " does not support COMPRESSION arguments"));
  3035. cmSystemTools::SetFatalErrorOccurred();
  3036. return false;
  3037. }
  3038. static std::map<std::string, cmSystemTools::cmTarCompression>
  3039. compressionTypeMap = { { "None", cmSystemTools::TarCompressNone },
  3040. { "BZip2", cmSystemTools::TarCompressBZip2 },
  3041. { "GZip", cmSystemTools::TarCompressGZip },
  3042. { "XZ", cmSystemTools::TarCompressXZ },
  3043. { "Zstd", cmSystemTools::TarCompressZstd } };
  3044. cmSystemTools::cmTarCompression compress = cmSystemTools::TarCompressNone;
  3045. auto typeIt = compressionTypeMap.find(parsedArgs.Compression);
  3046. if (typeIt != compressionTypeMap.end()) {
  3047. compress = typeIt->second;
  3048. } else if (!parsedArgs.Compression.empty()) {
  3049. status.SetError(cmStrCat("compression type ", parsedArgs.Compression,
  3050. " is not supported"));
  3051. cmSystemTools::SetFatalErrorOccurred();
  3052. return false;
  3053. }
  3054. int compressionLevel = 0;
  3055. int minCompressionLevel = 0;
  3056. int maxCompressionLevel = 9;
  3057. if (compress == cmSystemTools::TarCompressZstd) {
  3058. maxCompressionLevel = 19;
  3059. }
  3060. if (!parsedArgs.CompressionLevel.empty()) {
  3061. if (parsedArgs.CompressionLevel.size() != 1 &&
  3062. !std::isdigit(parsedArgs.CompressionLevel[0])) {
  3063. status.SetError(
  3064. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3065. parsedArgs.Compression, " should be in range ",
  3066. minCompressionLevel, " to ", maxCompressionLevel));
  3067. cmSystemTools::SetFatalErrorOccurred();
  3068. return false;
  3069. }
  3070. compressionLevel = std::stoi(parsedArgs.CompressionLevel);
  3071. if (compressionLevel < minCompressionLevel ||
  3072. compressionLevel > maxCompressionLevel) {
  3073. status.SetError(
  3074. cmStrCat("compression level ", parsedArgs.CompressionLevel, " for ",
  3075. parsedArgs.Compression, " should be in range ",
  3076. minCompressionLevel, " to ", maxCompressionLevel));
  3077. cmSystemTools::SetFatalErrorOccurred();
  3078. return false;
  3079. }
  3080. if (compress == cmSystemTools::TarCompressNone) {
  3081. status.SetError(cmStrCat("compression level is not supported for "
  3082. "compression \"None\"",
  3083. parsedArgs.Compression));
  3084. cmSystemTools::SetFatalErrorOccurred();
  3085. return false;
  3086. }
  3087. }
  3088. if (parsedArgs.Paths.empty()) {
  3089. status.SetError("ARCHIVE_CREATE requires a non-empty list of PATHS");
  3090. cmSystemTools::SetFatalErrorOccurred();
  3091. return false;
  3092. }
  3093. if (!cmSystemTools::CreateTar(parsedArgs.Output, parsedArgs.Paths, compress,
  3094. parsedArgs.Verbose, parsedArgs.MTime,
  3095. parsedArgs.Format, compressionLevel)) {
  3096. status.SetError(cmStrCat("failed to compress: ", parsedArgs.Output));
  3097. cmSystemTools::SetFatalErrorOccurred();
  3098. return false;
  3099. }
  3100. return true;
  3101. }
  3102. bool HandleArchiveExtractCommand(std::vector<std::string> const& args,
  3103. cmExecutionStatus& status)
  3104. {
  3105. struct Arguments : public ArgumentParser::ParseResult
  3106. {
  3107. std::string Input;
  3108. bool Verbose = false;
  3109. bool ListOnly = false;
  3110. std::string Destination;
  3111. ArgumentParser::MaybeEmpty<std::vector<std::string>> Patterns;
  3112. bool Touch = false;
  3113. };
  3114. static auto const parser = cmArgumentParser<Arguments>{}
  3115. .Bind("INPUT"_s, &Arguments::Input)
  3116. .Bind("VERBOSE"_s, &Arguments::Verbose)
  3117. .Bind("LIST_ONLY"_s, &Arguments::ListOnly)
  3118. .Bind("DESTINATION"_s, &Arguments::Destination)
  3119. .Bind("PATTERNS"_s, &Arguments::Patterns)
  3120. .Bind("TOUCH"_s, &Arguments::Touch);
  3121. std::vector<std::string> unrecognizedArguments;
  3122. auto parsedArgs =
  3123. parser.Parse(cmMakeRange(args).advance(1), &unrecognizedArguments);
  3124. auto argIt = unrecognizedArguments.begin();
  3125. if (argIt != unrecognizedArguments.end()) {
  3126. status.SetError(cmStrCat("Unrecognized argument: \"", *argIt, "\""));
  3127. cmSystemTools::SetFatalErrorOccurred();
  3128. return false;
  3129. }
  3130. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3131. cmSystemTools::SetFatalErrorOccurred();
  3132. return true;
  3133. }
  3134. std::string inFile = parsedArgs.Input;
  3135. if (parsedArgs.ListOnly) {
  3136. if (!cmSystemTools::ListTar(inFile, parsedArgs.Patterns,
  3137. parsedArgs.Verbose)) {
  3138. status.SetError(cmStrCat("failed to list: ", inFile));
  3139. cmSystemTools::SetFatalErrorOccurred();
  3140. return false;
  3141. }
  3142. } else {
  3143. std::string destDir = status.GetMakefile().GetCurrentBinaryDirectory();
  3144. if (!parsedArgs.Destination.empty()) {
  3145. if (cmSystemTools::FileIsFullPath(parsedArgs.Destination)) {
  3146. destDir = parsedArgs.Destination;
  3147. } else {
  3148. destDir = cmStrCat(destDir, "/", parsedArgs.Destination);
  3149. }
  3150. if (!cmSystemTools::MakeDirectory(destDir)) {
  3151. status.SetError(cmStrCat("failed to create directory: ", destDir));
  3152. cmSystemTools::SetFatalErrorOccurred();
  3153. return false;
  3154. }
  3155. if (!cmSystemTools::FileIsFullPath(inFile)) {
  3156. inFile =
  3157. cmStrCat(cmSystemTools::GetCurrentWorkingDirectory(), "/", inFile);
  3158. }
  3159. }
  3160. cmWorkingDirectory workdir(destDir);
  3161. if (workdir.Failed()) {
  3162. status.SetError(
  3163. cmStrCat("failed to change working directory to: ", destDir));
  3164. cmSystemTools::SetFatalErrorOccurred();
  3165. return false;
  3166. }
  3167. if (!cmSystemTools::ExtractTar(
  3168. inFile, parsedArgs.Patterns,
  3169. parsedArgs.Touch ? cmSystemTools::cmTarExtractTimestamps::No
  3170. : cmSystemTools::cmTarExtractTimestamps::Yes,
  3171. parsedArgs.Verbose)) {
  3172. status.SetError(cmStrCat("failed to extract: ", inFile));
  3173. cmSystemTools::SetFatalErrorOccurred();
  3174. return false;
  3175. }
  3176. }
  3177. return true;
  3178. }
  3179. bool ValidateAndConvertPermissions(
  3180. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>> const&
  3181. permissions,
  3182. mode_t& perms, cmExecutionStatus& status)
  3183. {
  3184. if (!permissions) {
  3185. return true;
  3186. }
  3187. for (const auto& i : *permissions) {
  3188. if (!cmFSPermissions::stringToModeT(i, perms)) {
  3189. status.SetError(i + " is an invalid permission specifier");
  3190. cmSystemTools::SetFatalErrorOccurred();
  3191. return false;
  3192. }
  3193. }
  3194. return true;
  3195. }
  3196. bool SetPermissions(const std::string& filename, const mode_t& perms,
  3197. cmExecutionStatus& status)
  3198. {
  3199. if (!cmSystemTools::SetPermissions(filename, perms)) {
  3200. status.SetError("Failed to set permissions for " + filename);
  3201. cmSystemTools::SetFatalErrorOccurred();
  3202. return false;
  3203. }
  3204. return true;
  3205. }
  3206. bool HandleChmodCommandImpl(std::vector<std::string> const& args, bool recurse,
  3207. cmExecutionStatus& status)
  3208. {
  3209. mode_t perms = 0;
  3210. mode_t fperms = 0;
  3211. mode_t dperms = 0;
  3212. cmsys::Glob globber;
  3213. globber.SetRecurse(recurse);
  3214. globber.SetRecurseListDirs(recurse);
  3215. struct Arguments : public ArgumentParser::ParseResult
  3216. {
  3217. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3218. Permissions;
  3219. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3220. FilePermissions;
  3221. cm::optional<ArgumentParser::NonEmpty<std::vector<std::string>>>
  3222. DirectoryPermissions;
  3223. };
  3224. static auto const parser =
  3225. cmArgumentParser<Arguments>{}
  3226. .Bind("PERMISSIONS"_s, &Arguments::Permissions)
  3227. .Bind("FILE_PERMISSIONS"_s, &Arguments::FilePermissions)
  3228. .Bind("DIRECTORY_PERMISSIONS"_s, &Arguments::DirectoryPermissions);
  3229. std::vector<std::string> pathEntries;
  3230. Arguments parsedArgs =
  3231. parser.Parse(cmMakeRange(args).advance(1), &pathEntries);
  3232. // check validity of arguments
  3233. if (!parsedArgs.Permissions && !parsedArgs.FilePermissions &&
  3234. !parsedArgs.DirectoryPermissions) // no permissions given
  3235. {
  3236. status.SetError("No permissions given");
  3237. cmSystemTools::SetFatalErrorOccurred();
  3238. return false;
  3239. }
  3240. if (parsedArgs.Permissions && parsedArgs.FilePermissions &&
  3241. parsedArgs.DirectoryPermissions) // all keywords are used
  3242. {
  3243. status.SetError("Remove either PERMISSIONS or FILE_PERMISSIONS or "
  3244. "DIRECTORY_PERMISSIONS from the invocation");
  3245. cmSystemTools::SetFatalErrorOccurred();
  3246. return false;
  3247. }
  3248. if (parsedArgs.MaybeReportError(status.GetMakefile())) {
  3249. cmSystemTools::SetFatalErrorOccurred();
  3250. return true;
  3251. }
  3252. // validate permissions
  3253. bool validatePermissions =
  3254. ValidateAndConvertPermissions(parsedArgs.Permissions, perms, status) &&
  3255. ValidateAndConvertPermissions(parsedArgs.FilePermissions, fperms,
  3256. status) &&
  3257. ValidateAndConvertPermissions(parsedArgs.DirectoryPermissions, dperms,
  3258. status);
  3259. if (!validatePermissions) {
  3260. return false;
  3261. }
  3262. std::vector<std::string> allPathEntries;
  3263. if (recurse) {
  3264. std::vector<std::string> tempPathEntries;
  3265. for (const auto& i : pathEntries) {
  3266. if (cmSystemTools::FileIsDirectory(i)) {
  3267. globber.FindFiles(i + "/*");
  3268. tempPathEntries = globber.GetFiles();
  3269. allPathEntries.insert(allPathEntries.end(), tempPathEntries.begin(),
  3270. tempPathEntries.end());
  3271. allPathEntries.emplace_back(i);
  3272. } else {
  3273. allPathEntries.emplace_back(i); // We validate path entries below
  3274. }
  3275. }
  3276. } else {
  3277. allPathEntries = std::move(pathEntries);
  3278. }
  3279. // chmod
  3280. for (const auto& i : allPathEntries) {
  3281. if (!(cmSystemTools::FileExists(i) || cmSystemTools::FileIsDirectory(i))) {
  3282. status.SetError(cmStrCat("does not exist:\n ", i));
  3283. cmSystemTools::SetFatalErrorOccurred();
  3284. return false;
  3285. }
  3286. if (cmSystemTools::FileExists(i, true)) {
  3287. bool success = true;
  3288. const mode_t& filePermissions =
  3289. parsedArgs.FilePermissions ? fperms : perms;
  3290. if (filePermissions) {
  3291. success = SetPermissions(i, filePermissions, status);
  3292. }
  3293. if (!success) {
  3294. return false;
  3295. }
  3296. }
  3297. else if (cmSystemTools::FileIsDirectory(i)) {
  3298. bool success = true;
  3299. const mode_t& directoryPermissions =
  3300. parsedArgs.DirectoryPermissions ? dperms : perms;
  3301. if (directoryPermissions) {
  3302. success = SetPermissions(i, directoryPermissions, status);
  3303. }
  3304. if (!success) {
  3305. return false;
  3306. }
  3307. }
  3308. }
  3309. return true;
  3310. }
  3311. bool HandleChmodCommand(std::vector<std::string> const& args,
  3312. cmExecutionStatus& status)
  3313. {
  3314. return HandleChmodCommandImpl(args, false, status);
  3315. }
  3316. bool HandleChmodRecurseCommand(std::vector<std::string> const& args,
  3317. cmExecutionStatus& status)
  3318. {
  3319. return HandleChmodCommandImpl(args, true, status);
  3320. }
  3321. } // namespace
  3322. bool cmFileCommand(std::vector<std::string> const& args,
  3323. cmExecutionStatus& status)
  3324. {
  3325. if (args.size() < 2) {
  3326. status.SetError("must be called with at least two arguments.");
  3327. return false;
  3328. }
  3329. static cmSubcommandTable const subcommand{
  3330. { "WRITE"_s, HandleWriteCommand },
  3331. { "APPEND"_s, HandleAppendCommand },
  3332. { "DOWNLOAD"_s, HandleDownloadCommand },
  3333. { "UPLOAD"_s, HandleUploadCommand },
  3334. { "READ"_s, HandleReadCommand },
  3335. { "MD5"_s, HandleHashCommand },
  3336. { "SHA1"_s, HandleHashCommand },
  3337. { "SHA224"_s, HandleHashCommand },
  3338. { "SHA256"_s, HandleHashCommand },
  3339. { "SHA384"_s, HandleHashCommand },
  3340. { "SHA512"_s, HandleHashCommand },
  3341. { "SHA3_224"_s, HandleHashCommand },
  3342. { "SHA3_256"_s, HandleHashCommand },
  3343. { "SHA3_384"_s, HandleHashCommand },
  3344. { "SHA3_512"_s, HandleHashCommand },
  3345. { "STRINGS"_s, HandleStringsCommand },
  3346. { "GLOB"_s, HandleGlobCommand },
  3347. { "GLOB_RECURSE"_s, HandleGlobRecurseCommand },
  3348. { "MAKE_DIRECTORY"_s, HandleMakeDirectoryCommand },
  3349. { "RENAME"_s, HandleRename },
  3350. { "COPY_FILE"_s, HandleCopyFile },
  3351. { "REMOVE"_s, HandleRemove },
  3352. { "REMOVE_RECURSE"_s, HandleRemoveRecurse },
  3353. { "COPY"_s, HandleCopyCommand },
  3354. { "INSTALL"_s, HandleInstallCommand },
  3355. { "DIFFERENT"_s, HandleDifferentCommand },
  3356. { "RPATH_CHANGE"_s, HandleRPathChangeCommand },
  3357. { "CHRPATH"_s, HandleRPathChangeCommand },
  3358. { "RPATH_SET"_s, HandleRPathSetCommand },
  3359. { "RPATH_CHECK"_s, HandleRPathCheckCommand },
  3360. { "RPATH_REMOVE"_s, HandleRPathRemoveCommand },
  3361. { "READ_ELF"_s, HandleReadElfCommand },
  3362. { "REAL_PATH"_s, HandleRealPathCommand },
  3363. { "RELATIVE_PATH"_s, HandleRelativePathCommand },
  3364. { "TO_CMAKE_PATH"_s, HandleCMakePathCommand },
  3365. { "TO_NATIVE_PATH"_s, HandleNativePathCommand },
  3366. { "TOUCH"_s, HandleTouchCommand },
  3367. { "TOUCH_NOCREATE"_s, HandleTouchNocreateCommand },
  3368. { "TIMESTAMP"_s, HandleTimestampCommand },
  3369. { "GENERATE"_s, HandleGenerateCommand },
  3370. { "LOCK"_s, HandleLockCommand },
  3371. { "SIZE"_s, HandleSizeCommand },
  3372. { "READ_SYMLINK"_s, HandleReadSymlinkCommand },
  3373. { "CREATE_LINK"_s, HandleCreateLinkCommand },
  3374. { "GET_RUNTIME_DEPENDENCIES"_s, HandleGetRuntimeDependenciesCommand },
  3375. { "CONFIGURE"_s, HandleConfigureCommand },
  3376. { "ARCHIVE_CREATE"_s, HandleArchiveCreateCommand },
  3377. { "ARCHIVE_EXTRACT"_s, HandleArchiveExtractCommand },
  3378. { "CHMOD"_s, HandleChmodCommand },
  3379. { "CHMOD_RECURSE"_s, HandleChmodRecurseCommand },
  3380. };
  3381. return subcommand(args[0], args, status);
  3382. }