1
0
Fork 0
mirror of https://gitlab.com/sortix/sortix.git synced 2023-02-13 20:55:38 -05:00
sortix--sortix/libc/stdlib/free.c

75 lines
1.9 KiB
C
Raw Normal View History

/*
* Copyright (c) 2011, 2012, 2013, 2014, 2015 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 18:40:10 -04: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 09:28:16 -04:00
#if !defined(HEAP_GUARD_DEBUG)
2016-02-28 06:11:02 -05:00
void free(void* addr)
2013-10-22 18:40:10 -04: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);
// 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 09:28:16 -04:00
#else
#include <sys/mman.h>
2016-02-28 06:11:02 -05:00
#ifdef __is_sortix_libk
#include <libk.h>
2015-10-09 09:28:16 -04:00
#endif
2016-02-28 06:11:02 -05:00
void free(void* addr)
2015-10-09 09:28:16 -04:00
{
if ( !addr )
return;
struct heap_alloc* alloc_ptr =
(struct heap_alloc*) HEAP_ALIGN_PAGEDOWN((uintptr_t) addr - 16);
2016-02-28 06:11:02 -05:00
#ifdef __is_sortix_libk
libk_munmap((void*) alloc_ptr->from, alloc_ptr->size);
#else
2015-10-09 09:28:16 -04:00
munmap((void*) alloc_ptr->from, alloc_ptr->size);
#endif
}
#endif