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