summaryrefslogtreecommitdiff
path: root/include/rvl/MEM/mem_heapCommon.h
blob: 60f3d8bd700c9651244f65affe56a9bc9fa2e95a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#ifndef RVL_SDK_MEM_HEAP_COMMON_H
#define RVL_SDK_MEM_HEAP_COMMON_H
#include "common.h"
#include "rvl/MEM/mem_list.h"
#include "rvl/OS.h" // IWYU pragma: export
#include "string.h"


// #include "string.h"
#ifdef __cplusplus
extern "C" {
#endif

typedef enum {
    MEM_HEAP_OPT_CLEAR_ALLOC = (1 << 0),
    MEM_HEAP_OPT_DEBUG_FILL = (1 << 1),
    MEM_HEAP_OPT_CAN_LOCK = (1 << 2)
} MEMHeapOpt;

typedef struct MEMiHeapHead {
    u32 magic;     // at 0x0
    MEMLink link;  // at 0x4
    MEMList list;  // at 0xC
    u8 *start;     // at 0x18
    u8 *end;       // at 0x1C
    OSMutex mutex; // at 0x20

    union {
        u32 attribute;
        struct {
            u32 attribute_0_24 : 24;
            u32 opt : 8;
        };
    }; // at 0x38
} MEMiHeapHead;

void MEMiInitHeapHead(MEMiHeapHead *heap, u32 magic, void *start, void *end, u16 opt);
void MEMiFinalizeHeap(MEMiHeapHead *heap);
MEMiHeapHead *MEMFindContainHeap(const void *memBlock);
MEMiHeapHead *MEMFindParentHeap(const MEMiHeapHead *pHandle);

static inline int GetUIntPtr(const void *p) {
    return (int)p;
}

static inline void *AddU32ToPtr(const void *p, u32 ofs) {
    return (void *)(GetUIntPtr(p) + ofs);
}

static inline void *SubU32ToPtr(const void *p, u32 ofs) {
    return (void *)(GetUIntPtr(p) - ofs);
}

static inline const void *AddU32ToCPtr(const void *p, u32 ofs) {
    return (const void *)(GetUIntPtr(p) + ofs);
}

static inline const void *SubU32ToCPtr(const void *p, u32 ofs) {
    return (const void *)(GetUIntPtr(p) - ofs);
}

static inline s32 GetOffsetFromPtr(const void *start, const void *end) {
    return GetUIntPtr(end) - GetUIntPtr(start);
}

static inline u16 GetOptForHeap(const MEMiHeapHead *heap) {
    return heap->opt;
}

static inline void SetOptForHeap(MEMiHeapHead *heap, u16 opt) {
    heap->opt = (u8)opt;
}

static inline void LockHeap(MEMiHeapHead *heap) {
    if (GetOptForHeap(heap) & MEM_HEAP_OPT_CAN_LOCK) {
        OSLockMutex(&heap->mutex);
    }
}

static void UnlockHeap(MEMiHeapHead *heap) {
    if (GetOptForHeap(heap) & MEM_HEAP_OPT_CAN_LOCK) {
        OSUnlockMutex(&heap->mutex);
    }
}

static void FillAllocMemory(MEMiHeapHead *heap, void *memBlock, u32 size) {
    if (GetOptForHeap(heap) & MEM_HEAP_OPT_CLEAR_ALLOC) {
        memset(memBlock, 0, size);
    }
}

static s32 MEMGetHeapTotalSize(MEMiHeapHead *heap) {
    return GetOffsetFromPtr(heap, heap->end);
}

static void FillAllocMemory(MEMiHeapHead *heap, void *memBlock, u32 size);

#ifdef __cplusplus
}
#endif
#endif