cmFileCommand.cxx 101 KB

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