Blame src/internal/toksvc_memfn_impl.c

69c770
/*********************************************************/
69c770
/*  toksvc: a framework-native token broker service      */
d91fa0
/*  Copyright (C) 2020  SysDeer Technologies, LLC        */
69c770
/*  Released under GPLv2 and GPLv3; see COPYING.TOKSVC.  */
69c770
/*********************************************************/
69c770
69c770
#include <stddef.h>
69c770
#include <ntapi/ntapi.h>
69c770
#include "toksvc_memfn_impl.h"
69c770
#include "toksvc_driver_impl.h"
69c770
69c770
void * toks_calloc(size_t n, size_t size)
69c770
{
69c770
	void *                      addr;
69c770
	size_t                      bsize;
69c770
	struct toks_memory_block *  block;
69c770
69c770
	if (!n || (size > (size_t)(-1) / n))
69c770
		return 0;
69c770
69c770
	size *= n;
69c770
	size += 0xf;
69c770
	size &= ~(size_t)0xf;
69c770
69c770
	addr  = 0;
69c770
	bsize = size + sizeof(*block);
69c770
69c770
	if (ntapi->zw_allocate_virtual_memory(
69c770
			NT_CURRENT_PROCESS_HANDLE,
69c770
			&addr,
69c770
			0,
69c770
			&bsize,
69c770
			NT_MEM_COMMIT,
69c770
			NT_PAGE_READWRITE))
69c770
		return 0;
69c770
69c770
	block        = (struct toks_memory_block *)addr;
69c770
	block->addr  = addr;
69c770
	block->size  = bsize;
69c770
	block->used  = size + offsetof(struct toks_memory_block,buffer);
69c770
	block->avail = bsize - block->used;
69c770
69c770
	return (char *)addr + offsetof(struct toks_memory_block,buffer);
69c770
}
69c770
69c770
void * toks_balloc(
69c770
	struct toks_memory_block * cache,
69c770
	struct toks_memory_block * block,
69c770
	size_t n, size_t size)
69c770
{
69c770
	void * addr;
69c770
69c770
	if (!n || (size > (size_t)(-1) / n))
69c770
		return 0;
69c770
69c770
	if (!cache || !cache->addr)
69c770
		return toks_calloc(n,size);
69c770
69c770
	size *= n;
69c770
	size += 0xf;
69c770
	size &= ~(size_t)0xf;
69c770
69c770
	if (size > block->avail)
69c770
		return toks_calloc(1,size);
69c770
69c770
	/* cached */
69c770
	addr          = &block->buffer[block->used / sizeof(size_t)];
69c770
	block->used  += size;
69c770
	block->avail -= size;
69c770
69c770
	return addr;
69c770
}
69c770
69c770
void toks_free(void * addr)
69c770
{
69c770
	char *                      baddr;
69c770
	size_t                      size;
69c770
	struct toks_memory_block *  block;
69c770
69c770
	baddr  = addr;
69c770
	baddr -= offsetof(struct toks_memory_block,buffer);
69c770
69c770
	block = (struct toks_memory_block *)baddr;
69c770
	addr  = block->addr;
69c770
	size  = block->size;
69c770
69c770
	ntapi->zw_free_virtual_memory(
69c770
		NT_CURRENT_PROCESS_HANDLE,
69c770
		&addr,
69c770
		&size,
69c770
		NT_MEM_RELEASE);
69c770
}