summaryrefslogtreecommitdiffstats
path: root/src/lib/mmap-util.c
blob: 87542266fd67956e1c4389c383a38b6c2ada45ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* Copyright (c) 2002-2018 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "mmap-util.h"

#include <sys/stat.h>

void *mmap_file(int fd, size_t *length, int prot)
{
	struct stat st;

	if (fstat(fd, &st) < 0)
		return MAP_FAILED;

#if OFF_T_MAX > SSIZE_T_MAX
	if (st.st_size > SSIZE_T_MAX) {
		/* too large file to map into memory */
		errno = EFBIG;
		return MAP_FAILED;
	}
#endif

	*length = (size_t)st.st_size;
	if (*length == 0)
		return NULL;

	i_assert(*length > 0 && *length < SSIZE_T_MAX);

	return mmap(NULL, *length, prot, MAP_SHARED, fd, 0);
}

void *mmap_ro_file(int fd, size_t *length)
{
	return mmap_file(fd, length, PROT_READ);
}

void *mmap_rw_file(int fd, size_t *length)
{
	return mmap_file(fd, length, PROT_READ | PROT_WRITE);
}

#undef madvise
int my_madvise(void *start ATTR_UNUSED, size_t length ATTR_UNUSED,
	       int advice ATTR_UNUSED)
{
#ifdef HAVE_MADVISE
	/* Ignore ENOSYS errors, which happen if the kernel hasn't implemented
	   the syscall even if libc has. */
	if (madvise(start, length, advice) < 0 && errno != ENOSYS)
		return -1;
#endif
	return 0;
}

size_t mmap_get_page_size(void)
{
	static size_t size = 0;

	if (size != 0)
		return size;
	size = getpagesize();
	return size;
}