]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/mmap.cc
Don't download "optional" files not in Release :/.
[apt.git] / apt-pkg / contrib / mmap.cc
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 /* */
40 MMap::MMap(FileFd &F,unsigned long Flags) : Flags(Flags), iSize(0),
41 Base(nullptr), SyncToFd(nullptr)
42 {
43 Map(F);
44 }
45 /*}}}*/
46 // MMap::MMap - Constructor /*{{{*/
47 // ---------------------------------------------------------------------
48 /* */
49 MMap::MMap(unsigned long Flags) : Flags(Flags), iSize(0),
50 Base(nullptr), SyncToFd(nullptr)
51 {
52 }
53 /*}}}*/
54 // MMap::~MMap - Destructor /*{{{*/
55 // ---------------------------------------------------------------------
56 /* */
57 MMap::~MMap()
58 {
59 Close();
60 }
61 /*}}}*/
62 // MMap::Map - Perform the mapping /*{{{*/
63 // ---------------------------------------------------------------------
64 /* */
65 bool MMap::Map(FileFd &Fd)
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
77 if (iSize == 0)
78 return _error->Error(_("Can't mmap an empty file"));
79
80 // We can't mmap compressed fd's directly, so we need to read it completely
81 if (Fd.IsCompressed() == true)
82 {
83 if ((Flags & ReadOnly) != ReadOnly)
84 return _error->Error("Compressed file %s can only be mapped readonly", Fd.Name().c_str());
85 Base = malloc(iSize);
86 if (unlikely(Base == nullptr))
87 return _error->Errno("MMap-compressed-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
88 SyncToFd = new FileFd();
89 if (Fd.Seek(0L) == false || Fd.Read(Base, iSize) == false)
90 return _error->Error("Compressed file %s can't be read into mmap", Fd.Name().c_str());
91 return true;
92 }
93
94 // Map it.
95 Base = (Flags & Fallback) ? MAP_FAILED : mmap(0,iSize,Prot,Map,Fd.Fd(),0);
96 if (Base == MAP_FAILED)
97 {
98 if (errno == ENODEV || errno == EINVAL || (Flags & Fallback))
99 {
100 // The filesystem doesn't support this particular kind of mmap.
101 // So we allocate a buffer and read the whole file into it.
102 if ((Flags & ReadOnly) == ReadOnly)
103 {
104 // for readonly, we don't need sync, so make it simple
105 Base = malloc(iSize);
106 if (unlikely(Base == nullptr))
107 return _error->Errno("MMap-malloc", _("Couldn't make mmap of %llu bytes"), iSize);
108 SyncToFd = new FileFd();
109 return Fd.Seek(0L) && Fd.Read(Base, iSize);
110 }
111 // FIXME: Writing to compressed fd's ?
112 int const dupped_fd = dup(Fd.Fd());
113 if (dupped_fd == -1)
114 return _error->Errno("mmap", _("Couldn't duplicate file descriptor %i"), Fd.Fd());
115
116 Base = malloc(iSize);
117 if (unlikely(Base == nullptr))
118 return _error->Errno("MMap-calloc", _("Couldn't make mmap of %llu bytes"), iSize);
119 SyncToFd = new FileFd (dupped_fd);
120 if (!SyncToFd->Seek(0L) || !SyncToFd->Read(Base, iSize))
121 return false;
122 }
123 else
124 return _error->Errno("MMap-mmap", _("Couldn't make mmap of %llu bytes"), iSize);
125 }
126
127 return true;
128 }
129 /*}}}*/
130 // MMap::Close - Close the map /*{{{*/
131 // ---------------------------------------------------------------------
132 /* */
133 bool MMap::Close(bool DoSync)
134 {
135 if ((Flags & UnMapped) == UnMapped || validData() == false || iSize == 0)
136 return true;
137
138 if (DoSync == true)
139 Sync();
140
141 if (SyncToFd != NULL)
142 {
143 free(Base);
144 delete SyncToFd;
145 SyncToFd = NULL;
146 }
147 else
148 {
149 if (munmap((char *)Base, iSize) != 0)
150 _error->WarningE("mmap", _("Unable to close mmap"));
151 }
152
153 iSize = 0;
154 Base = 0;
155 return true;
156 }
157 /*}}}*/
158 // MMap::Sync - Syncronize the map with the disk /*{{{*/
159 // ---------------------------------------------------------------------
160 /* This is done in syncronous mode - the docs indicate that this will
161 not return till all IO is complete */
162 bool MMap::Sync()
163 {
164 if ((Flags & UnMapped) == UnMapped)
165 return true;
166
167 if ((Flags & ReadOnly) != ReadOnly)
168 {
169 if (SyncToFd != NULL)
170 {
171 if (!SyncToFd->Seek(0) || !SyncToFd->Write(Base, iSize))
172 return false;
173 }
174 else
175 {
176 #ifdef _POSIX_SYNCHRONIZED_IO
177 if (msync((char *)Base, iSize, MS_SYNC) < 0)
178 return _error->Errno("msync", _("Unable to synchronize mmap"));
179 #endif
180 }
181 }
182 return true;
183 }
184 /*}}}*/
185 // MMap::Sync - Syncronize a section of the file to disk /*{{{*/
186 // ---------------------------------------------------------------------
187 /* */
188 bool MMap::Sync(unsigned long Start,unsigned long Stop)
189 {
190 if ((Flags & UnMapped) == UnMapped)
191 return true;
192
193 if ((Flags & ReadOnly) != ReadOnly)
194 {
195 if (SyncToFd != 0)
196 {
197 if (!SyncToFd->Seek(Start) ||
198 !SyncToFd->Write (((char *)Base)+Start, Stop-Start))
199 return false;
200 }
201 else
202 {
203 #ifdef _POSIX_SYNCHRONIZED_IO
204 unsigned long long const PSize = sysconf(_SC_PAGESIZE);
205 Start = (Start/PSize)*PSize;
206 if (msync((char *)Base+Start, 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 /* */
218 DynamicMMap::DynamicMMap(FileFd &F,unsigned long Flags,unsigned long const &Workspace,
219 unsigned long const &Grow, unsigned long const &Limit) :
220 MMap(Flags), 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 */
252 DynamicMMap::DynamicMMap(unsigned long Flags,unsigned long const &WorkSpace,
253 unsigned long const &Grow, unsigned long const &Limit) :
254 MMap(Flags | 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 */
303 DynamicMMap::~DynamicMMap()
304 {
305 if (Fd == 0)
306 {
307 if (validData() == false)
308 return;
309 #ifdef _POSIX_MAPPED_FILES
310 if ((Flags & Fallback) != Fallback) {
311 munmap(Base, WorkSpace);
312 } else
313 #endif
314 free(Base);
315 return;
316 }
317
318 unsigned long long EndOfFile = iSize;
319 iSize = WorkSpace;
320 Close(false);
321 if(ftruncate(Fd->Fd(),EndOfFile) < 0)
322 _error->Errno("ftruncate", _("Failed to truncate file"));
323 }
324 /*}}}*/
325 // DynamicMMap::RawAllocate - Allocate a raw chunk of unaligned space /*{{{*/
326 // ---------------------------------------------------------------------
327 /* This allocates a block of memory aligned to the given size */
328 unsigned long DynamicMMap::RawAllocate(unsigned long long Size,unsigned long Aln)
329 {
330 unsigned long long Result = iSize;
331 if (Aln != 0)
332 Result += Aln - (iSize%Aln);
333
334 iSize = Result + Size;
335
336 // try to grow the buffer
337 while(Result + Size > WorkSpace)
338 {
339 if(!Grow())
340 {
341 _error->Fatal(_("Dynamic MMap ran out of room. Please increase the size "
342 "of APT::Cache-Start. Current value: %lu. (man 5 apt.conf)"), WorkSpace);
343 return 0;
344 }
345 }
346 return Result;
347 }
348 /*}}}*/
349 // DynamicMMap::Allocate - Pooled aligned allocation /*{{{*/
350 // ---------------------------------------------------------------------
351 /* This allocates an Item of size ItemSize so that it is aligned to its
352 size in the file. */
353 unsigned long DynamicMMap::Allocate(unsigned long ItemSize)
354 {
355 if (unlikely(ItemSize == 0))
356 {
357 _error->Fatal("Can't allocate an item of size zero");
358 return 0;
359 }
360
361 // Look for a matching pool entry
362 Pool *I;
363 Pool *Empty = 0;
364 for (I = Pools; I != Pools + PoolCount; ++I)
365 {
366 if (I->ItemSize == 0)
367 Empty = I;
368 if (I->ItemSize == ItemSize)
369 break;
370 }
371 // No pool is allocated, use an unallocated one
372 if (I == Pools + PoolCount)
373 {
374 // Woops, we ran out, the calling code should allocate more.
375 if (Empty == 0)
376 {
377 _error->Error("Ran out of allocation pools");
378 return 0;
379 }
380
381 I = Empty;
382 I->ItemSize = ItemSize;
383 I->Count = 0;
384 }
385
386 unsigned long Result = 0;
387 // Out of space, allocate some more
388 if (I->Count == 0)
389 {
390 const unsigned long size = 20*1024;
391 I->Count = size/ItemSize;
392 Pool* oldPools = Pools;
393 _error->PushToStack();
394 Result = RawAllocate(size,ItemSize);
395 bool const newError = _error->PendingError();
396 _error->MergeWithStack();
397 if (Pools != oldPools)
398 I += Pools - oldPools;
399
400 // Does the allocation failed ?
401 if (Result == 0 && newError)
402 return 0;
403 I->Start = Result;
404 }
405 else
406 Result = I->Start;
407
408 I->Count--;
409 I->Start += ItemSize;
410 return Result/ItemSize;
411 }
412 /*}}}*/
413 // DynamicMMap::WriteString - Write a string to the file /*{{{*/
414 // ---------------------------------------------------------------------
415 /* Strings are aligned to 16 bytes */
416 unsigned long DynamicMMap::WriteString(const char *String,
417 unsigned long Len)
418 {
419 if (Len == (unsigned long)-1)
420 Len = strlen(String);
421
422 _error->PushToStack();
423 unsigned long Result = RawAllocate(Len+1+sizeof(uint16_t),sizeof(uint16_t));
424 bool const newError = _error->PendingError();
425 _error->MergeWithStack();
426
427 if (Base == NULL || (Result == 0 && newError))
428 return 0;
429
430 if (Len >= std::numeric_limits<uint16_t>::max())
431 abort();
432
433 uint16_t LenToWrite = Len;
434 memcpy((char *)Base + Result, &LenToWrite, sizeof(LenToWrite));
435 Result += + sizeof(LenToWrite);
436
437 memcpy((char *)Base + Result,String,Len);
438 ((char *)Base)[Result + Len] = 0;
439 return Result;
440 }
441 /*}}}*/
442 // DynamicMMap::Grow - Grow the mmap /*{{{*/
443 // ---------------------------------------------------------------------
444 /* This method is a wrapper around different methods to (try to) grow
445 a mmap (or our char[]-fallback). Encounterable environments:
446 1. Moveable + !Fallback + linux -> mremap with MREMAP_MAYMOVE
447 2. Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
448 3. Moveable + Fallback -> realloc
449 4. !Moveable + !Fallback + linux -> mremap alone - which will fail in 99,9%
450 5. !Moveable + !Fallback + !linux -> not possible (forbidden by constructor)
451 6. !Moveable + Fallback -> not possible
452 [ While Moveable and Fallback stands for the equally named flags and
453 "linux" indicates a linux kernel instead of a freebsd kernel. ]
454 So what you can see here is, that a MMAP which want to be growable need
455 to be moveable to have a real chance but that this method will at least try
456 the nearly impossible 4 to grow it before it finally give up: Never say never. */
457 bool DynamicMMap::Grow() {
458 if (Limit != 0 && WorkSpace >= Limit)
459 return _error->Error(_("Unable to increase the size of the MMap as the "
460 "limit of %lu bytes is already reached."), Limit);
461 if (GrowFactor <= 0)
462 return _error->Error(_("Unable to increase size of the MMap as automatic growing is disabled by user."));
463
464 unsigned long long const newSize = WorkSpace + GrowFactor;
465
466 if(Fd != 0) {
467 Fd->Seek(newSize - 1);
468 char C = 0;
469 Fd->Write(&C,sizeof(C));
470 }
471
472 unsigned long const poolOffset = Pools - ((Pool*) Base);
473
474 if ((Flags & Fallback) != Fallback) {
475 #if defined(_POSIX_MAPPED_FILES) && defined(__linux__)
476 #ifdef MREMAP_MAYMOVE
477
478 if ((Flags & Moveable) == Moveable)
479 Base = mremap(Base, WorkSpace, newSize, MREMAP_MAYMOVE);
480 else
481 #endif
482 Base = mremap(Base, WorkSpace, newSize, 0);
483
484 if(Base == MAP_FAILED)
485 return false;
486 #else
487 return false;
488 #endif
489 } else {
490 if ((Flags & Moveable) != Moveable)
491 return false;
492
493 auto Temp = realloc(Base, newSize);
494 if (Temp == NULL)
495 return false;
496 else {
497 Base = Temp;
498 /* Set new memory to 0 */
499 memset((char*)Base + WorkSpace, 0, newSize - WorkSpace);
500 }
501 }
502
503 Pools =(Pool*) Base + poolOffset;
504 WorkSpace = newSize;
505 return true;
506 }
507 /*}}}*/