1/*****************************************************************************\
2*  _  _       _          _              ___                                   *
3* | || | ___ | |_  _ __ | | _  _  __ _ |_  )                                  *
4* | __ |/ _ \|  _|| '_ \| || || |/ _` | / /                                   *
5* |_||_|\___/ \__|| .__/|_| \_,_|\__, |/___|                                  *
6*                 |_|            |___/                                        *
7\*****************************************************************************/
8
9#include <string.h>
10#include <stdlib.h>
11#include <fcntl.h>
12#include <unistd.h>
13#include <sys/types.h>
14#include <sys/stat.h>
15#include <sys/mman.h>
16
17#include "filemap_utils.h"
18
19/**
20 * Basic open/mmap wrapper to make things simpler.
21 *
22 * @1 Filename of the mmaped file
23 * @2 Pointer to filemap structure
24 *
25 * Returns: 0 if success, 1 otherwise
26 */
27int map_file(const char *filename, struct filemap_t *filemap) {
28	struct stat statbuf;
29
30	filemap->fd = open(filename, O_RDONLY);
31	if (filemap->fd == -1) {
32		return 1;
33	}
34
35	if (fstat(filemap->fd, &statbuf)) {
36		close(filemap->fd);
37		return 1;
38	}
39
40	filemap->size = statbuf.st_size;
41
42	filemap->map = mmap(0, filemap->size, PROT_READ, MAP_SHARED, filemap->fd, 0);
43	if (filemap->map == MAP_FAILED) {
44		close(filemap->fd);
45		return 1;
46	}
47
48	return 0;
49}
50
51/**
52 * Basic close/munmap wrapper.
53 *
54 * @1 Pointer to filemap structure
55 *
56 * Returns: always 0
57 */
58int unmap_file(struct filemap_t *filemap) {
59	munmap(filemap->map, filemap->size);
60	close(filemap->fd);
61
62	return 0;
63}
64