Memory Emulation
-
JoeTheProgrammer
- Member

- Posts: 48
- Joined: Mon Aug 13, 2007 2:30 pm
Memory Emulation
Does anyone know how to emulate memory for an x86 emulator? How to create functions to emulate reading and writing to memory like the MemRead8 and MemWrite8 functions? If anyone can help me, let me know.
Thanks,
Joseph
Thanks,
Joseph
The simplest way I can think of is this:
unsigned char SystemRam[65536]; //64k of ram
unsigned char Read8(unsigned long Location)
{
return SystemRam[Location];
}
void Write8(unsigned long Location, unsigned char Data)
{
SystemRam8[Location] = Data;
}
unsigned short Read16(unsigned long Location)
{
return *(unsigned short*)(&SystemRam[Location]);
}
void Write16(unsigned long Location, unsigned short Data)
{
*(unsigned short*)(&SystemRam[Location]) = Data;
}
Then the same for 32 and 64-bit... you would want to check things, like if Location is within certain ranges (for things like VGA buffers, memory mapped devices, holes in memory so certain memroy probing algorithms work correctly, check if location is further than the memory size, etc). It's pretty simple once you have a design/layout of devices and locations. Writing to VGA memory should be perfectly find, and handled normally, then your VGA emulator should read from the data at the VGA offset and display it to screen, but the code in the memroy reading/writing shouldn't need anything special in this case. I would probably make the reading/writing inlined for speed reasons.
unsigned char SystemRam[65536]; //64k of ram
unsigned char Read8(unsigned long Location)
{
return SystemRam[Location];
}
void Write8(unsigned long Location, unsigned char Data)
{
SystemRam8[Location] = Data;
}
unsigned short Read16(unsigned long Location)
{
return *(unsigned short*)(&SystemRam[Location]);
}
void Write16(unsigned long Location, unsigned short Data)
{
*(unsigned short*)(&SystemRam[Location]) = Data;
}
Then the same for 32 and 64-bit... you would want to check things, like if Location is within certain ranges (for things like VGA buffers, memory mapped devices, holes in memory so certain memroy probing algorithms work correctly, check if location is further than the memory size, etc). It's pretty simple once you have a design/layout of devices and locations. Writing to VGA memory should be perfectly find, and handled normally, then your VGA emulator should read from the data at the VGA offset and display it to screen, but the code in the memroy reading/writing shouldn't need anything special in this case. I would probably make the reading/writing inlined for speed reasons.
-
JoeTheProgrammer
- Member

