libk  Artifact [6a14dc9781]

Artifact 6a14dc9781b431e96ce4284bb1d8513a731d34e29f7e390be4783f7d580f4d3b:


#include <k/mem.h>
#include <k/core.h>
#include <k/def.h>
#include <k/type.h>
#include <posix.h>
/* heapf.c - kmheapf() "heap free"
 * ~ lexi hale <lexi@hale.su>
 * kmheapf() frees a region on the heap à la libc free()
 * see also: kmheapa() "heap alloc"
 */

/* we define all platform functions here,
 * whether or not they're for the correct
 * platform - only the ones actually called
 * by the generated code will be linked,
 * linker errors are our friend here! */
extern int kmem_platform_munmap(void* addr, unsigned long sz);

kmcond kmheapf(void* ptr) {
	/* take an object allocated on the heap and free it,
	 * returning kmcond_ok on success or an appropriate
	 * value on failure. */
	struct kmbox* header = (kmbox*)
		(((ubyte*)ptr) - sizeof (kmbox));
	sz const total = header -> size + sizeof (kmbox);

	if (header -> kind != kmkind_heap) return kmcond_mismatch;
#	ifdef KFenv_posix
		/* currently allocation is handled on posix by naive use
		 * of MAP_ANONYMOUS. munmap needs to be told the size of
		 * the region to unmap (free), which kmheapa() stores at
		 * (ptr - sizeof sz). see kmheap.c for details. */

		if(kmem_platform_munmap(header, total) == -1) {
			/* we don't need to bother recovering errno;
			 * there's only one possible munmap error */
			return kmcond_bad_address;
		}

#	else
		Knoimpl(kmheapa,KVos);
#		error missing implementation
#	endif
	return kmcond_ok;
}