0001-misc-Implement-grub_strlcpy.patch 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. From ea703528a8581a2ea7e0bad424a70fdf0aec7d8f Mon Sep 17 00:00:00 2001
  2. From: B Horn <b@horn.uk>
  3. Date: Sat, 15 Jun 2024 02:33:08 +0100
  4. Subject: [PATCH 1/2] misc: Implement grub_strlcpy()
  5. grub_strlcpy() acts the same way as strlcpy() does on most *NIX,
  6. returning the length of src and ensuring dest is always NUL
  7. terminated except when size is 0.
  8. Signed-off-by: B Horn <b@horn.uk>
  9. Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
  10. Upstream-Status: Backport [https://git.savannah.gnu.org/cgit/grub.git/commit/?id=ea703528a8581a2ea7e0bad424a70fdf0aec7d8f]
  11. Signed-off-by: Peter Marko <peter.marko@siemens.com>
  12. ---
  13. include/grub/misc.h | 39 +++++++++++++++++++++++++++++++++++++++
  14. 1 file changed, 39 insertions(+)
  15. diff --git a/include/grub/misc.h b/include/grub/misc.h
  16. index 1578f36c3..14d8f37ac 100644
  17. --- a/include/grub/misc.h
  18. +++ b/include/grub/misc.h
  19. @@ -64,6 +64,45 @@ grub_stpcpy (char *dest, const char *src)
  20. return d - 1;
  21. }
  22. +static inline grub_size_t
  23. +grub_strlcpy (char *dest, const char *src, grub_size_t size)
  24. +{
  25. + char *d = dest;
  26. + grub_size_t res = 0;
  27. + /*
  28. + * We do not subtract one from size here to avoid dealing with underflowing
  29. + * the value, which is why to_copy is always checked to be greater than one
  30. + * throughout this function.
  31. + */
  32. + grub_size_t to_copy = size;
  33. +
  34. + /* Copy size - 1 bytes to dest. */
  35. + if (to_copy > 1)
  36. + while ((*d++ = *src++) != '\0' && ++res && --to_copy > 1)
  37. + ;
  38. +
  39. + /*
  40. + * NUL terminate if size != 0. The previous step may have copied a NUL byte
  41. + * if it reached the end of the string, but we know dest[size - 1] must always
  42. + * be a NUL byte.
  43. + */
  44. + if (size != 0)
  45. + dest[size - 1] = '\0';
  46. +
  47. + /* If there is still space in dest, but are here, we reached the end of src. */
  48. + if (to_copy > 1)
  49. + return res;
  50. +
  51. + /*
  52. + * If we haven't reached the end of the string, iterate through to determine
  53. + * the strings total length.
  54. + */
  55. + while (*src++ != '\0' && ++res)
  56. + ;
  57. +
  58. + return res;
  59. +}
  60. +
  61. /* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */
  62. static inline void *
  63. grub_memcpy (void *dest, const void *src, grub_size_t n)