Skip to content

Commit

Permalink
feat(cortex): expose malloc internals for runtime diagnostics
Browse files Browse the repository at this point in the history
  • Loading branch information
ssimek committed Dec 9, 2024
1 parent a7c6c2f commit 8c2d96a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 13 deletions.
16 changes: 3 additions & 13 deletions targets/cortex-m/malloc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

#include <base/base.h>

#include <ld_symbols.h>
#include <malloc_internal.h>

#define DIAG_ALLOC 1
#define DIAG_HEAP 2
Expand Down Expand Up @@ -49,19 +49,9 @@ OPTIMIZE void* calloc(size_t size, size_t count)
return _malloc_impl(size * count, true);
}

struct free_list
{
struct free_list* next;
size_t size;
};
typedef __malloc_free_list free_list;

static struct
{
free_list* free;
size_t fragments;
void* top = &__heap_start;
void* limit = &__heap_end;
} __heap;
__malloc_heap __heap;

void* _malloc_r(_reent* _, size_t size) { return _malloc_impl(size, false); }
void _free_r(_reent* _, void* ptr) { free(ptr); }
Expand Down
39 changes: 39 additions & 0 deletions targets/cortex-m/malloc_internal.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2024 triaxis s.r.o.
* Licensed under the MIT license. See LICENSE.txt file in the repository root
* for full license information.
*
* cortex-m/malloc_internal.h
*
* Exposes the internals of the Cortex malloc implementation for diagnostics
*/

#pragma once

#include <base/base.h>

#include <ld_symbols.h>

struct __malloc_free_list
{
struct __malloc_free_list* next;
size_t size;
};

struct __malloc_heap
{
__malloc_free_list* free;
size_t fragments;
void* top = &__heap_start;
void* limit = &__heap_end;

constexpr size_t Total() { return &__heap_end - &__heap_start; }
constexpr size_t Committed() { return (char*)top - &__heap_start; }
constexpr size_t Fragments() { return fragments; }
constexpr size_t Used() { return Committed() - fragments; }
constexpr size_t ContiguousFree() { return (char*)limit - (char*)top; }
constexpr size_t Free() { return ContiguousFree() + fragments; }
constexpr size_t Once() { return &__heap_end - (char*)limit; }
};

extern __malloc_heap __heap;

0 comments on commit 8c2d96a

Please sign in to comment.