]> git.saurik.com Git - apt.git/blame - apt-pkg/contrib/mmap.cc
Correctly report write errors when flushing buffered writer
[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 /*{{{*/
f9d8a915 19#define _DEFAULT_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),
6789e01e 41 Base(nullptr), SyncToFd(nullptr)
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),
6789e01e 51 Base(nullptr), SyncToFd(nullptr)
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);
6789e01e
DK
87 if (unlikely(Base == nullptr))
88 return _error->Errno("MMap-compressed-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
6bae2c51 89 SyncToFd = new FileFd();
032bd56f 90 if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
b711c01e 91 return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
032bd56f
DK
92 return true;
93 }
94
578bfd0a 95 // Map it.
7899a133 96 Base = (Flags & Fallback) ? MAP_FAILED : mmap(0,iSize,Prot,Map,Fd.Fd(),0);
6789e01e 97 if (Base == MAP_FAILED)
06afffcc 98 {
7899a133 99 if (errno == ENODEV || errno == EINVAL || (Flags & Fallback))
06afffcc
DK
100 {
101 // The filesystem doesn't support this particular kind of mmap.
102 // So we allocate a buffer and read the whole file into it.
699b209e
DK
103 if ((Flags & ReadOnly) == ReadOnly)
104 {
105 // for readonly, we don't need sync, so make it simple
7899a133 106 Base = malloc(iSize);
6789e01e
DK
107 if (unlikely(Base == nullptr))
108 return _error->Errno("MMap-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
fbda0ee9 109 SyncToFd = new FileFd();
699b209e
DK
110 return Fd.Read(Base, iSize);
111 }
112 // FIXME: Writing to compressed fd's ?
06afffcc
DK
113 int const dupped_fd = dup(Fd.Fd());
114 if (dupped_fd == -1)
115 return _error->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd.Fd());
116
7899a133 117 Base = calloc(iSize, 1);
6789e01e
DK
118 if (unlikely(Base == nullptr))
119 return _error->Errno("MMap-calloc", _("Couldn't make mmap of %llu bytes"), iSize);
06afffcc
DK
120 SyncToFd = new FileFd (dupped_fd);
121 if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
122 return false;
123 }
124 else
6789e01e 125 return _error->Errno("MMap-mmap", _("Couldn't make mmap of %llu bytes"), iSize);
06afffcc 126 }
578bfd0a
AL
127
128 return true;
129}
130 /*}}}*/
131// MMap::Close - Close the map /*{{{*/
132// ---------------------------------------------------------------------
133/* */
2d11135a 134bool MMap::Close(bool DoSync)
578bfd0a 135{
2a79d5b5 136 if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
578bfd0a 137 return true;
2d11135a 138
1164783d
AL
139 if (DoSync == true)
140 Sync();
06afffcc
DK
141
142 if (SyncToFd != NULL)
143 {
7899a133 144 free(Base);
06afffcc
DK
145 delete SyncToFd;
146 SyncToFd = NULL;
147 }
148 else
149 {
150 if (munmap((char *)Base, iSize) != 0)
151 _error->WarningE("mmap", _("Unable to close mmap"));
152 }
153
578bfd0a 154 iSize = 0;
b2e465d6 155 Base = 0;
578bfd0a
AL
156 return true;
157}
158 /*}}}*/
159// MMap::Sync - Syncronize the map with the disk /*{{{*/
160// ---------------------------------------------------------------------
0149949b
AL
161/* This is done in syncronous mode - the docs indicate that this will
162 not return till all IO is complete */
578bfd0a 163bool MMap::Sync()
3ac981df 164{
2d11135a
AL
165 if ((Flags & UnMapped) == UnMapped)
166 return true;
3ac981df 167
1164783d 168 if ((Flags & ReadOnly) != ReadOnly)
06afffcc
DK
169 {
170 if (SyncToFd != NULL)
171 {
172 if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
173 return false;
174 }
175 else
176 {
3ac981df 177#ifdef _POSIX_SYNCHRONIZED_IO
06afffcc
DK
178 if (msync((char *)Base, iSize, MS_SYNC) < 0)
179 return _error->Errno("msync", _("Unable to synchronize mmap"));
3ac981df 180#endif
06afffcc
DK
181 }
182 }
578bfd0a
AL
183 return true;
184}
185 /*}}}*/
186// MMap::Sync - Syncronize a section of the file to disk /*{{{*/
187// ---------------------------------------------------------------------
188/* */
189bool MMap::Sync(unsigned long Start,unsigned long Stop)
190{
2d11135a
AL
191 if ((Flags & UnMapped) == UnMapped)
192 return true;
3ac981df 193
1164783d 194 if ((Flags & ReadOnly) != ReadOnly)
06afffcc
DK
195 {
196 if (SyncToFd != 0)
197 {
198 if (!SyncToFd->Seek(0) ||
199 !SyncToFd->Write (((char *)Base)+Start, Stop-Start))
200 return false;
201 }
202 else
203 {
3ac981df 204#ifdef _POSIX_SYNCHRONIZED_IO
e3348f47 205 unsigned long long const PSize = sysconf(_SC_PAGESIZE);
e788a834 206 if (msync((char *)Base+(Start/PSize)*PSize, Stop - Start, MS_SYNC) < 0)
06afffcc 207 return _error->Errno("msync", _("Unable to synchronize mmap"));
3ac981df 208#endif
06afffcc
DK
209 }
210 }
578bfd0a
AL
211 return true;
212}
213 /*}}}*/
214
215// DynamicMMap::DynamicMMap - Constructor /*{{{*/
216// ---------------------------------------------------------------------
217/* */
d6c4a976
DK
218DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
219 unsigned long const &Grow, unsigned long const &Limit) :
220 MMap(F,Flags | NoImmMap), Fd(&F), WorkSpace(Workspace),
221 GrowFactor(Grow), Limit(Limit)
578bfd0a 222{
7b15b702
DK
223 // disable Moveable if we don't grow
224 if (Grow == 0)
225 this->Flags &= ~Moveable;
226
227#ifndef __linux__
228 // kfreebsd doesn't have mremap, so we use the fallback
229 if ((this->Flags & Moveable) == Moveable)
230 this->Flags |= Fallback;
231#endif
232
650faab0 233 unsigned long long EndOfFile = Fd->Size();
b2e465d6
AL
234 if (EndOfFile > WorkSpace)
235 WorkSpace = EndOfFile;
ea92d036 236 else if(WorkSpace > 0)
b2e465d6 237 {
ea92d036 238 Fd->Seek(WorkSpace - 1);
b2e465d6
AL
239 char C = 0;
240 Fd->Write(&C,sizeof(C));
241 }
242
2d11135a 243 Map(F);
578bfd0a
AL
244 iSize = EndOfFile;
245}
246 /*}}}*/
2d11135a
AL
247// DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
248// ---------------------------------------------------------------------
f1c6a8ca
DK
249/* We try here to use mmap to reserve some space - this is much more
250 cooler than the fallback solution to simply allocate a char array
251 and could come in handy later than we are able to grow such an mmap */
d6c4a976
DK
252DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
253 unsigned long const &Grow, unsigned long const &Limit) :
254 MMap(Flags | NoImmMap | UnMapped), Fd(0), WorkSpace(WorkSpace),
255 GrowFactor(Grow), Limit(Limit)
2d11135a 256{
d6c4a976
DK
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{
62d8a765
DK
354 if (unlikely(ItemSize == 0))
355 {
356 _error->Fatal("Can't allocate an item of size zero");
357 return 0;
358 }
359
578bfd0a
AL
360 // Look for a matching pool entry
361 Pool *I;
362 Pool *Empty = 0;
a9fe5928 363 for (I = Pools; I != Pools + PoolCount; ++I)
578bfd0a
AL
364 {
365 if (I->ItemSize == 0)
366 Empty = I;
367 if (I->ItemSize == ItemSize)
368 break;
369 }
578bfd0a
AL
370 // No pool is allocated, use an unallocated one
371 if (I == Pools + PoolCount)
372 {
373 // Woops, we ran out, the calling code should allocate more.
374 if (Empty == 0)
375 {
376 _error->Error("Ran out of allocation pools");
377 return 0;
378 }
379
380 I = Empty;
381 I->ItemSize = ItemSize;
382 I->Count = 0;
383 }
c5f44afc
DK
384
385 unsigned long Result = 0;
578bfd0a
AL
386 // Out of space, allocate some more
387 if (I->Count == 0)
388 {
c5f44afc
DK
389 const unsigned long size = 20*1024;
390 I->Count = size/ItemSize;
a9fe5928 391 Pool* oldPools = Pools;
95278287 392 _error->PushToStack();
c5f44afc 393 Result = RawAllocate(size,ItemSize);
95278287
DK
394 bool const newError = _error->PendingError();
395 _error->MergeWithStack();
a9fe5928
DK
396 if (Pools != oldPools)
397 I += Pools - oldPools;
398
c5f44afc 399 // Does the allocation failed ?
95278287 400 if (Result == 0 && newError)
c5f44afc
DK
401 return 0;
402 I->Start = Result;
403 }
404 else
405 Result = I->Start;
f55a958f 406
578bfd0a 407 I->Count--;
c5f44afc 408 I->Start += ItemSize;
578bfd0a
AL
409 return Result/ItemSize;
410}
411 /*}}}*/
412// DynamicMMap::WriteString - Write a string to the file /*{{{*/
413// ---------------------------------------------------------------------
60d523e2 414/* Strings are aligned to 16 bytes */
578bfd0a
AL
415unsigned long DynamicMMap::WriteString(const char *String,
416 unsigned long Len)
417{
6e52073f 418 if (Len == (unsigned long)-1)
578bfd0a 419 Len = strlen(String);
c5f44afc 420
95278287 421 _error->PushToStack();
60d523e2 422 unsigned long Result = RawAllocate(Len+1+sizeof(uint16_t),sizeof(uint16_t));
95278287
DK
423 bool const newError = _error->PendingError();
424 _error->MergeWithStack();
c5f44afc 425
95278287 426 if (Base == NULL || (Result == 0 && newError))
c5f44afc
DK
427 return 0;
428
60d523e2
JAK
429 if (Len >= std::numeric_limits<uint16_t>::max())
430 abort();
431
432 uint16_t LenToWrite = Len;
433 memcpy((char *)Base + Result, &LenToWrite, sizeof(LenToWrite));
434 Result += + sizeof(LenToWrite);
435
578bfd0a
AL
436 memcpy((char *)Base + Result,String,Len);
437 ((char *)Base)[Result + Len] = 0;
438 return Result;
439}
440 /*}}}*/
f1c6a8ca
DK
441// DynamicMMap::Grow - Grow the mmap /*{{{*/
442// ---------------------------------------------------------------------
d6c4a976
DK
443/* This method is a wrapper around different methods to (try to) grow
444 a mmap (or our char[]-fallback). Encounterable environments:
445 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
446 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
447 3. Moveable + Fallback -> realloc
448 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
449 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
450 6. !Moveable + Fallback -> not possible
451 [ While Moveable and Fallback stands for the equally named flags and
452 "linux" indicates a linux kernel instead of a freebsd kernel. ]
453 So what you can see here is, that a MMAP which want to be growable need
454 to be moveable to have a real chance but that this method will at least try
455 the nearly impossible 4 to grow it before it finally give up: Never say never. */
456bool DynamicMMap::Grow() {
457 if (Limit != 0 && WorkSpace >= Limit)
e3ac3b46
DK
458 return _error->Error(_("Unable to increase the size of the MMap as the "
459 "limit of %lu bytes is already reached."), Limit);
dcdf1ef1
DK
460 if (GrowFactor <= 0)
461 return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
f1c6a8ca 462
650faab0 463 unsigned long long const newSize = WorkSpace + GrowFactor;
f1c6a8ca 464
d6c4a976
DK
465 if(Fd != 0) {
466 Fd->Seek(newSize - 1);
467 char C = 0;
468 Fd->Write(&C,sizeof(C));
469 }
a9fe5928
DK
470
471 unsigned long const poolOffset = Pools - ((Pool*) Base);
472
d6c4a976
DK
473 if ((Flags & Fallback) != Fallback) {
474#if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
475 #ifdef MREMAP_MAYMOVE
a9fe5928 476
d6c4a976
DK
477 if ((Flags & Moveable) == Moveable)
478 Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
479 else
480 #endif
481 Base = mremap(Base, WorkSpace, newSize, 0);
f1c6a8ca 482
d6c4a976
DK
483 if(Base == MAP_FAILED)
484 return false;
f1c6a8ca 485#else
d6c4a976 486 return false;
f1c6a8ca 487#endif
d6c4a976
DK
488 } else {
489 if ((Flags & Moveable) != Moveable)
490 return false;
491
492 Base = realloc(Base, newSize);
493 if (Base == NULL)
494 return false;
e3026ce4
JAK
495 else
496 /* Set new memory to 0 */
497 memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
d6c4a976
DK
498 }
499
a9fe5928 500 Pools =(Pool*) Base + poolOffset;
d6c4a976
DK
501 WorkSpace = newSize;
502 return true;
f1c6a8ca
DK
503}
504 /*}}}*/