]> git.saurik.com Git - apt.git/blame_incremental - apt-pkg/contrib/mmap.cc
Correctly report write errors when flushing buffered writer
[apt.git] / apt-pkg / contrib / mmap.cc
... / ...
CommitLineData
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
3// $Id: mmap.cc,v 1.22 2001/05/27 05:19:30 jgg Exp $
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
16 ##################################################################### */
17 /*}}}*/
18// Include Files /*{{{*/
19#define _DEFAULT_SOURCE
20#include <config.h>
21
22#include <apt-pkg/mmap.h>
23#include <apt-pkg/error.h>
24#include <apt-pkg/fileutl.h>
25#include <apt-pkg/macros.h>
26
27#include <string>
28#include <sys/mman.h>
29#include <unistd.h>
30#include <stdlib.h>
31#include <errno.h>
32#include <cstring>
33
34#include <apti18n.h>
35 /*}}}*/
36
37// MMap::MMap - Constructor /*{{{*/
38// ---------------------------------------------------------------------
39/* */
40MMap::MMap(FileFd &F,unsigned long Flags) : Flags(Flags), iSize(0),
41 Base(nullptr), SyncToFd(nullptr)
42{
43 if ((Flags & NoImmMap) != NoImmMap)
44 Map(F);
45}
46 /*}}}*/
47// MMap::MMap - Constructor /*{{{*/
48// ---------------------------------------------------------------------
49/* */
50MMap::MMap(unsigned long Flags) : Flags(Flags), iSize(0),
51 Base(nullptr), SyncToFd(nullptr)
52{
53}
54 /*}}}*/
55// MMap::~MMap - Destructor /*{{{*/
56// ---------------------------------------------------------------------
57/* */
58MMap::~MMap()
59{
60 Close();
61}
62 /*}}}*/
63// MMap::Map - Perform the mapping /*{{{*/
64// ---------------------------------------------------------------------
65/* */
66bool MMap::Map(FileFd &Fd)
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
78 if (iSize == 0)
79 return _error->Error(_("Can't mmap an empty file"));
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 = malloc(iSize);
87 if (unlikely(Base == nullptr))
88 return _error->Errno("MMap-compressed-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
89 SyncToFd = new FileFd();
90 if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
91 return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
92 return true;
93 }
94
95 // Map it.
96 Base = (Flags & Fallback) ? MAP_FAILED : mmap(0,iSize,Prot,Map,Fd.Fd(),0);
97 if (Base == MAP_FAILED)
98 {
99 if (errno == ENODEV || errno == EINVAL || (Flags & Fallback))
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.
103 if ((Flags & ReadOnly) == ReadOnly)
104 {
105 // for readonly, we don't need sync, so make it simple
106 Base = malloc(iSize);
107 if (unlikely(Base == nullptr))
108 return _error->Errno("MMap-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
109 SyncToFd = new FileFd();
110 return Fd.Read(Base, iSize);
111 }
112 // FIXME: Writing to compressed fd's ?
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
117 Base = calloc(iSize, 1);
118 if (unlikely(Base == nullptr))
119 return _error->Errno("MMap-calloc", _("Couldn't make mmap of %llu bytes"), iSize);
120 SyncToFd = new FileFd (dupped_fd);
121 if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
122 return false;
123 }
124 else
125 return _error->Errno("MMap-mmap", _("Couldn't make mmap of %llu bytes"), iSize);
126 }
127
128 return true;
129}
130 /*}}}*/
131// MMap::Close - Close the map /*{{{*/
132// ---------------------------------------------------------------------
133/* */
134bool MMap::Close(bool DoSync)
135{
136 if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
137 return true;
138
139 if (DoSync == true)
140 Sync();
141
142 if (SyncToFd != NULL)
143 {
144 free(Base);
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
154 iSize = 0;
155 Base = 0;
156 return true;
157}
158 /*}}}*/
159// MMap::Sync - Syncronize the map with the disk /*{{{*/
160// ---------------------------------------------------------------------
161/* This is done in syncronous mode - the docs indicate that this will
162 not return till all IO is complete */
163bool MMap::Sync()
164{
165 if ((Flags & UnMapped) == UnMapped)
166 return true;
167
168 if ((Flags & ReadOnly) != ReadOnly)
169 {
170 if (SyncToFd != NULL)
171 {
172 if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
173 return false;
174 }
175 else
176 {
177#ifdef _POSIX_SYNCHRONIZED_IO
178 if (msync((char *)Base, iSize, MS_SYNC) < 0)
179 return _error->Errno("msync", _("Unable to synchronize mmap"));
180#endif
181 }
182 }
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{
191 if ((Flags & UnMapped) == UnMapped)
192 return true;
193
194 if ((Flags & ReadOnly) != ReadOnly)
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 {
204#ifdef _POSIX_SYNCHRONIZED_IO
205 unsigned long long const PSize = sysconf(_SC_PAGESIZE);
206 if (msync((char *)Base+(Start/PSize)*PSize, Stop - Start, MS_SYNC) < 0)
207 return _error->Errno("msync", _("Unable to synchronize mmap"));
208#endif
209 }
210 }
211 return true;
212}
213 /*}}}*/
214
215// DynamicMMap::DynamicMMap - Constructor /*{{{*/
216// ---------------------------------------------------------------------
217/* */
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)
222{
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
233 unsigned long long EndOfFile = Fd->Size();
234 if (EndOfFile > WorkSpace)
235 WorkSpace = EndOfFile;
236 else if(WorkSpace > 0)
237 {
238 Fd->Seek(WorkSpace - 1);
239 char C = 0;
240 Fd->Write(&C,sizeof(C));
241 }
242
243 Map(F);
244 iSize = EndOfFile;
245}
246 /*}}}*/
247// DynamicMMap::DynamicMMap - Constructor for a non-file backed map /*{{{*/
248// ---------------------------------------------------------------------
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 */
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)
256{
257 // disable Moveable if we don't grow
258 if (Grow == 0)
259 this->Flags &= ~Moveable;
260
261#ifndef __linux__
262 // kfreebsd doesn't have mremap, so we use the fallback
263 if ((this->Flags & Moveable) == Moveable)
264 this->Flags |= Fallback;
265#endif
266
267#ifdef _POSIX_MAPPED_FILES
268 if ((this->Flags & Fallback) != Fallback) {
269 // Set the permissions.
270 int Prot = PROT_READ;
271#ifdef MAP_ANONYMOUS
272 int Map = MAP_PRIVATE | MAP_ANONYMOUS;
273#else
274 int Map = MAP_PRIVATE | MAP_ANON;
275#endif
276 if ((this->Flags & ReadOnly) != ReadOnly)
277 Prot |= PROT_WRITE;
278 if ((this->Flags & Public) == Public)
279#ifdef MAP_ANONYMOUS
280 Map = MAP_SHARED | MAP_ANONYMOUS;
281#else
282 Map = MAP_SHARED | MAP_ANON;
283#endif
284
285 // use anonymous mmap() to get the memory
286 Base = (unsigned char*) mmap(0, WorkSpace, Prot, Map, -1, 0);
287
288 if(Base == MAP_FAILED)
289 _error->Errno("DynamicMMap",_("Couldn't make mmap of %lu bytes"),WorkSpace);
290
291 iSize = 0;
292 return;
293 }
294#endif
295 // fallback to a static allocated space
296 Base = calloc(WorkSpace, 1);
297 iSize = 0;
298}
299 /*}}}*/
300// DynamicMMap::~DynamicMMap - Destructor /*{{{*/
301// ---------------------------------------------------------------------
302/* We truncate the file to the size of the memory data set */
303DynamicMMap::~DynamicMMap()
304{
305 if (Fd == 0)
306 {
307 if (validData() == false)
308 return;
309#ifdef _POSIX_MAPPED_FILES
310 munmap(Base, WorkSpace);
311#else
312 free(Base);
313#endif
314 return;
315 }
316
317 unsigned long long EndOfFile = iSize;
318 iSize = WorkSpace;
319 Close(false);
320 if(ftruncate(Fd->Fd(),EndOfFile) < 0)
321 _error->Errno("ftruncate", _("Failed to truncate file"));
322}
323 /*}}}*/
324// DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
325// ---------------------------------------------------------------------
326/* This allocates a block of memory aligned to the given size */
327unsigned long DynamicMMap::RawAllocate(unsigned long long Size,unsigned long Aln)
328{
329 unsigned long long Result = iSize;
330 if (Aln != 0)
331 Result += Aln - (iSize%Aln);
332
333 iSize = Result + Size;
334
335 // try to grow the buffer
336 while(Result + Size > WorkSpace)
337 {
338 if(!Grow())
339 {
340 _error->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
341 "of APT::Cache-Start. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
342 return 0;
343 }
344 }
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)
353{
354 if (unlikely(ItemSize == 0))
355 {
356 _error->Fatal("Can't allocate an item of size zero");
357 return 0;
358 }
359
360 // Look for a matching pool entry
361 Pool *I;
362 Pool *Empty = 0;
363 for (I = Pools; I != Pools + PoolCount; ++I)
364 {
365 if (I->ItemSize == 0)
366 Empty = I;
367 if (I->ItemSize == ItemSize)
368 break;
369 }
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 }
384
385 unsigned long Result = 0;
386 // Out of space, allocate some more
387 if (I->Count == 0)
388 {
389 const unsigned long size = 20*1024;
390 I->Count = size/ItemSize;
391 Pool* oldPools = Pools;
392 _error->PushToStack();
393 Result = RawAllocate(size,ItemSize);
394 bool const newError = _error->PendingError();
395 _error->MergeWithStack();
396 if (Pools != oldPools)
397 I += Pools - oldPools;
398
399 // Does the allocation failed ?
400 if (Result == 0 && newError)
401 return 0;
402 I->Start = Result;
403 }
404 else
405 Result = I->Start;
406
407 I->Count--;
408 I->Start += ItemSize;
409 return Result/ItemSize;
410}
411 /*}}}*/
412// DynamicMMap::WriteString - Write a string to the file /*{{{*/
413// ---------------------------------------------------------------------
414/* Strings are aligned to 16 bytes */
415unsigned long DynamicMMap::WriteString(const char *String,
416 unsigned long Len)
417{
418 if (Len == (unsigned long)-1)
419 Len = strlen(String);
420
421 _error->PushToStack();
422 unsigned long Result = RawAllocate(Len+1+sizeof(uint16_t),sizeof(uint16_t));
423 bool const newError = _error->PendingError();
424 _error->MergeWithStack();
425
426 if (Base == NULL || (Result == 0 && newError))
427 return 0;
428
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
436 memcpy((char *)Base + Result,String,Len);
437 ((char *)Base)[Result + Len] = 0;
438 return Result;
439}
440 /*}}}*/
441// DynamicMMap::Grow - Grow the mmap /*{{{*/
442// ---------------------------------------------------------------------
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)
458 return _error->Error(_("Unable to increase the size of the MMap as the "
459 "limit of %lu bytes is already reached."), Limit);
460 if (GrowFactor <= 0)
461 return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
462
463 unsigned long long const newSize = WorkSpace + GrowFactor;
464
465 if(Fd != 0) {
466 Fd->Seek(newSize - 1);
467 char C = 0;
468 Fd->Write(&C,sizeof(C));
469 }
470
471 unsigned long const poolOffset = Pools - ((Pool*) Base);
472
473 if ((Flags & Fallback) != Fallback) {
474#if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
475 #ifdef MREMAP_MAYMOVE
476
477 if ((Flags & Moveable) == Moveable)
478 Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
479 else
480 #endif
481 Base = mremap(Base, WorkSpace, newSize, 0);
482
483 if(Base == MAP_FAILED)
484 return false;
485#else
486 return false;
487#endif
488 } else {
489 if ((Flags & Moveable) != Moveable)
490 return false;
491
492 Base = realloc(Base, newSize);
493 if (Base == NULL)
494 return false;
495 else
496 /* Set new memory to 0 */
497 memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
498 }
499
500 Pools =(Pool*) Base + poolOffset;
501 WorkSpace = newSize;
502 return true;
503}
504 /*}}}*/