cmFileCommand.cxx 107 KB

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