memory.hh 2.03 KB
Newer Older
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
102
103
104
#ifndef VM_MEMORY_HH
# define VM_MEMORY_HH

# include "misc/contract.hh"

# include "inst/data_section.hh"
# include "vm/segment.hh"

// FIXME: lack of compatibility
# include <stdint.h>
# ifndef INT32_MAX
#  define INT32_MAX		2147483647
# endif
# include <string.h>

namespace vm
{

  class Memory
  {
  public:
    static const int		stack_size = 128 * 1024;
    static const int		stack_bottom = INT32_MAX - 3;
    static const int		stack_top = stack_bottom - stack_size + 4;

  public:
    Memory():
      _heap(0),
      _stack(stack_size)
    {
    }

  protected:
    int			translate(int offset) const
    {
      precondition(offset >= stack_top);
      // Stack grows down
      return offset - stack_top;
    }

  public:
    int			sbrk(int size)
    {
      precondition(size >= 0);
      int		ptr = _heap.size();
      if (size)
	// FIXME: check collision with stack
	_heap.resize(size + _heap.size());
      return ptr;
    }

  public:
    void		store(const inst::DataSection& data_section)
    {
      _heap.resize(data_section.size());
      for (int i = 0; i < data_section.size(); ++i)
	_heap.store_byte(i, data_section.load_byte(i));
    }

    void		store_byte(int offset, int b)
    {
      precondition(offset >= 0);
      if (offset < _heap.size())
	_heap.store_byte(offset, b);
      else
	_stack.store_byte(translate(offset), b);
    }

    void		store_word(int offset, int w)
    {
      precondition(offset >= 0);
      if (offset < _heap.size())
	_heap.store_word(offset, w);
      else
	_stack.store_word(translate(offset), w);
    }

    
  public:
    int			load_byte(int offset) const
    {
      precondition(offset >= 0);
      if (offset < _heap.size())
	return _heap.load_byte(offset);
      return _stack.load_byte(translate(offset));
    }

    int			load_word(int offset) const
    {
      precondition(offset >= 0);
      if (offset < _heap.size())
	return _heap.load_word(offset);
      return _stack.load_word(translate(offset));
    }


  protected:
    Segment	_heap;
    Segment	_stack;
  };

} // namespace vm

#endif // !VM_MEMORY_HH