1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24: #include <sys/types.h>
25: #include <sys/mman.h>
26: #include <sys/stat.h>
27: #include <unistd.h>
28: #include <fcntl.h>
29: #include <stdlib.h>
30:
31: #include <anthy/filemap.h>
32: #include <anthy/logger.h>
33:
34: struct filemapping {
35:
36: int wr;
37:
38: void *ptr;
39:
40: size_t size;
41: };
42:
43: struct filemapping *
44: anthy_mmap(const char *fn, int wr)
45: {
46: int fd;
47: void *ptr;
48: int r;
49: struct filemapping *m;
50: struct stat st;
51: int prot;
52: int flags;
53: mode_t mode;
54:
55: if (wr) {
56: prot = PROT_READ | PROT_WRITE;
57: flags = O_RDWR;
58: mode = S_IRUSR | S_IWUSR;
59: } else {
60: prot = PROT_READ;
61: flags = O_RDONLY;
62: mode = S_IRUSR;
63: }
64:
65: fd = open(fn, flags, mode);
66:
67: if (fd == -1) {
68: anthy_log(0, "Failed to open (%s).\n", fn);
69: return NULL;
70: }
71:
72: r = fstat(fd, &st);
73: if (r == -1) {
74: anthy_log(0, "Failed to stat() (%s).\n", fn);
75: close(fd);
76: return NULL;
77: }
78: if (st.st_size == 0) {
79: anthy_log(0, "Failed to mmap 0size file (%s).\n", fn);
80: close(fd);
81: return NULL;
82: }
83:
84: ptr = mmap(NULL, st.st_size, prot, MAP_SHARED, fd, 0);
85: close(fd);
86: if (ptr == MAP_FAILED) {
87: anthy_log(0, "Failed to mmap() (%s).\n", fn);
88: return NULL;
89: }
90:
91:
92: m = malloc(sizeof(struct filemapping));
93: m->size = st.st_size;
94: m->ptr = ptr;
95: m->wr = wr;
96:
97: return m;
98: }
99:
100: void *
101: anthy_mmap_address(struct filemapping *m)
102: {
103: if (!m) {
104: return NULL;
105: }
106: return m->ptr;
107: }
108:
109: int
110: anthy_mmap_size(struct filemapping *m)
111: {
112: if (!m) {
113: return 0;
114: }
115: return m->size;
116: }
117:
118: int
119: anthy_mmap_is_writable(struct filemapping *m)
120: {
121: if (!m) {
122: return 0;
123: }
124: return m->wr;
125: }
126:
127: void
128: anthy_munmap(struct filemapping *m)
129: {
130: if (!m) {
131: return ;
132: }
133: munmap(m->ptr, m->size);
134: free(m);
135: }