cmFileCommand.cxx 101 KB

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