map.c 2.39 KB
Newer Older
Vicent Marti committed
1
/*
schu committed
2
 * Copyright (C) 2009-2012 the libgit2 contributors
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 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

#include "map.h"
#include <errno.h>


static DWORD get_page_size(void)
{
	static DWORD page_size;
	SYSTEM_INFO sys;

	if (!page_size) {
		GetSystemInfo(&sys);
		page_size = sys.dwAllocationGranularity;
	}

	return page_size;
}

Vicent Marti committed
25
int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, git_off_t offset)
26 27 28 29 30 31
{
	HANDLE fh = (HANDLE)_get_osfhandle(fd);
	DWORD page_size = get_page_size();
	DWORD fmap_prot = 0;
	DWORD view_prot = 0;
	DWORD off_low = 0;
Vicent Marti committed
32
	DWORD off_hi = 0;
33 34
	git_off_t page_start;
	git_off_t page_offset;
35

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

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

	if (fh == INVALID_HANDLE_VALUE) {
		errno = EBADF;
44 45
		giterr_set(GITERR_OS, "Failed to mmap. Invalid handle value");
		return -1;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
	}

	if (prot & GIT_PROT_WRITE)
		fmap_prot |= PAGE_READWRITE;
	else if (prot & GIT_PROT_READ)
		fmap_prot |= PAGE_READONLY;

	if (prot & GIT_PROT_WRITE)
		view_prot |= FILE_MAP_WRITE;
	if (prot & GIT_PROT_READ)
		view_prot |= FILE_MAP_READ;

	page_start = (offset / page_size) * page_size;
	page_offset = offset - page_start;

Vicent Marti committed
61
	if (page_offset != 0) { /* offset must be multiple of page size */
62
		errno = EINVAL;
63 64
		giterr_set(GITERR_OS, "Failed to mmap. Offset must be multiple of page size");
		return -1;
65 66 67 68
	}

	out->fmh = CreateFileMapping(fh, NULL, fmap_prot, 0, 0, NULL);
	if (!out->fmh || out->fmh == INVALID_HANDLE_VALUE) {
69
		giterr_set(GITERR_OS, "Failed to mmap. Invalid handle value");
70
		out->fmh = NULL;
71
		return -1;
72 73
	}

74
	assert(sizeof(git_off_t) == 8);
75

76
	off_low = (DWORD)(page_start);
77
	off_hi = (DWORD)(page_start >> 32);
78 79
	out->data = MapViewOfFile(out->fmh, view_prot, off_hi, off_low, len);
	if (!out->data) {
80
		giterr_set(GITERR_OS, "Failed to mmap. No data written");
81 82
		CloseHandle(out->fmh);
		out->fmh = NULL;
83
		return -1;
84 85 86
	}
	out->len = len;

87
	return 0;
88 89
}

Vicent Marti committed
90
int p_munmap(git_map *map)
91
{
92
	int error = 0;
93

94
	assert(map != NULL);
95 96 97

	if (map->data) {
		if (!UnmapViewOfFile(map->data)) {
98 99
			giterr_set(GITERR_OS, "Failed to munmap. Could not unmap view of file");
			error = -1;
100 101 102 103 104 105
		}
		map->data = NULL;
	}

	if (map->fmh) {
		if (!CloseHandle(map->fmh)) {
106 107
			giterr_set(GITERR_OS, "Failed to munmap. Could not close handle");
			error = -1;
108 109 110 111
		}
		map->fmh = NULL;
	}

112
	return error;
113 114 115
}