cmFileCommand.cxx 104 KB

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