strncat_chk.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include <string.h>
  15. #include <memcopy.h>
  16. char *
  17. __strncat_chk (char *s1, const char *s2, size_t n, size_t s1len)
  18. {
  19. char c;
  20. char *s = s1;
  21. /* Find the end of S1. */
  22. do
  23. {
  24. if (__glibc_unlikely (s1len-- == 0))
  25. __chk_fail ();
  26. c = *s1++;
  27. }
  28. while (c != '\0');
  29. /* Make S1 point before next character, so we can increment
  30. it while memory is read (wins on pipelined cpus). */
  31. ++s1len;
  32. s1 -= 2;
  33. if (n >= 4)
  34. {
  35. size_t n4 = n >> 2;
  36. do
  37. {
  38. if (__glibc_unlikely (s1len-- == 0))
  39. __chk_fail ();
  40. c = *s2++;
  41. *++s1 = c;
  42. if (c == '\0')
  43. return s;
  44. if (__glibc_unlikely (s1len-- == 0))
  45. __chk_fail ();
  46. c = *s2++;
  47. *++s1 = c;
  48. if (c == '\0')
  49. return s;
  50. if (__glibc_unlikely (s1len-- == 0))
  51. __chk_fail ();
  52. c = *s2++;
  53. *++s1 = c;
  54. if (c == '\0')
  55. return s;
  56. if (__glibc_unlikely (s1len-- == 0))
  57. __chk_fail ();
  58. c = *s2++;
  59. *++s1 = c;
  60. if (c == '\0')
  61. return s;
  62. } while (--n4 > 0);
  63. n &= 3;
  64. }
  65. while (n > 0)
  66. {
  67. if (__glibc_unlikely (s1len-- == 0))
  68. __chk_fail ();
  69. c = *s2++;
  70. *++s1 = c;
  71. if (c == '\0')
  72. return s;
  73. n--;
  74. }
  75. if (c != '\0')
  76. {
  77. if (__glibc_unlikely (s1len-- == 0))
  78. __chk_fail ();
  79. *++s1 = '\0';
  80. }
  81. return s;
  82. }