Bug fix: check if vm exists
[avr-sim.git] / Memory.cpp
blobe0c9bcc9309d99b76e33b5ee0436db2245d5fe7f
1 #include "Memory.h"
2 #include <memory.h>
3 #include <fstream>
5 #include "Format.h"
6 #include "AccessViolation.h"
8 namespace avr {
9 Memory::Memory(unsigned int size) : siz(size) {
10 mem = new unsigned char[size];
13 Memory::~Memory() {
14 delete [] mem;
17 void Memory::write(unsigned int offset, unsigned char *block, unsigned int size /*= 1*/) {
18 if( offset + size > siz )
19 throw AccessViolation("Memory::write: writing too much to memory");
21 memcpy( mem + offset, block, size );
24 void Memory::fill(unsigned char val) {
25 memset( mem, val, siz );
28 const unsigned char *Memory::read(unsigned int offset, unsigned int size /*= 1*/) const {
29 if( offset + size > siz )
30 throw AccessViolation("Memory::read: reads too far");
32 return mem + offset;
35 /**
36 * Reads \e size bytes of raw data from memory starting at
37 * offset \e offset. It returns a pointer to this data.
39 * \exception RuntimeException { When the data requested is
40 * not available, this exception is thrown }
42 byte Memory::readByte(unsigned int offset) const {
43 if( offset >= siz )
44 throw AccessViolation("Memory::read: reads too far");
46 return mem[ offset ];
49 word Memory::readWord(unsigned int offset) const {
50 if( offset >= siz )
51 throw AccessViolation("Memory::read: reads too far");
53 return *((word *)(mem + offset));
56 void Memory::dump(const char *fname) const {
57 std::ofstream fout( fname, std::ios::out | std::ios::binary );
58 if( ! fout.is_open() )
59 throw AccessViolation( util::format("Memory::dump: failed to open file: %s") % fname );
61 fout.write( reinterpret_cast<const char *>(mem), siz );