firasuke / cross / slibtool

Forked from cross/slibtool 3 months ago
Clone

Blame src/logic/slbt_map_input.c

9ca8c4
/*******************************************************************/
9ca8c4
/*  slibtool: a skinny libtool implementation, written in C        */
9ca8c4
/*  Copyright (C) 2016  Z. Gilboa                                  */
9ca8c4
/*  Released under the Standard MIT License; see COPYING.SLIBTOOL. */
9ca8c4
/*******************************************************************/
9ca8c4
9ca8c4
#include <stdint.h>
9ca8c4
#include <stdbool.h>
9ca8c4
#include <unistd.h>
9ca8c4
#include <fcntl.h>
9ca8c4
#include <sys/mman.h>
9ca8c4
#include <sys/types.h>
9ca8c4
#include <sys/stat.h>
9ca8c4
9ca8c4
#include <slibtool/slibtool.h>
9ca8c4
9ca8c4
int slbt_map_input(
9ca8c4
	int			fd,
9ca8c4
	const char *		path,
9ca8c4
	int			prot,
9ca8c4
	struct slbt_input *	map)
9ca8c4
{
9ca8c4
	struct stat	st;
9ca8c4
	bool		fnew;
9ca8c4
	int		ret;
9ca8c4
9ca8c4
	if ((fnew = (fd < 0)))
9ca8c4
		fd  = open(path,O_RDONLY | O_CLOEXEC);
9ca8c4
9ca8c4
	if (fd < 0)
9ca8c4
		return -1;
9ca8c4
9ca8c4
	if ((ret = fstat(fd,&st) < 0) && fnew)
9ca8c4
		close(fd);
9ca8c4
9ca8c4
	if (ret < 0)
9ca8c4
		return -1;
9ca8c4
9ca8c4
	map->size = st.st_size;
9ca8c4
	map->addr = mmap(0,map->size,prot,MAP_PRIVATE,fd,0);
9ca8c4
9ca8c4
	if (fnew)
9ca8c4
		close(fd);
9ca8c4
9ca8c4
	return (map->addr == MAP_FAILED) ? -1 : 0;
9ca8c4
}
9ca8c4
9ca8c4
int slbt_unmap_input(struct slbt_input * map)
9ca8c4
{
9ca8c4
	return munmap(map->addr,map->size);
9ca8c4
}