cmFileCommand.cxx 111 KB

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