cmFileCommand.cxx 100 KB

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