Blame src/helper/slbt_map_input.c

e99ba2
/*******************************************************************/
e99ba2
/*  slibtool: a skinny libtool implementation, written in C        */
e99ba2
/*  Copyright (C) 2015--2023  SysDeer Technologies, LLC            */
e99ba2
/*  Released under the Standard MIT License; see COPYING.SLIBTOOL. */
e99ba2
/*******************************************************************/
e99ba2
e99ba2
#include <stdint.h>
e99ba2
#include <stdbool.h>
e99ba2
#include <unistd.h>
e99ba2
#include <fcntl.h>
e99ba2
#include <sys/mman.h>
e99ba2
#include <sys/types.h>
e99ba2
#include <sys/stat.h>
e99ba2
e99ba2
#include <slibtool/slibtool.h>
e99ba2
#include "slibtool_driver_impl.h"
e99ba2
#include "slibtool_errinfo_impl.h"
e99ba2
e99ba2
int slbt_map_input(
e99ba2
	const struct slbt_driver_ctx *	dctx,
e99ba2
	int				fd,
e99ba2
	const char *			path,
e99ba2
	int				prot,
e99ba2
	struct slbt_input *		map)
e99ba2
{
e99ba2
	int		ret;
e99ba2
	struct stat	st;
e99ba2
	bool		fnew;
e99ba2
	int		fdcwd;
e99ba2
e99ba2
	fdcwd = slbt_driver_fdcwd(dctx);
e99ba2
e99ba2
	if ((fnew = (fd < 0)))
e99ba2
		fd  = openat(fdcwd,path,O_RDONLY | O_CLOEXEC);
e99ba2
e99ba2
	if (fd < 0)
e99ba2
		return SLBT_SYSTEM_ERROR(dctx,path);
e99ba2
e99ba2
	if ((ret = fstat(fd,&st) < 0) && fnew)
e99ba2
		close(fd);
e99ba2
e99ba2
	else if ((st.st_size == 0) && fnew)
e99ba2
		close(fd);
e99ba2
e99ba2
	if (ret < 0)
e99ba2
		return SLBT_SYSTEM_ERROR(dctx,path);
e99ba2
e99ba2
	if (st.st_size == 0) {
e99ba2
		map->size = 0;
e99ba2
		map->addr = 0;
e99ba2
	} else {
e99ba2
		map->size = st.st_size;
e99ba2
		map->addr = mmap(0,map->size,prot,MAP_PRIVATE,fd,0);
e99ba2
	}
e99ba2
e99ba2
	if (fnew)
e99ba2
		close(fd);
e99ba2
e99ba2
	return (map->addr == MAP_FAILED)
e99ba2
		? SLBT_SYSTEM_ERROR(dctx,path)
e99ba2
		: 0;
e99ba2
}
e99ba2
e99ba2
int slbt_unmap_input(struct slbt_input * map)
e99ba2
{
e99ba2
	return map->size ? munmap(map->addr,map->size) : 0;
e99ba2
}