Memory.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "api.h"
  2. #include "pal.h"
  3. #include "pal_debug.h"
  4. #define UNIT (pal_control.alloc_align)
  5. static volatile int count = 0;
  6. void handler(PAL_PTR event, PAL_NUM arg, PAL_CONTEXT* context) {
  7. count++;
  8. pal_printf("Memory Fault %d\n", count);
  9. while (*(unsigned char*)context->rip != 0x90) {
  10. context->rip++;
  11. }
  12. DkExceptionReturn(event);
  13. }
  14. int main(int argc, char** argv, char** envp) {
  15. volatile int c;
  16. DkSetExceptionHandler(handler, PAL_EVENT_MEMFAULT);
  17. void* mem1 = (void*)DkVirtualMemoryAlloc(NULL, UNIT * 4, 0, PAL_PROT_READ | PAL_PROT_WRITE);
  18. if (mem1)
  19. pal_printf("Memory Allocation OK\n");
  20. void* mem2 = (void*)DkVirtualMemoryAlloc(NULL, UNIT, 0, PAL_PROT_READ | PAL_PROT_WRITE);
  21. if (mem2) {
  22. c = count;
  23. *(volatile int*)mem2 = 0;
  24. pal_printf("(int *) %p = %d\n", mem2, *(volatile int*)mem2);
  25. if (c == count)
  26. pal_printf("Memory Allocation Protection (RW) OK\n");
  27. DkVirtualMemoryProtect(mem2, UNIT, PAL_PROT_READ);
  28. c = count;
  29. *(volatile int*)mem2 = 0;
  30. __asm__ volatile("nop");
  31. if (c == count - 1)
  32. pal_printf("Memory Protection (R) OK\n");
  33. DkVirtualMemoryFree(mem2, UNIT);
  34. c = count;
  35. *(volatile int*)mem2 = 0;
  36. __asm__ volatile("nop");
  37. if (c == count - 1)
  38. pal_printf("Memory Deallocation OK\n");
  39. }
  40. void* mem3 = (void*)pal_control.user_address.start;
  41. void* mem4 = (void*)pal_control.user_address.end - UNIT;
  42. if (mem3 >= pal_control.executable_range.start && mem3 < pal_control.executable_range.end)
  43. mem3 = (void*)ALIGN_UP_PTR(pal_control.executable_range.end, UNIT);
  44. mem3 = (void*)DkVirtualMemoryAlloc(mem3, UNIT, 0, PAL_PROT_READ | PAL_PROT_WRITE);
  45. mem4 = (void*)DkVirtualMemoryAlloc(mem4, UNIT, 0, PAL_PROT_READ | PAL_PROT_WRITE);
  46. if (mem3 && mem4)
  47. pal_printf("Memory Allocation with Address OK\n");
  48. /* Testing total memory */
  49. pal_printf("Total Memory: %lu\n", pal_control.mem_info.mem_total);
  50. /* Testing available memory (must be within valid range) */
  51. PAL_NUM avail = DkMemoryAvailableQuota();
  52. if (avail > 0 && avail < pal_control.mem_info.mem_total)
  53. pal_printf("Get Memory Available Quota OK\n");
  54. return 0;
  55. }