0002-misc-Implement-grub_strlcpy.patch 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. From 67241595d3dae392589ee74b65cd40ea090d1837 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] 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: ea703528a8581a2ea7e0bad424a70fdf0aec7d8f
  11. Signed-off-by: Thomas Petazzoni <thomas.petazzoni@bootlin.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 1b35a167f..103175480 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)
  64. --
  65. 2.50.1