summaryrefslogtreecommitdiffstats
path: root/mapfile.c
blob: 91db71b3e1b179de695b8fd75bc8417c01c7b46f (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
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2008 rPath, Inc. - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 *   Boston MA 02110-1301, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * mapfile.c
 *
 * Memory-map a file, and/or read it into a memory buffer.
 * If the "writable" flag is set, return a writable memory
 * buffer, *not* one which writes back to the file!
 *
 * Note: if this is modified to use a buffer, always round the buffer
 * size up to at least a dword boundary.
 */

#include "wraplinux.h"

#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>

void *mapfile(int fd, size_t *len, bool writable)
{
	struct stat st;
	void *ptr;
	int prot, flags;

	if (fstat(fd, &st))
		return NULL;

	*len = st.st_size;

	if (writable) {
		prot  = PROT_READ|PROT_WRITE;
		flags = MAP_PRIVATE;
	} else {
		prot  = PROT_READ;
		flags = MAP_SHARED;
	}

	ptr = mmap(NULL, st.st_size, prot, flags, fd, 0);

	return (ptr == MAP_FAILED) ? NULL : ptr;
}

void unmapfile(int fd, void *ptr, size_t len)
{
	if (ptr)
		munmap(ptr, len);
	if (fd >= 0)
		close(fd);
}