mmap.cc 13 KB

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