/* ----------------------------------------------------------------------- *
 *
 *   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);
}
