cmFileCommand.cxx 106 KB

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