sbrk.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* Copyright (C) 1991-2026 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. <https://www.gnu.org/licenses/>. */
  14. /* Mark symbols hidden in static PIE for early self relocation to work. */
  15. #if BUILD_PIE_DEFAULT
  16. # pragma GCC visibility push(hidden)
  17. #endif
  18. #include <errno.h>
  19. #include <libc-internal.h>
  20. #include <stdbool.h>
  21. #include <stdint.h>
  22. #include <unistd.h>
  23. /* Defined in brk.c. */
  24. extern void *__curbrk;
  25. extern int __brk (void *addr);
  26. /* Extend the process's data space by INCREMENT.
  27. If INCREMENT is negative, shrink data space by - INCREMENT.
  28. Return start of new space allocated, or -1 for errors. */
  29. void *
  30. __sbrk (intptr_t increment)
  31. {
  32. /* Controls whether __brk (0) is called to read the brk value from
  33. the kernel. */
  34. bool update_brk = __curbrk == NULL;
  35. #if defined (SHARED) && ! IS_IN (rtld)
  36. if (!__libc_initial)
  37. {
  38. if (increment != 0)
  39. {
  40. /* Do not allow changing the brk from an inner libc because
  41. it cannot be synchronized with the outer libc's brk. */
  42. __set_errno (ENOMEM);
  43. return (void *) -1;
  44. }
  45. /* Querying the kernel's brk value from an inner namespace is
  46. fine. */
  47. update_brk = true;
  48. }
  49. #endif
  50. if (update_brk)
  51. if (__brk (NULL) < 0) /* Initialize the break. */
  52. return (void *) -1;
  53. if (increment == 0)
  54. return __curbrk;
  55. void *oldbrk = __curbrk;
  56. if (increment > 0
  57. ? ((uintptr_t) oldbrk + (uintptr_t) increment < (uintptr_t) oldbrk)
  58. : ((uintptr_t) oldbrk < (uintptr_t) -increment))
  59. {
  60. __set_errno (ENOMEM);
  61. return (void *) -1;
  62. }
  63. if (__brk (oldbrk + increment) < 0)
  64. return (void *) -1;
  65. return oldbrk;
  66. }
  67. libc_hidden_def (__sbrk)
  68. weak_alias (__sbrk, sbrk)