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