sbrk.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /* Copyright (C) 1991-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <errno.h>
  15. #include <stdint.h>
  16. #include <unistd.h>
  17. #include <libc-internal.h>
  18. /* Defined in brk.c. */
  19. extern void *__curbrk;
  20. extern int __brk (void *addr);
  21. /* Extend the process's data space by INCREMENT.
  22. If INCREMENT is negative, shrink data space by - INCREMENT.
  23. Return start of new space allocated, or -1 for errors. */
  24. void *
  25. __sbrk (intptr_t increment)
  26. {
  27. void *oldbrk;
  28. /* If this is not part of the dynamic library or the library is used
  29. via dynamic loading in a statically linked program update
  30. __curbrk from the kernel's brk value. That way two separate
  31. instances of __brk and __sbrk can share the heap, returning
  32. interleaved pieces of it. */
  33. if (__curbrk == NULL || __libc_multiple_libcs)
  34. if (__brk (0) < 0) /* Initialize the break. */
  35. return (void *) -1;
  36. if (increment == 0)
  37. return __curbrk;
  38. oldbrk = __curbrk;
  39. if (increment > 0
  40. ? ((uintptr_t) oldbrk + (uintptr_t) increment < (uintptr_t) oldbrk)
  41. : ((uintptr_t) oldbrk < (uintptr_t) -increment))
  42. {
  43. __set_errno (ENOMEM);
  44. return (void *) -1;
  45. }
  46. if (__brk (oldbrk + increment) < 0)
  47. return (void *) -1;
  48. return oldbrk;
  49. }
  50. libc_hidden_def (__sbrk)
  51. weak_alias (__sbrk, sbrk)