mmap.cc 13 KB

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