Web based MIPS assembler and emulator

memory.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // At the moment the memory array is a simple array, this means that _most_ of the time we
  2. // will not be filling up the array and therefore will not be using much RAM, however if
  3. // the full 4gb of memory are used, then it might prove problematic, and I will likely
  4. // move to a server side memory model that persists most data to disk
  5. const mainMemory = {}
  6. // Pads a string with 0's until it is the desired length
  7. const padAddress = (addr, len, ch) => (addr.length >= len) ?
  8. addr : ch.repeat(len-addr.length).concat(addr)
  9. // Converts a string address to a number, adds 1, then back to a string to be padded to 32 bits
  10. const getNextAddr = addr => padAddress((parseInt(addr, 2) + 1).toString(2), 32, '0')
  11. // Load a byte as a 32 bit 0 extended word
  12. const loadByte = addr => padAddress(mainMemory[addr], 32, '0')
  13. // Load a halfword as a 32 bit 0 extended word
  14. const loadHalfWord = addr => padAddress(
  15. loadByte(getNextAddr(addr))
  16. .concat(loadByte(addr)), 32, '0')
  17. // load a full 32 bit word into memory
  18. const loadWord = addr => padAddress(
  19. loadHalfWord(getNextAddr(getNextAddr(addr))).concat(
  20. loadHalfWord(addr)), 32, '0')
  21. // Stores a single byte in the memory array
  22. const storeByte = (addr, data) => {
  23. if (data.length == 8) {
  24. mainMemory[addr] = data
  25. } else {
  26. console.error("data length should be 8bit for byte store")
  27. }
  28. }
  29. // Stores two bytes in memory array, with the lower bytes in the lower addresses
  30. const storeHalfWord = (addr, data) => {
  31. if (data.length == 16) {
  32. if (addr.slice(-1) === '0') {
  33. storeByte(addr, data.slice(8))
  34. storeByte(getNextAddr(addr), data.slice(0,8))
  35. } else {
  36. console.error("misaligned halfword assignments are not yet supported")
  37. }
  38. } else {
  39. console.error("data length should be 16bit for halfword store")
  40. }
  41. }
  42. // Stores two bytes in memory array, with the lower bytes in the lower addresses
  43. const storeWord = (addr, data) => {
  44. if (data.length != 32) return console.error("data length should be 32bit") // function is void anyway so returning undefined doesn't matter
  45. storeHalfWord(addr, data.slice(16))
  46. storeHalfWord(getNextAddr(getNextAddr(addr)), data.slice(0, 16))
  47. }
  48. module.exports = {
  49. storeWord: storeWord,
  50. storeByte: storeByte,
  51. storeHalfWord, storeHalfWord,
  52. loadByte: loadByte,
  53. loadHalfWord: loadHalfWord,
  54. loadWord: loadWord
  55. }