cmFileCommand.cxx 118 KB

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