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