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