Blame src/driver/mdso_unit_ctx.c

cde03b
/****************************************************************/
cde03b
/*  mdso: midipix dso scavenger                                 */
cde03b
/*  Copyright (C) 2015  Z. Gilboa                               */
cde03b
/*  Released under GPLv2 and GPLv3; see COPYING.MDSO.           */
cde03b
/****************************************************************/
cde03b
cde03b
#include <stdint.h>
cde03b
#include <stddef.h>
cde03b
#include <stdlib.h>
cde03b
#include <string.h>
14073f
#include <unistd.h>
14073f
#include <errno.h>
cde03b
#include <sys/mman.h>
cde03b
cde03b
#include <mdso/mdso.h>
cde03b
#include "mdso_driver_impl.h"
cde03b
cde03b
static int mdso_free_unit_ctx_impl(struct mdso_unit_ctx_impl * ctx, int status)
cde03b
{
cde03b
	if (ctx) {
cde03b
		mdso_unmap_input(&ctx->map);
cde03b
		free(ctx);
cde03b
	}
cde03b
cde03b
	return status;
cde03b
}
cde03b
14073f
static FILE * mdso_stdin_to_tmp(void)
14073f
{
14073f
	FILE *	ftmp;
14073f
	char	buf[4096];
14073f
	ssize_t	nread;
14073f
	int	ret;
14073f
14073f
	if (!(ftmp = tmpfile()))
14073f
		return 0;
14073f
14073f
	nread = read(0,buf,sizeof(buf)-1);
14073f
14073f
	while (nread) {
14073f
		if (nread > 0) {
14073f
			buf[nread] = '\0';
14073f
			ret = fputs(buf,ftmp);
14073f
		} else
14073f
			ret = (errno == EINTR) ? 0 : -1;
14073f
14073f
		if (ret < 0) {
14073f
			fclose(ftmp);
14073f
			return 0;
14073f
		}
14073f
14073f
		nread = read(0,buf,sizeof(buf)-1);
14073f
	}
14073f
14073f
	return ftmp;
14073f
}
14073f
cde03b
int mdso_get_unit_ctx(
cde03b
	const struct mdso_driver_ctx *	dctx,
cde03b
	const char *			path,
cde03b
	struct mdso_unit_ctx **		pctx)
cde03b
{
cde03b
	struct mdso_unit_ctx_impl *	ctx;
14073f
	FILE *				ftmp;
14073f
	int				fd;
cde03b
cde03b
	if (!dctx || !(ctx = calloc(sizeof(*ctx),1)))
cde03b
		return -1;
cde03b
14073f
	if (strcmp(path,"-"))
14073f
		fd = -1;
14073f
	else if (!(ftmp = mdso_stdin_to_tmp()))
14073f
		return mdso_free_unit_ctx_impl(ctx,-1);
14073f
	else if ((fd = dup(fileno(ftmp))) < 0)
cde03b
		return mdso_free_unit_ctx_impl(ctx,-1);
14073f
	else
14073f
		fclose(ftmp);
14073f
14073f
	if (mdso_map_input(fd,path,PROT_READ,&ctx->map))
14073f
		return mdso_free_unit_ctx_impl(ctx,-1);
14073f
14073f
	if (fd > 0)
14073f
		close(fd);
cde03b
cde03b
	memcpy(&ctx->cctx,dctx->cctx,
cde03b
		sizeof(ctx->cctx));
cde03b
cde03b
	ctx->path	= path;
cde03b
cde03b
	ctx->uctx.path	= &ctx->path;
cde03b
	ctx->uctx.map	= &ctx->map;
cde03b
	ctx->uctx.cctx	= &ctx->cctx;
cde03b
cde03b
	*pctx = &ctx->uctx;
cde03b
	return 0;
cde03b
}
cde03b
cde03b
void mdso_free_unit_ctx(struct mdso_unit_ctx * ctx)
cde03b
{
cde03b
	struct mdso_unit_ctx_impl *	ictx;
cde03b
	uintptr_t			addr;
cde03b
cde03b
	if (ctx) {
cde03b
		addr = (uintptr_t)ctx - offsetof(struct mdso_unit_ctx_impl,uctx);
cde03b
		ictx = (struct mdso_unit_ctx_impl *)addr;
cde03b
		mdso_free_unit_ctx_impl(ictx,0);
cde03b
	}
cde03b
}