File: mapfile.c

package info (click to toggle)
wraplinux 1.7-7
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 412 kB
  • sloc: ansic: 1,550; asm: 427; perl: 155; sh: 152; makefile: 89
file content (61 lines) | stat: -rw-r--r-- 1,487 bytes parent folder | download | duplicates (3)
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);
}