alloc.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. void *result;
  52. #if 1
  53. /* Some programs will call malloc (0). Lets be strict and return NULL */
  54. if (size == 0)
  55. return NULL;
  56. #endif
  57. result = mmap((void *) 0, size, PROT_READ | PROT_WRITE,
  58. #ifdef __UCLIBC_HAS_MMU__
  59. MAP_PRIVATE | MAP_ANONYMOUS, 0, 0
  60. #else
  61. MAP_SHARED | MAP_ANONYMOUS, 0, 0
  62. #endif
  63. );
  64. if (result == MAP_FAILED)
  65. return 0;
  66. return result;
  67. }
  68. #endif
  69. #ifdef L_free
  70. void free(void *ptr)
  71. {
  72. munmap(ptr, 0);
  73. }
  74. #endif
  75. #ifdef L_realloc
  76. void *realloc(void *ptr, size_t size)
  77. {
  78. void *newptr = NULL;
  79. if (size > 0) {
  80. newptr = malloc(size);
  81. if (newptr && ptr) {
  82. memcpy(newptr, ptr, size);
  83. free(ptr);
  84. }
  85. }
  86. else
  87. free(ptr);
  88. return newptr;
  89. }
  90. #endif