mmap.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: mmap.cc,v 1.22 2001/05/27 05:19:30 jgg Exp $
  4. /* ######################################################################
  5. MMap Class - Provides 'real' mmap or a faked mmap using read().
  6. MMap cover class.
  7. Some broken versions of glibc2 (libc6) have a broken definition
  8. of mmap that accepts a char * -- all other systems (and libc5) use
  9. void *. We can't safely do anything here that would be portable, so
  10. libc6 generates warnings -- which should be errors, g++ isn't properly
  11. strict.
  12. ##################################################################### */
  13. /*}}}*/
  14. // Include Files /*{{{*/
  15. #define _BSD_SOURCE
  16. #include <config.h>
  17. #include <apt-pkg/mmap.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/fileutl.h>
  20. #include <sys/mman.h>
  21. #include <sys/stat.h>
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <stdlib.h>
  25. #include <errno.h>
  26. #include <cstring>
  27. #include <apti18n.h>
  28. /*}}}*/
  29. // MMap::MMap - Constructor /*{{{*/
  30. // ---------------------------------------------------------------------
  31. /* */
  32. MMap::MMap(FileFd &F,unsigned long Flags) : Flags(Flags), iSize(0),
  33. Base(0), SyncToFd(NULL)
  34. {
  35. if ((Flags & NoImmMap) != NoImmMap)
  36. Map(F);
  37. }
  38. /*}}}*/
  39. // MMap::MMap - Constructor /*{{{*/
  40. // ---------------------------------------------------------------------
  41. /* */
  42. MMap::MMap(unsigned long Flags) : Flags(Flags), iSize(0),
  43. Base(0), SyncToFd(NULL)
  44. {
  45. }
  46. /*}}}*/
  47. // MMap::~MMap - Destructor /*{{{*/
  48. // ---------------------------------------------------------------------
  49. /* */
  50. MMap::~MMap()
  51. {
  52. Close();
  53. }
  54. /*}}}*/
  55. // MMap::Map - Perform the mapping /*{{{*/
  56. // ---------------------------------------------------------------------
  57. /* */
  58. bool MMap::Map(FileFd &Fd)
  59. {
  60. iSize = Fd.Size();
  61. // Set the permissions.
  62. int Prot = PROT_READ;
  63. int Map = MAP_SHARED;
  64. if ((Flags & ReadOnly) != ReadOnly)
  65. Prot |= PROT_WRITE;
  66. if ((Flags & Public) != Public)
  67. Map = MAP_PRIVATE;
  68. if (iSize == 0)
  69. return _error->Error(_("Can't mmap an empty file"));
  70. // We can't mmap compressed fd's directly, so we need to read it completely
  71. if (Fd.IsCompressed() == true)
  72. {
  73. if ((Flags & ReadOnly) != ReadOnly)
  74. return _error->Error("Compressed file %s can only be mapped readonly", Fd.Name().c_str());
  75. Base = new unsigned char[iSize];
  76. if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
  77. return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
  78. return true;
  79. }
  80. // Map it.
  81. Base = mmap(0,iSize,Prot,Map,Fd.Fd(),0);
  82. if (Base == (void *)-1)
  83. {
  84. if (errno == ENODEV || errno == EINVAL)
  85. {
  86. // The filesystem doesn't support this particular kind of mmap.
  87. // So we allocate a buffer and read the whole file into it.
  88. if ((Flags & ReadOnly) == ReadOnly)
  89. {
  90. // for readonly, we don't need sync, so make it simple
  91. Base = new unsigned char[iSize];
  92. return Fd.Read(Base, iSize);
  93. }
  94. // FIXME: Writing to compressed fd's ?
  95. int const dupped_fd = dup(Fd.Fd());
  96. if (dupped_fd == -1)
  97. return _error->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd.Fd());
  98. Base = new unsigned char[iSize];
  99. SyncToFd = new FileFd (dupped_fd);
  100. if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
  101. return false;
  102. }
  103. else
  104. return _error->Errno("mmap",_("Couldn't make mmap of %llu bytes"),
  105. iSize);
  106. }
  107. return true;
  108. }
  109. /*}}}*/
  110. // MMap::Close - Close the map /*{{{*/
  111. // ---------------------------------------------------------------------
  112. /* */
  113. bool MMap::Close(bool DoSync)
  114. {
  115. if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
  116. return true;
  117. if (DoSync == true)
  118. Sync();
  119. if (SyncToFd != NULL)
  120. {
  121. delete[] (char *)Base;
  122. delete SyncToFd;
  123. SyncToFd = NULL;
  124. }
  125. else
  126. {
  127. if (munmap((char *)Base, iSize) != 0)
  128. _error->WarningE("mmap", _("Unable to close mmap"));
  129. }
  130. iSize = 0;
  131. Base = 0;
  132. return true;
  133. }
  134. /*}}}*/
  135. // MMap::Sync - Syncronize the map with the disk /*{{{*/
  136. // ---------------------------------------------------------------------
  137. /* This is done in syncronous mode - the docs indicate that this will
  138. not return till all IO is complete */
  139. bool MMap::Sync()
  140. {
  141. if ((Flags & UnMapped) == UnMapped)
  142. return true;
  143. #ifdef _POSIX_SYNCHRONIZED_IO
  144. if ((Flags & ReadOnly) != ReadOnly)
  145. {
  146. if (SyncToFd != NULL)
  147. {
  148. if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
  149. return false;
  150. }
  151. else
  152. {
  153. if (msync((char *)Base, iSize, MS_SYNC) < 0)
  154. return _error->Errno("msync", _("Unable to synchronize mmap"));
  155. }
  156. }
  157. #endif
  158. return true;
  159. }
  160. /*}}}*/
  161. // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
  162. // ---------------------------------------------------------------------
  163. /* */
  164. bool MMap::Sync(unsigned long Start,unsigned long Stop)
  165. {
  166. if ((Flags & UnMapped) == UnMapped)
  167. return true;
  168. #ifdef _POSIX_SYNCHRONIZED_IO
  169. unsigned long long PSize = sysconf(_SC_PAGESIZE);
  170. if ((Flags & ReadOnly) != ReadOnly)
  171. {
  172. if (SyncToFd != 0)
  173. {
  174. if (!SyncToFd->Seek(0) ||
  175. !SyncToFd->Write (((char *)Base)+Start, Stop-Start))
  176. return false;
  177. }
  178. else
  179. {
  180. if (msync((char *)Base+(unsigned long long)(Start/PSize)*PSize,Stop - Start,MS_SYNC) < 0)
  181. return _error->Errno("msync", _("Unable to synchronize mmap"));
  182. }
  183. }
  184. #endif
  185. return true;
  186. }
  187. /*}}}*/
  188. // DynamicMMap::DynamicMMap - Constructor /*{{{*/
  189. // ---------------------------------------------------------------------
  190. /* */
  191. DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
  192. unsigned long const &Grow, unsigned long const &Limit) :
  193. MMap(F,Flags | NoImmMap), Fd(&F), WorkSpace(Workspace),
  194. GrowFactor(Grow), Limit(Limit)
  195. {
  196. if (_error->PendingError() == true)
  197. return;
  198. unsigned long long EndOfFile = Fd->Size();
  199. if (EndOfFile > WorkSpace)
  200. WorkSpace = EndOfFile;
  201. else if(WorkSpace > 0)
  202. {
  203. Fd->Seek(WorkSpace - 1);
  204. char C = 0;
  205. Fd->Write(&C,sizeof(C));
  206. }
  207. Map(F);
  208. iSize = EndOfFile;
  209. }
  210. /*}}}*/
  211. // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
  212. // ---------------------------------------------------------------------
  213. /* We try here to use mmap to reserve some space - this is much more
  214. cooler than the fallback solution to simply allocate a char array
  215. and could come in handy later than we are able to grow such an mmap */
  216. DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
  217. unsigned long const &Grow, unsigned long const &Limit) :
  218. MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
  219. GrowFactor(Grow), Limit(Limit)
  220. {
  221. if (_error->PendingError() == true)
  222. return;
  223. // disable Moveable if we don't grow
  224. if (Grow == 0)
  225. this->Flags &= ~Moveable;
  226. #ifndef __linux__
  227. // kfreebsd doesn't have mremap, so we use the fallback
  228. if ((this->Flags & Moveable) == Moveable)
  229. this->Flags |= Fallback;
  230. #endif
  231. #ifdef _POSIX_MAPPED_FILES
  232. if ((this->Flags & Fallback) != Fallback) {
  233. // Set the permissions.
  234. int Prot = PROT_READ;
  235. #ifdef MAP_ANONYMOUS
  236. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  237. #else
  238. int Map = MAP_PRIVATE | MAP_ANON;
  239. #endif
  240. if ((this->Flags & ReadOnly) != ReadOnly)
  241. Prot |= PROT_WRITE;
  242. if ((this->Flags & Public) == Public)
  243. #ifdef MAP_ANONYMOUS
  244. Map = MAP_SHARED | MAP_ANONYMOUS;
  245. #else
  246. Map = MAP_SHARED | MAP_ANON;
  247. #endif
  248. // use anonymous mmap() to get the memory
  249. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  250. if(Base == MAP_FAILED)
  251. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  252. iSize = 0;
  253. return;
  254. }
  255. #endif
  256. // fallback to a static allocated space
  257. Base = new unsigned char[WorkSpace];
  258. memset(Base,0,WorkSpace);
  259. iSize = 0;
  260. }
  261. /*}}}*/
  262. // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
  263. // ---------------------------------------------------------------------
  264. /* We truncate the file to the size of the memory data set */
  265. DynamicMMap::~DynamicMMap()
  266. {
  267. if (Fd == 0)
  268. {
  269. if (validData() == false)
  270. return;
  271. #ifdef _POSIX_MAPPED_FILES
  272. munmap(Base, WorkSpace);
  273. #else
  274. delete [] (unsigned char *)Base;
  275. #endif
  276. return;
  277. }
  278. unsigned long long EndOfFile = iSize;
  279. iSize = WorkSpace;
  280. Close(false);
  281. if(ftruncate(Fd->Fd(),EndOfFile) < 0)
  282. _error->Errno("ftruncate", _("Failed to truncate file"));
  283. }
  284. /*}}}*/
  285. // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
  286. // ---------------------------------------------------------------------
  287. /* This allocates a block of memory aligned to the given size */
  288. unsigned long DynamicMMap::RawAllocate(unsigned long long Size,unsigned long Aln)
  289. {
  290. unsigned long long Result = iSize;
  291. if (Aln != 0)
  292. Result += Aln - (iSize%Aln);
  293. iSize = Result + Size;
  294. // try to grow the buffer
  295. while(Result + Size > WorkSpace)
  296. {
  297. if(!Grow())
  298. {
  299. _error->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
  300. "of APT::Cache-Limit. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
  301. return 0;
  302. }
  303. }
  304. return Result;
  305. }
  306. /*}}}*/
  307. // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
  308. // ---------------------------------------------------------------------
  309. /* This allocates an Item of size ItemSize so that it is aligned to its
  310. size in the file. */
  311. unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
  312. {
  313. // Look for a matching pool entry
  314. Pool *I;
  315. Pool *Empty = 0;
  316. for (I = Pools; I != Pools + PoolCount; ++I)
  317. {
  318. if (I->ItemSize == 0)
  319. Empty = I;
  320. if (I->ItemSize == ItemSize)
  321. break;
  322. }
  323. // No pool is allocated, use an unallocated one
  324. if (I == Pools + PoolCount)
  325. {
  326. // Woops, we ran out, the calling code should allocate more.
  327. if (Empty == 0)
  328. {
  329. _error->Error("Ran out of allocation pools");
  330. return 0;
  331. }
  332. I = Empty;
  333. I->ItemSize = ItemSize;
  334. I->Count = 0;
  335. }
  336. unsigned long Result = 0;
  337. // Out of space, allocate some more
  338. if (I->Count == 0)
  339. {
  340. const unsigned long size = 20*1024;
  341. I->Count = size/ItemSize;
  342. Pool* oldPools = Pools;
  343. Result = RawAllocate(size,ItemSize);
  344. if (Pools != oldPools)
  345. I += Pools - oldPools;
  346. // Does the allocation failed ?
  347. if (Result == 0 && _error->PendingError())
  348. return 0;
  349. I->Start = Result;
  350. }
  351. else
  352. Result = I->Start;
  353. I->Count--;
  354. I->Start += ItemSize;
  355. return Result/ItemSize;
  356. }
  357. /*}}}*/
  358. // DynamicMMap::WriteString - Write a string to the file /*{{{*/
  359. // ---------------------------------------------------------------------
  360. /* Strings are not aligned to anything */
  361. unsigned long DynamicMMap::WriteString(const char *String,
  362. unsigned long Len)
  363. {
  364. if (Len == (unsigned long)-1)
  365. Len = strlen(String);
  366. unsigned long const Result = RawAllocate(Len+1,0);
  367. if (Result == 0 && _error->PendingError())
  368. return 0;
  369. memcpy((char *)Base + Result,String,Len);
  370. ((char *)Base)[Result + Len] = 0;
  371. return Result;
  372. }
  373. /*}}}*/
  374. // DynamicMMap::Grow - Grow the mmap /*{{{*/
  375. // ---------------------------------------------------------------------
  376. /* This method is a wrapper around different methods to (try to) grow
  377. a mmap (or our char[]-fallback). Encounterable environments:
  378. 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
  379. 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  380. 3. Moveable + Fallback -> realloc
  381. 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
  382. 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  383. 6. !Moveable + Fallback -> not possible
  384. [ While Moveable and Fallback stands for the equally named flags and
  385. "linux" indicates a linux kernel instead of a freebsd kernel. ]
  386. So what you can see here is, that a MMAP which want to be growable need
  387. to be moveable to have a real chance but that this method will at least try
  388. the nearly impossible 4 to grow it before it finally give up: Never say never. */
  389. bool DynamicMMap::Grow() {
  390. if (Limit != 0 && WorkSpace >= Limit)
  391. return _error->Error(_("Unable to increase the size of the MMap as the "
  392. "limit of %lu bytes is already reached."), Limit);
  393. if (GrowFactor <= 0)
  394. return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
  395. unsigned long long const newSize = WorkSpace + GrowFactor;
  396. if(Fd != 0) {
  397. Fd->Seek(newSize - 1);
  398. char C = 0;
  399. Fd->Write(&C,sizeof(C));
  400. }
  401. unsigned long const poolOffset = Pools - ((Pool*) Base);
  402. if ((Flags & Fallback) != Fallback) {
  403. #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
  404. #ifdef MREMAP_MAYMOVE
  405. if ((Flags & Moveable) == Moveable)
  406. Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
  407. else
  408. #endif
  409. Base = mremap(Base, WorkSpace, newSize, 0);
  410. if(Base == MAP_FAILED)
  411. return false;
  412. #else
  413. return false;
  414. #endif
  415. } else {
  416. if ((Flags & Moveable) != Moveable)
  417. return false;
  418. Base = realloc(Base, newSize);
  419. if (Base == NULL)
  420. return false;
  421. }
  422. Pools =(Pool*) Base + poolOffset;
  423. WorkSpace = newSize;
  424. return true;
  425. }
  426. /*}}}*/