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