cmFileCommand.cxx 105 KB

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