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