]> git.saurik.com Git - apple/system_cmds.git/blob - CPPUtil/UtilMappedFile.cpp
acc71bd6929ea70a2262fb625e4973b7111e3e9e
[apple/system_cmds.git] / CPPUtil / UtilMappedFile.cpp
1 //
2 // UtilMappedFile.cpp
3 // CPPUtil
4 //
5 // Created by James McIlree on 4/19/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
7 //
8
9 #include "CPPUtil.h"
10
11 #include <sys/mman.h>
12
13 BEGIN_UTIL_NAMESPACE
14
15 static int open_fd(const char* path, size_t& file_size)
16 {
17 int fd = open(path, O_RDONLY, 0);
18 if(fd >= 0) {
19 struct stat data;
20 if (fstat(fd, &data) == 0) {
21 if (S_ISREG(data.st_mode)) {
22 // Is it zero sized?
23 if (data.st_size > 0) {
24 file_size = (size_t)data.st_size;
25 return fd;
26 }
27 }
28 }
29 close(fd);
30 }
31
32 return -1;
33 }
34
35 MappedFile::MappedFile(const char* path) :
36 _address(NULL),
37 _size(0)
38 {
39 ASSERT(path, "Sanity");
40 int fd = open_fd(path, _size);
41 if (fd >= 0) {
42 _address = (unsigned char*)mmap(NULL, _size, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0);
43 if (_address == (void*)-1) {
44 _address = NULL;
45 }
46 close(fd);
47 }
48 }
49
50 MappedFile::~MappedFile()
51 {
52 if (_address != NULL) {
53 munmap(_address, _size);
54 }
55 }
56
57 END_UTIL_NAMESPACE