sortix-mirror/libc/stdlib/free.c

85 lines
2.1 KiB
C
Raw Normal View History

/*
* Copyright (c) 2011, 2012, 2013, 2014, 2015, 2022 Jonas 'Sortie' Termansen.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* stdlib/free.c
* Returns a chunk of memory to the dynamic memory heap.
*/
2013-10-22 22:40:10 +00:00
#include <malloc.h>
#include <stdlib.h>
#if defined(HEAP_NO_ASSERT)
#define __heap_verify() ((void) 0)
#undef assert
#define assert(x) do { ((void) 0); } while ( 0 )
#endif
2015-10-09 13:28:16 +00:00
#if !defined(HEAP_GUARD_DEBUG)
2016-02-28 11:11:02 +00:00
void free(void* addr)
2013-10-22 22:40:10 +00:00
{
if ( !addr )
return;
__heap_lock();
__heap_verify();
// Retrieve the chunk that contains this allocation.
struct heap_chunk* chunk = heap_data_to_chunk((uint8_t*) addr);
#ifdef __TRACE_ALLOCATION_SITES
if ( MAGIC_IS_ALLOCATION_SITE(chunk->chunk_magic) )
{
struct __allocation_site* allocation_site =
ALLOCATION_SITE_OF_MAGIC(chunk->chunk_magic);
allocation_site->current_size -= chunk->chunk_size;
allocation_site->allocations--;
}
#endif
2013-10-22 22:40:10 +00:00
// Return the chunk to the heap.
heap_insert_chunk(chunk);
// Combine the chunk with its left and right neighbors if they are unused.
heap_chunk_combine_neighbors(chunk);
__heap_verify();
__heap_unlock();
}
2015-10-09 13:28:16 +00:00
#else
#include <sys/mman.h>
2016-02-28 11:11:02 +00:00
#ifdef __is_sortix_libk
#include <libk.h>
2015-10-09 13:28:16 +00:00
#endif
2016-02-28 11:11:02 +00:00
void free(void* addr)
2015-10-09 13:28:16 +00:00
{
if ( !addr )
return;
struct heap_alloc* alloc_ptr =
(struct heap_alloc*) HEAP_ALIGN_PAGEDOWN((uintptr_t) addr - 16);
2016-02-28 11:11:02 +00:00
#ifdef __is_sortix_libk
libk_munmap((void*) alloc_ptr->from, alloc_ptr->size);
#else
2015-10-09 13:28:16 +00:00
munmap((void*) alloc_ptr->from, alloc_ptr->size);
#endif
}
#endif