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