1 #include "stream.h"
2 
3 #include <sys/types.h>
4 #include <sys/stat.h>
5 
6 #include <unistd.h>
7 #include <fcntl.h>
8 
9 #include "sys-mmap.h"
10 
11 #ifndef O_BINARY
12 # define O_BINARY 0
13 #endif
14 
stream_open(stream * f,buffer * fn)15 int stream_open(stream *f, buffer *fn) {
16 	struct stat st;
17 #ifdef HAVE_MMAP
18 	int fd;
19 #elif defined __WIN32
20 	HANDLE *fh, *mh;
21 	void *p;
22 #endif
23 
24 	f->start = NULL;
25 
26 	if (-1 == stat(fn->ptr, &st)) {
27 		return -1;
28 	}
29 
30 	f->size = st.st_size;
31 
32 #ifdef HAVE_MMAP
33 	if (-1 == (fd = open(fn->ptr, O_RDONLY | O_BINARY))) {
34 		return -1;
35 	}
36 
37 	f->start = mmap(NULL, f->size, PROT_READ, MAP_SHARED, fd, 0);
38 
39 	close(fd);
40 
41 	if (MAP_FAILED == f->start) {
42 		return -1;
43 	}
44 
45 #elif defined __WIN32
46 	fh = CreateFile(fn->ptr,
47 			GENERIC_READ,
48 			FILE_SHARE_READ,
49 			NULL,
50 			OPEN_EXISTING,
51 			FILE_ATTRIBUTE_READONLY,
52 			NULL);
53 
54 	if (!fh) return -1;
55 
56 	mh = CreateFileMapping( fh,
57 			NULL,
58 			PAGE_READONLY,
59 			(sizeof(off_t) > 4) ? f->size >> 32 : 0,
60 			f->size & 0xffffffff,
61 			NULL);
62 
63 	if (!mh) {
64 /*
65 		LPVOID lpMsgBuf;
66 		FormatMessage(
67 		        FORMAT_MESSAGE_ALLOCATE_BUFFER |
68 		        FORMAT_MESSAGE_FROM_SYSTEM,
69 		        NULL,
70 		        GetLastError(),
71 		        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
72 		        (LPTSTR) &lpMsgBuf,
73 		        0, NULL );
74 */
75 		return -1;
76 	}
77 
78 	p = MapViewOfFile(mh,
79 			FILE_MAP_READ,
80 			0,
81 			0,
82 			0);
83 	CloseHandle(mh);
84 	CloseHandle(fh);
85 
86 	f->start = p;
87 #else
88 # error no mmap found
89 #endif
90 
91 	return 0;
92 }
93 
stream_close(stream * f)94 int stream_close(stream *f) {
95 #ifdef HAVE_MMAP
96 	if (f->start) munmap(f->start, f->size);
97 #elif defined(__WIN32)
98 	if (f->start) UnmapViewOfFile(f->start);
99 #endif
100 
101 	f->start = NULL;
102 
103 	return 0;
104 }
105