mmap.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 || Base == 0 || 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. Flags &= ~Moveable;
  207. #ifndef __linux__
  208. // kfreebsd doesn't have mremap, so we use the fallback
  209. if ((Flags & Moveable) == Moveable)
  210. Flags |= Fallback;
  211. #endif
  212. #ifdef _POSIX_MAPPED_FILES
  213. if ((Flags & Fallback) != Fallback) {
  214. // Set the permissions.
  215. int Prot = PROT_READ;
  216. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  217. if ((Flags & ReadOnly) != ReadOnly)
  218. Prot |= PROT_WRITE;
  219. if ((Flags & Public) == Public)
  220. Map = MAP_SHARED | MAP_ANONYMOUS;
  221. // use anonymous mmap() to get the memory
  222. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  223. if(Base == MAP_FAILED)
  224. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  225. iSize = 0;
  226. return;
  227. }
  228. #endif
  229. // fallback to a static allocated space
  230. Base = new unsigned char[WorkSpace];
  231. memset(Base,0,WorkSpace);
  232. iSize = 0;
  233. }
  234. /*}}}*/
  235. // DynamicMMap::~DynamicMMap - Destructor /*{{{*/
  236. // ---------------------------------------------------------------------
  237. /* We truncate the file to the size of the memory data set */
  238. DynamicMMap::~DynamicMMap()
  239. {
  240. if (Fd == 0)
  241. {
  242. #ifdef _POSIX_MAPPED_FILES
  243. munmap(Base, WorkSpace);
  244. #else
  245. delete [] (unsigned char *)Base;
  246. #endif
  247. return;
  248. }
  249. unsigned long EndOfFile = iSize;
  250. iSize = WorkSpace;
  251. Close(false);
  252. if(ftruncate(Fd->Fd(),EndOfFile) < 0)
  253. _error->Errno("ftruncate", _("Failed to truncate file"));
  254. }
  255. /*}}}*/
  256. // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
  257. // ---------------------------------------------------------------------
  258. /* This allocates a block of memory aligned to the given size */
  259. unsigned long DynamicMMap::RawAllocate(unsigned long Size,unsigned long Aln)
  260. {
  261. unsigned long Result = iSize;
  262. if (Aln != 0)
  263. Result += Aln - (iSize%Aln);
  264. iSize = Result + Size;
  265. // try to grow the buffer
  266. while(Result + Size > WorkSpace)
  267. {
  268. if(!Grow())
  269. {
  270. _error->Error(_("Dynamic MMap ran out of room. Please increase the size "
  271. "of APT::Cache-Limit. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
  272. return 0;
  273. }
  274. }
  275. return Result;
  276. }
  277. /*}}}*/
  278. // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
  279. // ---------------------------------------------------------------------
  280. /* This allocates an Item of size ItemSize so that it is aligned to its
  281. size in the file. */
  282. unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
  283. {
  284. // Look for a matching pool entry
  285. Pool *I;
  286. Pool *Empty = 0;
  287. for (I = Pools; I != Pools + PoolCount; I++)
  288. {
  289. if (I->ItemSize == 0)
  290. Empty = I;
  291. if (I->ItemSize == ItemSize)
  292. break;
  293. }
  294. // No pool is allocated, use an unallocated one
  295. if (I == Pools + PoolCount)
  296. {
  297. // Woops, we ran out, the calling code should allocate more.
  298. if (Empty == 0)
  299. {
  300. _error->Error("Ran out of allocation pools");
  301. return 0;
  302. }
  303. I = Empty;
  304. I->ItemSize = ItemSize;
  305. I->Count = 0;
  306. }
  307. unsigned long Result = 0;
  308. // Out of space, allocate some more
  309. if (I->Count == 0)
  310. {
  311. const unsigned long size = 20*1024;
  312. I->Count = size/ItemSize;
  313. Result = RawAllocate(size,ItemSize);
  314. // Does the allocation failed ?
  315. if (Result == 0 && _error->PendingError())
  316. return 0;
  317. I->Start = Result;
  318. }
  319. else
  320. Result = I->Start;
  321. I->Count--;
  322. I->Start += ItemSize;
  323. return Result/ItemSize;
  324. }
  325. /*}}}*/
  326. // DynamicMMap::WriteString - Write a string to the file /*{{{*/
  327. // ---------------------------------------------------------------------
  328. /* Strings are not aligned to anything */
  329. unsigned long DynamicMMap::WriteString(const char *String,
  330. unsigned long Len)
  331. {
  332. if (Len == (unsigned long)-1)
  333. Len = strlen(String);
  334. unsigned long Result = RawAllocate(Len+1,0);
  335. if (Result == 0 && _error->PendingError())
  336. return 0;
  337. memcpy((char *)Base + Result,String,Len);
  338. ((char *)Base)[Result + Len] = 0;
  339. return Result;
  340. }
  341. /*}}}*/
  342. // DynamicMMap::Grow - Grow the mmap /*{{{*/
  343. // ---------------------------------------------------------------------
  344. /* This method is a wrapper around different methods to (try to) grow
  345. a mmap (or our char[]-fallback). Encounterable environments:
  346. 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
  347. 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  348. 3. Moveable + Fallback -> realloc
  349. 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
  350. 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
  351. 6. !Moveable + Fallback -> not possible
  352. [ While Moveable and Fallback stands for the equally named flags and
  353. "linux" indicates a linux kernel instead of a freebsd kernel. ]
  354. So what you can see here is, that a MMAP which want to be growable need
  355. to be moveable to have a real chance but that this method will at least try
  356. the nearly impossible 4 to grow it before it finally give up: Never say never. */
  357. bool DynamicMMap::Grow() {
  358. if (Limit != 0 && WorkSpace >= Limit)
  359. return _error->Error(_("Unable to increase the size of the MMap as the "
  360. "limit of %lu bytes is already reached."), Limit);
  361. unsigned long const newSize = WorkSpace + 1024*1024;
  362. if(Fd != 0) {
  363. Fd->Seek(newSize - 1);
  364. char C = 0;
  365. Fd->Write(&C,sizeof(C));
  366. }
  367. if ((Flags & Fallback) != Fallback) {
  368. #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
  369. #ifdef MREMAP_MAYMOVE
  370. if ((Flags & Moveable) == Moveable)
  371. Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
  372. else
  373. #endif
  374. Base = mremap(Base, WorkSpace, newSize, 0);
  375. if(Base == MAP_FAILED)
  376. return false;
  377. #else
  378. return false;
  379. #endif
  380. } else {
  381. if ((Flags & Moveable) != Moveable)
  382. return false;
  383. Base = realloc(Base, newSize);
  384. if (Base == NULL)
  385. return false;
  386. }
  387. WorkSpace = newSize;
  388. return true;
  389. }
  390. /*}}}*/