cmFileCommand.cxx 107 KB

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