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