cmFileCommand.cxx 106 KB

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