cmFileCommand.cxx 101 KB

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