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