Blame src/logic/pe_map_raw_image.c

e2e2c2
/***************************************************************/
e2e2c2
/*  perk: PE Resource Kit                                      */
463997
/*  Copyright (C) 2015--2021  Z. Gilboa                        */
e2e2c2
/*  Released under GPLv2 and GPLv3; see COPYING.PERK.          */
e2e2c2
/***************************************************************/
e2e2c2
c0fbae
#include <stdint.h>
fa22b4
#include <stdbool.h>
c0fbae
#include <unistd.h>
c0fbae
#include <fcntl.h>
c0fbae
#include <sys/mman.h>
c0fbae
#include <sys/types.h>
c0fbae
#include <sys/stat.h>
c0fbae
c0fbae
#include <perk/perk.h>
b4fb20
#include "perk_driver_impl.h"
9a46b6
#include "perk_errinfo_impl.h"
c0fbae
2b7f36
int pe_map_raw_image(
9a46b6
	const struct pe_driver_ctx *	dctx,
9a46b6
	int				fd,
9a46b6
	const char *			path,
9a46b6
	int				prot,
9a46b6
	struct pe_raw_image *		map)
c0fbae
{
b4fb20
	int		ret;
ce59ae
	struct stat	st;
fa22b4
	bool		fnew;
b4fb20
	int		fdcwd;
b4fb20
b4fb20
	fdcwd = pe_driver_fdcwd(dctx);
c0fbae
e62c17
	if ((fnew = (fd < 0)))
b4fb20
		fd  = openat(fdcwd,path,O_RDONLY | O_CLOEXEC);
c0fbae
b46e6f
	if (fd < 0)
9a46b6
		return PERK_SYSTEM_ERROR(dctx);
b46e6f
ce59ae
	if ((ret = fstat(fd,&st) < 0) && fnew)
b46e6f
		close(fd);
b46e6f
841928
	else if ((st.st_size == 0) && fnew)
841928
		close(fd);
841928
b46e6f
	if (ret < 0)
9a46b6
		return PERK_SYSTEM_ERROR(dctx);
c0fbae
841928
	else if (st.st_size == 0)
acad6b
		return PERK_CUSTOM_ERROR(
acad6b
			dctx,PERK_ERR_IMAGE_SIZE_ZERO);
841928
ed06fb
	map->map_size = st.st_size;
ed06fb
	map->map_addr = mmap(0,map->map_size,prot,MAP_PRIVATE,fd,0);
c0fbae
fa22b4
	if (fnew)
fa22b4
		close(fd);
c0fbae
ed06fb
	return (map->map_addr == MAP_FAILED)
9a46b6
		? PERK_SYSTEM_ERROR(dctx)
9a46b6
		: 0;
c0fbae
}
c0fbae
2b7f36
int pe_unmap_raw_image(struct pe_raw_image * map)
c0fbae
{
ed06fb
	return munmap(map->map_addr,map->map_size);
b5f7f5
}