cmFileCommand.cxx 99 KB

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