cmFileCommand.cxx 107 KB

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