Subversion Repositories Kolibri OS

Rev

Rev 8179 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
8140 IgorA 1
#ifndef __KOLIBRI_HEAP_H_INCLUDED_
2
#define __KOLIBRI_HEAP_H_INCLUDED_
3
 
4
#include "kolibri.h"
5
#include "memheap.h"
6
 
7
// Kolibri memory heap interface.
8
 
9
namespace Kolibri   // All kolibri functions, types and data are nested in the (Kolibri) namespace.
10
{
11
	void *Alloc(unsigned int size);
12
	void *ReAlloc(void *mem, unsigned int size);
13
	void Free(void *mem);
14
}
15
 
16
#ifdef __KOLIBRI__
17
 
18
namespace Kolibri
19
{
20
 
21
// Global variables
22
 
23
	MemoryHeap::TFreeSpace _KolibriFreeSpace;
24
	MemoryHeap::TMemBlock  _KolibriMemBlock;
25
	TMutex _MemHeapMutex = KOLIBRI_MUTEX_INIT;
26
 
27
// Functions
28
 
29
	void *_HeapInit(void *begin, void *use_end, void *end)
30
	{
31
		MemoryHeap::InitFreeSpace(_KolibriFreeSpace);
32
		_KolibriMemBlock = MemoryHeap::CreateBlock(begin, end, _KolibriFreeSpace);
33
		unsigned int use_beg = (unsigned int)MemoryHeap::BlockBegin(_KolibriMemBlock) +
34
					MemoryHeap::BlockAddSize - MemoryHeap::BlockEndSize;
35
		unsigned int use_size = (unsigned int)use_end;
36
		if (use_size <= use_beg) return 0;
37
		else use_size -= use_beg;
38
		return MemoryHeap::Alloc(_KolibriFreeSpace, use_size);
39
	}
40
 
41
	bool _SetUseMemory(unsigned int use_mem);
42
 
43
	int _RecalculateUseMemory(unsigned int use_mem);
44
 
45
	void *Alloc(unsigned int size)
46
	{
47
		if (!size) return 0;
48
		Lock(&_MemHeapMutex);
49
		void *res = MemoryHeap::Alloc(_KolibriFreeSpace, size);
50
		if (!res)
51
		{
52
			unsigned use_mem = (unsigned int)MemoryHeap::BlockEndFor(_KolibriMemBlock, size);
53
			if (_SetUseMemory(_RecalculateUseMemory(use_mem)))
54
			{
55
				res = MemoryHeap::Alloc(_KolibriFreeSpace, size);
56
			}
57
		}
58
		UnLock(&_MemHeapMutex);
59
		return res;
60
	}
61
 
62
	void *ReAlloc(void *mem, unsigned int size)
63
	{
64
		Lock(&_MemHeapMutex);
65
		void *res = MemoryHeap::ReAlloc(_KolibriFreeSpace, mem, size);
66
		if (!res && size)
67
		{
68
			unsigned use_mem = (unsigned int)MemoryHeap::BlockEndFor(_KolibriMemBlock, size);
69
			if (_SetUseMemory(_RecalculateUseMemory(use_mem)))
70
			{
71
				res = MemoryHeap::ReAlloc(_KolibriFreeSpace, mem, size);
72
			}
73
		}
74
		UnLock(&_MemHeapMutex);
75
		return res;
76
	}
77
 
78
	void Free(void *mem)
79
	{
80
		Lock(&_MemHeapMutex);
81
		MemoryHeap::Free(_KolibriFreeSpace, mem);
82
		UnLock(&_MemHeapMutex);
83
	}
84
 
85
	void _FreeAndThreadFinish(void *mem, int *exit_proc_now);
86
}
87
 
88
#endif  // def  __KOLIBRI__
89
 
90
#endif  // ndef __KOLIBRI_HEAP_H_INCLUDED_