mmap.cc 14 KB

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