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