-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemory.cpp
More file actions
76 lines (67 loc) · 1.89 KB
/
Memory.cpp
File metadata and controls
76 lines (67 loc) · 1.89 KB
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
#include "Memory.h"
#include "Stack.h"
#include "Environment.h"
using namespace std;
Memory memory;
extern Environment globalEnvironment;
Memory::Memory() {
blocks.push_back(new MemoryBlock());
}
Memory::~Memory() {
for (MemoryBlock * block : blocks)
delete block;
blocks.clear();
}
Object * Memory::allocate(unsigned int requestedSize) {
unsigned char * address = this->tryAllocate(requestedSize);
if (freeBlock >= 0 && !address) {
#ifdef DEBUG
cout << "DEBUG: collecting garbage to free " << requestedSize << " B" << endl;
#endif
collectGarbage();
freeBlock = -1;
#ifdef DEBUG
cout << "DEBUG: garbage collected - mode set to pick free spaces";
#endif
address = this->tryAllocate(requestedSize);
#ifdef DEBUG
if (address)
cout << " - freed enough memory";
cout << endl;
#endif
}
if (address)
return reinterpret_cast<Object*> (address);
freeBlock = blocks.size();
#ifdef DEBUG
cout << "DEBUG: mode set to always append to end" << endl;
#endif
blocks.push_back(new MemoryBlock());
address = blocks.back()->allocateAtEnd(requestedSize);
if (!address)
throw runtime_error("no address");
return reinterpret_cast<Object*> (address);
}
unsigned char * Memory::tryAllocate(unsigned int requestedSize) {
if (freeBlock >= 0)
return blocks[freeBlock]->allocateAtEnd(requestedSize);
unsigned char * address;
for (MemoryBlock * block : blocks) {
address = block->allocate(requestedSize);
if (address)
return address;
}
return nullptr;
}
void Memory::collectGarbage() {
mark();
sweep();
}
void Memory::mark() {
globalEnvironment.mark();
stack.mark();
}
void Memory::sweep() {
for (MemoryBlock * block : blocks)
block->sweep();
}