mem.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include "mem.h"
  4. struct mem_segment
  5. {
  6. uint64_t start;
  7. uint64_t end;
  8. uint8_t permissions;
  9. uint8_t *memory;
  10. };
  11. int num_segments = 0;
  12. struct mem_segment *memory = 0;
  13. int mem_make_segment(uint64_t start,uint64_t size)
  14. {
  15. struct mem_segment *newsegment;
  16. //TODO: check for overlaps and reject
  17. memory = realloc(memory,++num_segments * sizeof(mem_segment));
  18. newsegment = &memory[num_segments-1];
  19. newsegment->start = start;
  20. newsegment->end = start+size - 1;
  21. newsegment->memory = malloc(size);
  22. return 0;
  23. }
  24. int mem_phys_read_8(uint64_t address,uint8_t *data,uint8_t access)
  25. {
  26. uint64_t offset;
  27. int i;
  28. for(i=0;i<num_segments;i++)
  29. {
  30. if(memory[i].start <= address && memory[i].end >= address)
  31. {
  32. break;
  33. }
  34. }
  35. if(i==num_segments)
  36. {
  37. return MEM_INVALID;
  38. }
  39. if(!(access & memory[i].permissions))
  40. {
  41. return access == MEM_RD? MEM_NOREAD : MEM_NOEXEC;
  42. }
  43. offset = address - memory[i].start;
  44. *data = memory[i].memory[offset];
  45. return MEM_OK;
  46. }
  47. int mem_phys_write_8(uint64_t address,uint8_t *data, uint8_t access)
  48. {
  49. uint64_t offset;
  50. int i;
  51. for(i=0;i<num_segments;i++)
  52. {
  53. if(memory[i].start <= address && memory[i].end >= address)
  54. {
  55. break;
  56. }
  57. }
  58. if(i==num_segments)
  59. {
  60. return MEM_INVALID;
  61. }
  62. if(!(access & memory[i].permissions))
  63. {
  64. return access == MEM_NOWRITE;
  65. }
  66. offset = address - memory[i].start;
  67. memory[i].memory[offset] = *data;
  68. return MEM_OK;
  69. }