firasuke / cross / slibtool

Forked from cross/slibtool a month ago
Clone

Blame src/driver/slbt_unit_ctx.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 <stddef.h>
9ca8c4
#include <stdlib.h>
9ca8c4
#include <string.h>
9ca8c4
#include <sys/mman.h>
9ca8c4
9ca8c4
#include <slibtool/slibtool.h>
9ca8c4
#include "slibtool_driver_impl.h"
9ca8c4
9ca8c4
static int slbt_free_unit_ctx_impl(struct slbt_unit_ctx_impl * ctx, int status)
9ca8c4
{
9ca8c4
	if (ctx) {
9ca8c4
		slbt_unmap_input(&ctx->map);
9ca8c4
		free(ctx);
9ca8c4
	}
9ca8c4
9ca8c4
	return status;
9ca8c4
}
9ca8c4
9ca8c4
int slbt_get_unit_ctx(
9ca8c4
	const struct slbt_driver_ctx *	dctx,
9ca8c4
	const char *			path,
9ca8c4
	struct slbt_unit_ctx **		pctx)
9ca8c4
{
9ca8c4
	struct slbt_unit_ctx_impl *	ctx;
9ca8c4
9ca8c4
	if (!dctx || !(ctx = calloc(1,sizeof(*ctx))))
9ca8c4
		return -1;
9ca8c4
9ca8c4
	if (slbt_map_input(-1,path,PROT_READ,&ctx->map))
9ca8c4
		return slbt_free_unit_ctx_impl(ctx,-1);
9ca8c4
9ca8c4
	memcpy(&ctx->cctx,dctx->cctx,
9ca8c4
		sizeof(ctx->cctx));
9ca8c4
9ca8c4
	ctx->path	= path;
9ca8c4
9ca8c4
	ctx->uctx.path	= &ctx->path;
9ca8c4
	ctx->uctx.map	= &ctx->map;
9ca8c4
	ctx->uctx.cctx	= &ctx->cctx;
9ca8c4
9ca8c4
	*pctx = &ctx->uctx;
9ca8c4
	return 0;
9ca8c4
}
9ca8c4
9ca8c4
void slbt_free_unit_ctx(struct slbt_unit_ctx * ctx)
9ca8c4
{
9ca8c4
	struct slbt_unit_ctx_impl *	ictx;
9ca8c4
	uintptr_t			addr;
9ca8c4
9ca8c4
	if (ctx) {
9ca8c4
		addr = (uintptr_t)ctx - offsetof(struct slbt_unit_ctx_impl,uctx);
9ca8c4
		ictx = (struct slbt_unit_ctx_impl *)addr;
9ca8c4
		slbt_free_unit_ctx_impl(ictx,0);
9ca8c4
	}
9ca8c4
}