mmap.cc 13 KB

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