map.c 1.45 KB
Newer Older
Vicent Marti committed
1
/*
Edward Thomson committed
2
 * Copyright (C) the libgit2 contributors. All rights reserved.
Vicent Marti committed
3 4 5 6
 *
 * This file is part of libgit2, distributed under the GNU GPL v2 with
 * a Linking Exception. For full terms see the included COPYING file.
 */
7

8
#include "git2_util.h"
9

10
#if !defined(GIT_WIN32) && !defined(NO_MMAP)
11 12 13

#include "map.h"
#include <sys/mman.h>
14
#include <unistd.h>
15 16
#include <errno.h>

17
int git__page_size(size_t *page_size)
18
{
19 20
	long sc_page_size = sysconf(_SC_PAGE_SIZE);
	if (sc_page_size < 0) {
21
		git_error_set(GIT_ERROR_OS, "can't determine system page size");
22 23 24 25
		return -1;
	}
	*page_size = (size_t) sc_page_size;
	return 0;
26 27
}

28 29 30 31 32
int git__mmap_alignment(size_t *alignment)
{
  return git__page_size(alignment);
}

33
int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, off64_t offset)
34
{
35
	int mprot = PROT_READ;
36 37
	int mflag = 0;

38
	GIT_MMAP_VALIDATE(out, len, prot, flags);
39 40 41 42 43

	out->data = NULL;
	out->len = 0;

	if (prot & GIT_PROT_WRITE)
44
		mprot |= PROT_WRITE;
45 46 47 48 49

	if ((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED)
		mflag = MAP_SHARED;
	else if ((flags & GIT_MAP_TYPE) == GIT_MAP_PRIVATE)
		mflag = MAP_PRIVATE;
50 51
	else
		mflag = MAP_SHARED;
52

53
	out->data = mmap(NULL, len, mprot, mflag, fd, offset);
54

55
	if (!out->data || out->data == MAP_FAILED) {
56
		git_error_set(GIT_ERROR_OS, "failed to mmap. Could not write data");
57
		return -1;
58 59 60
	}

	out->len = len;
61

62
	return 0;
63 64
}

Vicent Marti committed
65
int p_munmap(git_map *map)
66
{
Edward Thomson committed
67
	GIT_ASSERT_ARG(map);
68
	munmap(map->data, map->len);
69 70
	map->data = NULL;
	map->len = 0;
71

72
	return 0;
73 74
}

75
#endif
76