You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.2 KiB

  1. /*
  2. * memlib.c - a module that simulates the memory system. Needed because it
  3. * allows us to interleave calls from the student's malloc package
  4. * with the system's malloc package in libc.
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <assert.h>
  9. #include <unistd.h>
  10. #include <sys/mman.h>
  11. #include <string.h>
  12. #include <errno.h>
  13. #include "memlib.h"
  14. #include "config.h"
  15. /* private variables */
  16. static char *mem_start_brk; /* points to first byte of heap */
  17. static char *mem_brk; /* points to last byte of heap */
  18. static char *mem_max_addr; /* largest legal heap address */
  19. /*
  20. * mem_init - initialize the memory system model
  21. */
  22. void mem_init(void)
  23. {
  24. /* allocate the storage we will use to model the available VM */
  25. if ((mem_start_brk = (char *)malloc(MAX_HEAP)) == NULL) {
  26. fprintf(stderr, "mem_init_vm: malloc error\n");
  27. exit(1);
  28. }
  29. mem_max_addr = mem_start_brk + MAX_HEAP; /* max legal heap address */
  30. mem_brk = mem_start_brk; /* heap is empty initially */
  31. }
  32. /*
  33. * mem_deinit - free the storage used by the memory system model
  34. */
  35. void mem_deinit(void)
  36. {
  37. free(mem_start_brk);
  38. }
  39. /*
  40. * mem_reset_brk - reset the simulated brk pointer to make an empty heap
  41. */
  42. void mem_reset_brk()
  43. {
  44. mem_brk = mem_start_brk;
  45. }
  46. /*
  47. * mem_sbrk - simple model of the sbrk function. Extends the heap
  48. * by incr bytes and returns the start address of the new area. In
  49. * this model, the heap cannot be shrunk.
  50. */
  51. void *mem_sbrk(int incr)
  52. {
  53. char *old_brk = mem_brk;
  54. if ( (incr < 0) || ((mem_brk + incr) > mem_max_addr)) {
  55. errno = ENOMEM;
  56. fprintf(stderr, "ERROR: mem_sbrk failed. Ran out of memory...\n");
  57. return (void *)-1;
  58. }
  59. mem_brk += incr;
  60. return (void *)old_brk;
  61. }
  62. /*
  63. * mem_heap_lo - return address of the first heap byte
  64. */
  65. void *mem_heap_lo()
  66. {
  67. return (void *)mem_start_brk;
  68. }
  69. /*
  70. * mem_heap_hi - return address of last heap byte
  71. */
  72. void *mem_heap_hi()
  73. {
  74. return (void *)(mem_brk - 1);
  75. }
  76. /*
  77. * mem_heapsize() - returns the heap size in bytes
  78. */
  79. size_t mem_heapsize()
  80. {
  81. return (size_t)(mem_brk - mem_start_brk);
  82. }
  83. /*
  84. * mem_pagesize() - returns the page size of the system
  85. */
  86. size_t mem_pagesize()
  87. {
  88. return (size_t)getpagesize();
  89. }