wcsncat_chk.c 2.2 KB

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