alloc.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include <features.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <unistd.h>
  7. #include <sys/mman.h>
  8. #ifdef L_calloc_dbg
  9. void *calloc_dbg(size_t num, size_t size, char *function, char *file,
  10. int line)
  11. {
  12. void *ptr;
  13. fprintf(stderr, "calloc of %d bytes at %s @%s:%d = ", num * size,
  14. function, file, line);
  15. ptr = calloc(num, size);
  16. fprintf(stderr, "%p\n", ptr);
  17. return ptr;
  18. }
  19. #endif
  20. #ifdef L_malloc_dbg
  21. void *malloc_dbg(size_t size, char *function, char *file, int line)
  22. {
  23. void *result;
  24. fprintf(stderr, "malloc of %d bytes at %s @%s:%d = ", size, function,
  25. file, line);
  26. result = malloc(size);
  27. fprintf(stderr, "%p\n", result);
  28. return result;
  29. }
  30. #endif
  31. #ifdef L_free_dbg
  32. void free_dbg(void *ptr, char *function, char *file, int line)
  33. {
  34. fprintf(stderr, "free of %p at %s @%s:%d\n", ptr, function, file,
  35. line);
  36. free(ptr);
  37. }
  38. #endif
  39. #ifdef L_calloc
  40. void *calloc(size_t num, size_t size)
  41. {
  42. void *ptr = malloc(num * size);
  43. if (ptr)
  44. memset(ptr, 0, num * size);
  45. return ptr;
  46. }
  47. #endif
  48. #ifdef L_malloc
  49. void *malloc(size_t size)
  50. {
  51. #if 1
  52. /* Some programs will call malloc (0). Lets be strict and return NULL */
  53. if (size == 0)
  54. return NULL;
  55. #endif
  56. void *result = mmap((void *) 0, size, PROT_READ | PROT_WRITE,
  57. #ifdef __UCLIBC_HAS_MMU__
  58. MAP_PRIVATE | MAP_ANONYMOUS, 0, 0
  59. #else
  60. MAP_SHARED | MAP_ANONYMOUS, 0, 0
  61. #endif
  62. );
  63. if (result == MAP_FAILED)
  64. return 0;
  65. return result;
  66. }
  67. #endif
  68. #ifdef L_free
  69. void free(void *ptr)
  70. {
  71. munmap(ptr, 0);
  72. }
  73. #endif
  74. #ifdef L_realloc
  75. void *realloc(void *ptr, size_t size)
  76. {
  77. void *newptr = NULL;
  78. if (size > 0) {
  79. newptr = malloc(size);
  80. if (newptr && ptr) {
  81. memcpy(newptr, ptr, size);
  82. free(ptr);
  83. }
  84. }
  85. else
  86. free(ptr);
  87. return newptr;
  88. }
  89. #endif