sys_alloc.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <dmmlib/heap.h>
  6. #include "dmm_config.h"
  7. #ifdef HAVE_LOCKS
  8. #include "posix_lock.h"
  9. #endif /* HAVE_LOCKS */
  10. #include "other.h"
  11. #include "sys_alloc.h"
  12. #include "block_header.h"
  13. void *sys_alloc(allocator_t *allocator, heap_t *heap, size_t size) {
  14. size_t allocation_size, previous_size, previous_size_availability;
  15. void *ptr;
  16. #ifdef HAVE_LOCKS
  17. sbrk_lock();
  18. #endif /* HAVE_LOCKS */
  19. allocation_size = req_padding(size) + HEADER_SIZE;
  20. if(allocator->border_ptr != NULL) {
  21. previous_size = get_size(allocator->border_ptr);
  22. previous_size_availability = get_size_availability(allocator->border_ptr);
  23. } else {
  24. previous_size = 0;
  25. previous_size_availability = 1; /* Occupied and of 0 size */
  26. }
  27. #ifndef WITH_MEMORY_SPACE_AWARENESS
  28. ptr = sbrk((int) allocation_size);
  29. if(ptr == (void *) -1) {
  30. printf("sbrk problem for size of: %zu\n", allocation_size);
  31. printf("Error on sbrk: %s\n", strerror( errno ) );
  32. }
  33. if(allocator->border_ptr != NULL && ptr != (void *)
  34. ((char *) allocator->border_ptr + previous_size)) {
  35. printf("sbrk() does not return sequential space.\n");
  36. }
  37. #else
  38. if(allocator->remaining_size >= allocation_size) {
  39. ptr = (void *) ((char *) allocator->border_ptr + previous_size);
  40. allocator->remaining_size -= allocation_size;
  41. } else {
  42. printf("No more free space.\n");
  43. }
  44. #endif /* WITH_MEMORY_SPACE_AWARENESS */
  45. /* Go to the data part of the block */
  46. ptr = (void *) ((char *) ptr + HEADER_SIZE);
  47. /* Set the new border pointer */
  48. allocator->border_ptr = ptr;
  49. /* Set some values for block header */
  50. set_size(ptr, req_padding(size));
  51. set_previous_size_availability(ptr, previous_size_availability);
  52. /* Update stats */
  53. heap->dmm_stats.mem_allocated += req_padding(size);
  54. heap->dmm_stats.mem_requested += size;
  55. /* FIXME To be refactored - START */
  56. set_requested_size(ptr, size);
  57. mark_used(ptr);
  58. // Update the used blocks list
  59. set_next(ptr, heap->used_blocks_head);
  60. heap->used_blocks_head = ptr;
  61. // Begin of Stats
  62. heap->dmm_stats.live_objects += 1;
  63. heap->dmm_stats.num_malloc += 1;
  64. // End of Stats
  65. /* FIXME To be refactored - END */
  66. #ifdef HAVE_LOCKS
  67. sbrk_unlock();
  68. #endif /* HAVE_LOCKS */
  69. return ptr;
  70. }