mmap.cc 14 KB

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