cmFileCommand.cxx 110 KB

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