• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include "SkMMapStream.h"
2 
3 #include <unistd.h>
4 #include <sys/mman.h>
5 #include <fcntl.h>
6 #include <errno.h>
7 
SkMMAPStream(const char filename[])8 SkMMAPStream::SkMMAPStream(const char filename[])
9 {
10     fFildes = -1;   // initialize to failure case
11 
12     int fildes = open(filename, O_RDONLY);
13     if (fildes < 0)
14     {
15         SkDEBUGF(("---- failed to open(%s) for mmap stream error=%d\n", filename, errno));
16         return;
17     }
18 
19     off_t offset = lseek(fildes, 0, SEEK_END);    // find the file size
20     if (offset == -1)
21     {
22         SkDEBUGF(("---- failed to lseek(%s) for mmap stream error=%d\n", filename, errno));
23         close(fildes);
24         return;
25     }
26     (void)lseek(fildes, 0, SEEK_SET);   // restore file offset to beginning
27 
28     // to avoid a 64bit->32bit warning, I explicitly create a size_t size
29     size_t size = static_cast<size_t>(offset);
30 
31     void* addr = mmap(NULL, size, PROT_READ, MAP_SHARED, fildes, 0);
32     if (MAP_FAILED == addr)
33     {
34         SkDEBUGF(("---- failed to mmap(%s) for mmap stream error=%d\n", filename, errno));
35         close(fildes);
36         return;
37     }
38 
39     this->INHERITED::setMemory(addr, size);
40 
41     fFildes = fildes;
42     fAddr = addr;
43     fSize = size;
44 }
45 
~SkMMAPStream()46 SkMMAPStream::~SkMMAPStream()
47 {
48     this->closeMMap();
49 }
50 
setMemory(const void * data,size_t length,bool copyData)51 void SkMMAPStream::setMemory(const void* data, size_t length, bool copyData)
52 {
53     this->closeMMap();
54     this->INHERITED::setMemory(data, length, copyData);
55 }
56 
closeMMap()57 void SkMMAPStream::closeMMap()
58 {
59     if (fFildes >= 0)
60     {
61         munmap(fAddr, fSize);
62         close(fFildes);
63         fFildes = -1;
64     }
65 }
66 
67