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