cmFileCommand.cxx 97 KB

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