sbrk_emu.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * The Amsterdam Compiler Kit
  3. * See the copyright notice in the ACK home directory, in the file "Copyright".
  4. */
  5. /*
  6. * sbrk(), brk() emulation based on calloc()
  7. * Based on version from D A Gwyn
  8. * 02-Mar-1990 D A Gwyn
  9. * http://www.linuxmisc.com/10-unix-questions/0875f91c36e18724.htm
  10. */
  11. #include <stdio.h>
  12. #include <errno.h> /* for errno, ENOMEM */
  13. #if __STDC__
  14. #include <stdlib.h> /* for calloc */
  15. #else
  16. extern char *calloc();
  17. #endif
  18. /* Allocate 64MB to brk/sbrk should be enough for such application */
  19. #ifndef HEAP_SIZE /* with 32-bit ints, 0x200000 is recommended */
  20. #define HEAP_SIZE 0x4000000 /* size of simulated heap, in bytes */
  21. #endif
  22. #define BRK_OK 0
  23. #define BRK_ERR (-1)
  24. #define SBRK_ERR ((void *)-1) /* horrible interface design */
  25. static void *bottom = NULL; /* bottom of calloc()ed pseudo-heap */
  26. static void *brkval = NULL; /* current value of simulated break */
  27. int brk_emu( void *endds )
  28. {
  29. int offset;
  30. if ( bottom == NULL )
  31. {
  32. if ( (bottom = calloc( HEAP_SIZE, 1 )) == 0 )
  33. {
  34. return BRK_ERR; /* unable to set up pseudo-heap */
  35. }
  36. else
  37. {
  38. brkval = bottom;
  39. }
  40. }
  41. if ( (offset = endds - bottom) < 0 || offset > HEAP_SIZE )
  42. {
  43. errno = ENOMEM;
  44. return BRK_ERR; /* attempt to set break out of heap */
  45. }
  46. else
  47. {
  48. brkval = endds;
  49. return BRK_OK;
  50. }
  51. }
  52. void *sbrk_emu(int incr)
  53. {
  54. int offset;
  55. if ( bottom == 0 )
  56. {
  57. if ( (bottom = (char *)calloc( HEAP_SIZE, 1 )) == 0 )
  58. {
  59. return SBRK_ERR; /* unable to set up heap */
  60. }
  61. else
  62. {
  63. brkval = bottom;
  64. }
  65. }
  66. if ( (offset = (brkval - bottom) + incr) < 0 || offset > HEAP_SIZE )
  67. {
  68. errno = ENOMEM;
  69. return SBRK_ERR; /* attempt to set break out of heap */
  70. }
  71. else
  72. {
  73. char *oldbrk = brkval;
  74. brkval += incr;
  75. return oldbrk;
  76. }
  77. }