- Posts: 48
- Joined: Mon Aug 13, 2007 2:30 pm
Thanks for the reply, now I completely understand.Ready4Dis wrote:The simplest way I can think of is this:
unsigned char SystemRam[65536]; //64k of ram
unsigned char Read8(unsigned long Location)
{
return SystemRam[Location];
}
void Write8(unsigned long Location, unsigned char Data)
{
SystemRam8[Location] = Data;
}
unsigned short Read16(unsigned long Location)
{
return *(unsigned short*)(&SystemRam[Location]);
}
void Write16(unsigned long Location, unsigned short Data)
{
*(unsigned short*)(&SystemRam[Location]) = Data;
}
Then the same for 32 and 64-bit... you would want to check things, like if Location is within certain ranges (for things like VGA buffers, memory mapped devices, holes in memory so certain memroy probing algorithms work correctly, check if location is further than the memory size, etc). It's pretty simple once you have a design/layout of devices and locations. Writing to VGA memory should be perfectly find, and handled normally, then your VGA emulator should read from the data at the VGA offset and display it to screen, but the code in the memroy reading/writing shouldn't need anything special in this case. I would probably make the reading/writing inlined for speed reasons.
Yeah, not to difficult as you can see, you can do whatever fancy thing you want also, for example, some machines have a hole in their memory address, or do certain functions (i/o mapped devices) when read/written to. For something like a memory whole, you would basically just return a 0 for a read, and do nothing for a write (or leave the code the same for writing just for simplicity and speed, less if statements==faster), then if the OS or program is trying to do memory probing it will see that it wrote a value to that location and couldn't read it back in, so it's a hole
.
You can also save space (and have the ability to dynamically allocate the ram on an as used basis) is to use simulated paging (also known as "banking" in the emulation world).
Basically you setup an array of blocks to represent RAM like this:
/* this will take up 4MB of actual memory system, but will easily support sparse memory, here, we do like intel and have each "page" represent 4KB */
uint8_t *g_Banks[4096];
to access an address, you simply do a little bit shifting and masking:
uint8_t read8(uint32_t address) {
uint32_t page = (address & 0xfffff000) >> 12;
uint32_t offset = (address & 0x00000fff);
if(g_Banks[page] != 0) {
return g_Banks[page][offset];
else {
return 0xff; /* if they read a dead area, we return 0xff */
}
}
void write8(uint32_t address, uint8_t value) {
uint32_t page = (address & 0xfffff000) >> 12;
uint32_t offset = (address & 0x00000fff);
if(g_Banks[page] != 0) {
g_Banks[page][offset] = value;
}
}
and finally to allocate a "page" you just fill it in:
void allocate_bank(unsigned int bank) {
g_Banks[bank] = malloc(4096);
}
This concept is simple, provides easy support for holes (just don't allocate a bank in the middle somewhere). support mirroring with no extra code (point two banks to same memory). And has very little overhead.
proxy
Basically you setup an array of blocks to represent RAM like this:
/* this will take up 4MB of actual memory system, but will easily support sparse memory, here, we do like intel and have each "page" represent 4KB */
uint8_t *g_Banks[4096];
to access an address, you simply do a little bit shifting and masking:
uint8_t read8(uint32_t address) {
uint32_t page = (address & 0xfffff000) >> 12;
uint32_t offset = (address & 0x00000fff);
if(g_Banks[page] != 0) {
return g_Banks[page][offset];
else {
return 0xff; /* if they read a dead area, we return 0xff */
}
}
void write8(uint32_t address, uint8_t value) {
uint32_t page = (address & 0xfffff000) >> 12;
uint32_t offset = (address & 0x00000fff);
if(g_Banks[page] != 0) {
g_Banks[page][offset] = value;
}
}
and finally to allocate a "page" you just fill it in:
void allocate_bank(unsigned int bank) {
g_Banks[bank] = malloc(4096);
}
This concept is simple, provides easy support for holes (just don't allocate a bank in the middle somewhere). support mirroring with no extra code (point two banks to same memory). And has very little overhead.
proxy
That would work alright for paging, but what about if someone unmaps an area that was allocated? You can't free the memory, because the physical memory would still be full, what if they unmapped it from something and re-mapped it afterwards? Then you can't deallocate and re-allocate the memory, so you need something to store un-allocated memory and what it's physical address where. Now, you can use this in a physical memory manager and only allocate memory once it's being asked for, which isn't to hard to do using this method. I would do something like this:
That would be a pretty extensive read function to save on memory at the same time, although a bit slower than just a large array
. The write function would be similar, except you would check to see if the flags Useable bit was set (meaning it's not a memory hole) before allocating memory for the address, if it isn't useable, you just return immediately, otherwise you would allocate the 4mb page directory, then allocate whichever page table you need, and write the value, maybe zeroize, or write a sequence for debugging (if you zeroize it, the program may run under your emulator but not a real PC). Anyways, I wrote this in this window, so it's not tested, but you can get a good idea from it. Like I said though, it is much slower but safer and saves ram if the OS running isn't using it, but if it does use it, you are wasting memory, but it does simplify creating memory holes and any other additional features you needed by using more bits of the flag. I would stick with an easy method but use functions like Read/Write so you could always modify the memory handler at a later time once it's all working without breaking the rest of the program. The idea of mirroring is good, you can have 2 PTE entries point to the same physical location for mirroring address to save memory, I would first look and figure out what you are planning for, ease of debugging, speed, memory footprint, etc and then work on a method to work best for it, and also what kind of PC you would like to emulate, how many holes, mirrors, etc.
Code: Select all
#define PresentBit 1 //Is it allocated already?
#define UseableBit 2 //Is this a valid page to use?
struct PTE_S
{
u32 Flags;
u8 *Data;
};
struct PDE_S
{
u32 Flags;
struct PTE_S *PTE[1024]; //1k worth of pointers
};
//1024 entries, 4mb in size = 4gb limit!
struct PDE_S PDE_List[1024];
u8 Read8(u32 Addr)
{
u32 Entry4mb = (Addr/0x400000); //4mb boundary :)
u32 Offset4mb;
u32 Offset4kb;
if (PDE_List[Entry4mb].Flags & PresentBit) //Is page already allocated?
{
Offset4kb = Addr&0x003FFFFF;
Offset4kb /= 4096; //Find the entry
if (PDE_List[Entry4mb].PTE[Offset4kb]->Flags & PresentBit)
{
return PDE_List[Entry4mb].PTE[Offset4kb]->Data[Addr&0xFFF]; //return data
}
}
return 0; //Return blank, if it's either not allocated yet or not a valid memory address!
}
The goal of my example was not to replicate paging outright (though it does achieve that to some degree). The goal was to not have to allocate a ton of RAM immediately, but instead on an as needed basis. I was actually suggesting it for the physical memory emulation where a layer like your would provide paging emualtion.
for your example of emulating paging, your code is pretty much on the mark, and is unfortunately necessary to do it right. All the checks the hardware does, you need to do in software in order to have page faults happen in all the same ways as the hardware does.
proxy
for your example of emulating paging, your code is pretty much on the mark, and is unfortunately necessary to do it right. All the checks the hardware does, you need to do in software in order to have page faults happen in all the same ways as the hardware does.
proxy
Actually, my example was for physical, although it may not seem that way, lol. It was the easiest (and easiest to implement virtual memory manager on top of). You use that for the physical memory allocation up to 4gb dynamically. The address you pass it is the physical address and it checks if it's there or not. The example you gave was for a single 4mb region, but to extend that to 4gb, you'd need 1024 4m entries (like mine has in my little snippet), i just dynamically allocate the 4mb entries as well, i could have simplified it a bit to just have a 1024 entry list of 4m entries, and saved a bit of code and conditionals, but you were talking about saving memory, so allocating 1024 4k lists wastes another 4mb that may not be needed, but probably more worth it in the worst case scenario since mine uses 8-bytes per entry rather than 4, wasting 8mb if you allocated the entire 4gb, but saves memory if you are only using a small section. And adding virtual memory manager on top of my version s VERY simple, just have to make sure when they update the page table's you update them properly (not hard to do). Oh well, I still suggest just doing a basic array and replace it with a more complex system later.proxy wrote:The goal of my example was not to replicate paging outright (though it does achieve that to some degree). The goal was to not have to allocate a ton of RAM immediately, but instead on an as needed basis. I was actually suggesting it for the physical memory emulation where a layer like your would provide paging emualtion.
for your example of emulating paging, your code is pretty much on the mark, and is unfortunately necessary to do it right. All the checks the hardware does, you need to do in software in order to have page faults happen in all the same ways as the hardware does.
proxy
Re: Memory Emulation
Hi,
Note: Most emulators skip most of this for various reasons. How much you skip depends on if you want accuracy or performance (and lots of other things).
Cheers,
Brendan
The full sequence would probably go something like:JoeTheProgrammer wrote:Does anyone know how to emulate memory for an x86 emulator? How to create functions to emulate reading and writing to memory like the MemRead8 and MemWrite8 functions? If anyone can help me, let me know.
- In "GetLinearAddress()":
- add the segment base to the offset (and check segment limit)
- if "alignment checking" is enabled, check if the access is aligned and do an "alignement check exception" if it isn't.
- check if the access corresponds to anything in the debugging registers (DR0 to DR7) and do a debug exception if it does.
In "GetPhysicalAddress()":
- if the access crosses a page boundary, split it into 2 accesses that don't
- set initial "caching type" according to the CD and NW flags in CR0 (optional - only if caches are emulated).
- if paging is enabled do page lookup; and limit "caching type" to whatever the page table entry says (optional - only if caches are emulated).
- if A20 is disabled, do "address = address & 0xFFEFFFFF".
In "DoPhysicalAccess()":
- lookup the physical address in the MTRRs (and combine it with the previous "caching type") to get the final "caching type" (optional - only if caches are emulated).
- depending on the "caching type", try to complete the operation in the emulated cache and/or write-combining buffer (optional - only if caches are emulated).
- if the local APIC is present; check if the physical address hits the local APIC area (and if it's a 32-bit access that's aligned on a 32-bit boundary) and forward it to the local APIC emulation code if it is.
- lookup the physical address in the memory controller to see if it hits local RAM or not. This may depend on if the CPU is in SMM mode or not, and various memory controller configuration registers ("Programmable Attribute Map Registers", etc).
- if it hits local RAM complete the operation in RAM (optionally loading the cache line into the emulated cache, depending on the "caching type" and if caches are emulated), and add some sort of "local RAM cache miss penalty" to the time stamp counter.
- if it hits remote RAM forward the access to the CPU that controls the remote RAM, and add some sort of "remote RAM cache miss penalty" to the time stamp counter (optional - for AMD style NUMA emulation only).
- if it doesn't hit local RAM (or remote RAM), forward the access to the PCI host controller (or the I/O hub, or the CPU that connects to the I/O hub for AMD style NUMA emulation), and add some sort of "PCI access penalty" to the time stamp counter.
Note: Most emulators skip most of this for various reasons. How much you skip depends on if you want accuracy or performance (and lots of other things).
Cheers,
Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.


