_sbrk.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* There should be a header for brk and sbrk, but there isn't. */
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. /* #include <unistd.h> */
  5. extern char _end[];
  6. static char* brkpointer = _end;
  7. static void prints(char* s)
  8. {
  9. for (;;)
  10. {
  11. char c = *s++;
  12. if (!c)
  13. break;
  14. write(0, &c, 1);
  15. }
  16. }
  17. static void printc(unsigned int n)
  18. {
  19. char c;
  20. n &= 0xF;
  21. if (n < 10)
  22. c = n + '0';
  23. else
  24. c = n + 'A' - 10;
  25. write(0, &c, 1);
  26. }
  27. static void printh(unsigned int n)
  28. {
  29. printc(n>>12);
  30. printc(n>>8);
  31. printc(n>>4);
  32. printc(n);
  33. }
  34. static void waitforkey(void)
  35. {
  36. char c;
  37. read(1, &c, 1);
  38. }
  39. int _brk(char* newend)
  40. {
  41. char dummy;
  42. /* Ensure that newend is reasonable. */
  43. if ((newend < _end) || (newend > (&dummy - 256)))
  44. {
  45. prints("[brk to ");
  46. printh((unsigned int) newend);
  47. prints(" failed]\n\r");
  48. waitforkey();
  49. errno = ENOMEM;
  50. return -1;
  51. }
  52. prints("[brk to ");
  53. printh((unsigned int) newend);
  54. prints("]\n\r");
  55. waitforkey();
  56. brkpointer = newend;
  57. return 0;
  58. }
  59. char* _sbrk(int delta)
  60. {
  61. char* oldpointer = brkpointer;
  62. prints("[sbrk delta ");
  63. printh((unsigned int) delta);
  64. prints(" from ");
  65. printh((unsigned int) oldpointer);
  66. prints("]\n\r");
  67. printh((unsigned int) brkpointer);
  68. prints(" ");
  69. printh((unsigned int) _end);
  70. if (_brk(oldpointer + delta) == -1)
  71. return (char*)-1;
  72. return oldpointer;
  73. }