mmap.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 = malloc(iSize);
  76. SyncToFd = new FileFd();
  77. if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
  78. return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
  79. return true;
  80. }
  81. // Map it.
  82. Base = (Flags & Fallback) ? MAP_FAILED : mmap(0,iSize,Prot,Map,Fd.Fd(),0);
  83. if (Base == (void *)-1)
  84. {
  85. if (errno == ENODEV || errno == EINVAL || (Flags & Fallback))
  86. {
  87. // The filesystem doesn't support this particular kind of mmap.
  88. // So we allocate a buffer and read the whole file into it.
  89. if ((Flags & ReadOnly) == ReadOnly)
  90. {
  91. // for readonly, we don't need sync, so make it simple
  92. Base = malloc(iSize);
  93. return Fd.Read(Base, iSize);
  94. }
  95. // FIXME: Writing to compressed fd's ?
  96. int const dupped_fd = dup(Fd.Fd());
  97. if (dupped_fd == -1)
  98. return _error->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd.Fd());
  99. Base = calloc(iSize, 1);
  100. SyncToFd = new FileFd (dupped_fd);
  101. if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
  102. return false;
  103. }
  104. else
  105. return _error->Errno("mmap",_("Couldn't make mmap of %llu bytes"),
  106. iSize);
  107. }
  108. return true;
  109. }
  110. /*}}}*/
  111. // MMap::Close - Close the map /*{{{*/
  112. // ---------------------------------------------------------------------
  113. /* */
  114. bool MMap::Close(bool DoSync)
  115. {
  116. if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
  117. return true;
  118. if (DoSync == true)
  119. Sync();
  120. if (SyncToFd != NULL)
  121. {
  122. free(Base);
  123. delete SyncToFd;
  124. SyncToFd = NULL;
  125. }
  126. else
  127. {
  128. if (munmap((char *)Base, iSize) != 0)
  129. _error->WarningE("mmap", _("Unable to close mmap"));
  130. }
  131. iSize = 0;
  132. Base = 0;
  133. return true;
  134. }
  135. /*}}}*/
  136. // MMap::Sync - Syncronize the map with the disk /*{{{*/
  137. // ---------------------------------------------------------------------
  138. /* This is done in syncronous mode - the docs indicate that this will
  139. not return till all IO is complete */
  140. bool MMap::Sync()
  141. {
  142. if ((Flags & UnMapped) == UnMapped)
  143. return true;
  144. #ifdef _POSIX_SYNCHRONIZED_IO
  145. if ((Flags & ReadOnly) != ReadOnly)
  146. {
  147. if (SyncToFd != NULL)
  148. {
  149. if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
  150. return false;
  151. }
  152. else
  153. {
  154. if (msync((char *)Base, iSize, MS_SYNC) < 0)
  155. return _error->Errno("msync", _("Unable to synchronize mmap"));
  156. }
  157. }
  158. #endif
  159. return true;
  160. }
  161. /*}}}*/
  162. // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
  163. // ---------------------------------------------------------------------
  164. /* */
  165. bool MMap::Sync(unsigned long Start,unsigned long Stop)
  166. {
  167. if ((Flags & UnMapped) == UnMapped)
  168. return true;
  169. #ifdef _POSIX_SYNCHRONIZED_IO
  170. unsigned long long PSize = sysconf(_SC_PAGESIZE);
  171. if ((Flags & ReadOnly) != ReadOnly)
  172. {
  173. if (SyncToFd != 0)
  174. {
  175. if (!SyncToFd->Seek(0) ||
  176. !SyncToFd->Write (((char *)Base)+Start, Stop-Start))
  177. return false;
  178. }
  179. else
  180. {
  181. if (msync((char *)Base+(unsigned long long)(Start/PSize)*PSize,Stop - Start,MS_SYNC) < 0)
  182. return _error->Errno("msync", _("Unable to synchronize mmap"));
  183. }
  184. }
  185. #endif
  186. return true;
  187. }
  188. /*}}}*/
  189. // DynamicMMap::DynamicMMap - Constructor /*{{{*/
  190. // ---------------------------------------------------------------------
  191. /* */
  192. DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
  193. unsigned long const &Grow, unsigned long const &Limit) :
  194. MMap(F,Flags | NoImmMap), Fd(&F), WorkSpace(Workspace),
  195. GrowFactor(Grow), Limit(Limit)
  196. {
  197. if (_error->PendingError() == true)
  198. return;
  199. unsigned long long EndOfFile = Fd->Size();
  200. if (EndOfFile > WorkSpace)
  201. WorkSpace = EndOfFile;
  202. else if(WorkSpace > 0)
  203. {
  204. Fd->Seek(WorkSpace - 1);
  205. char C = 0;
  206. Fd->Write(&C,sizeof(C));
  207. }
  208. Map(F);
  209. iSize = EndOfFile;
  210. }
  211. /*}}}*/
  212. // DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
  213. // ---------------------------------------------------------------------
  214. /* We try here to use mmap to reserve some space - this is much more
  215. cooler than the fallback solution to simply allocate a char array
  216. and could come in handy later than we are able to grow such an mmap */
  217. DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
  218. unsigned long const &Grow, unsigned long const &Limit) :
  219. MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
  220. GrowFactor(Grow), Limit(Limit)
  221. {
  222. if (_error->PendingError() == true)
  223. return;
  224. // disable Moveable if we don't grow
  225. if (Grow == 0)
  226. this->Flags &= ~Moveable;
  227. #ifndef __linux__
  228. // kfreebsd doesn't have mremap, so we use the fallback
  229. if ((this->Flags & Moveable) == Moveable)
  230. this->Flags |= Fallback;
  231. #endif
  232. #ifdef _POSIX_MAPPED_FILES
  233. if ((this->Flags & Fallback) != Fallback) {
  234. // Set the permissions.
  235. int Prot = PROT_READ;
  236. #ifdef MAP_ANONYMOUS
  237. int Map = MAP_PRIVATE | MAP_ANONYMOUS;
  238. #else
  239. int Map = MAP_PRIVATE | MAP_ANON;
  240. #endif
  241. if ((this->Flags & ReadOnly) != ReadOnly)
  242. Prot |= PROT_WRITE;
  243. if ((this->Flags & Public) == Public)
  244. #ifdef MAP_ANONYMOUS
  245. Map = MAP_SHARED | MAP_ANONYMOUS;
  246. #else
  247. Map = MAP_SHARED | MAP_ANON;
  248. #endif
  249. // use anonymous mmap() to get the memory
  250. Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
  251. if(Base == MAP_FAILED)
  252. _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
  253. iSize = 0;
  254. return;
  255. }
  256. #endif
  257. // fallback to a static allocated space
  258. Base = calloc(WorkSpace, 1);
  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. free(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. else
  422. /* Set new memory to 0 */
  423. memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
  424. }
  425. Pools =(Pool*) Base + poolOffset;
  426. WorkSpace = newSize;
  427. return true;
  428. }
  429. /*}}}*/