File: misc-Implement-grub_strlcpy.patch

package info (click to toggle)
grub2 2.12-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie, trixie-updates
  • size: 70,780 kB
  • sloc: ansic: 424,740; asm: 16,228; sh: 9,525; cpp: 2,095; makefile: 1,590; python: 1,468; sed: 431; lex: 393; yacc: 268; awk: 85; lisp: 54; perl: 31
file content (64 lines) | stat: -rw-r--r-- 1,884 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
From: B Horn <b@horn.uk>
Date: Sat, 15 Jun 2024 02:33:08 +0100
Subject: misc: Implement grub_strlcpy()

grub_strlcpy() acts the same way as strlcpy() does on most *NIX,
returning the length of src and ensuring dest is always NUL
terminated except when size is 0.

Signed-off-by: B Horn <b@horn.uk>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
---
 include/grub/misc.h | 39 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)

diff --git a/include/grub/misc.h b/include/grub/misc.h
index 1b35a16..1031754 100644
--- a/include/grub/misc.h
+++ b/include/grub/misc.h
@@ -64,6 +64,45 @@ grub_stpcpy (char *dest, const char *src)
   return d - 1;
 }
 
+static inline grub_size_t
+grub_strlcpy (char *dest, const char *src, grub_size_t size)
+{
+  char *d = dest;
+  grub_size_t res = 0;
+  /*
+   * We do not subtract one from size here to avoid dealing with underflowing
+   * the value, which is why to_copy is always checked to be greater than one
+   * throughout this function.
+   */
+  grub_size_t to_copy = size;
+
+  /* Copy size - 1 bytes to dest. */
+  if (to_copy > 1)
+    while ((*d++ = *src++) != '\0' && ++res && --to_copy > 1)
+      ;
+
+  /*
+   * NUL terminate if size != 0. The previous step may have copied a NUL byte
+   * if it reached the end of the string, but we know dest[size - 1] must always
+   * be a NUL byte.
+   */
+  if (size != 0)
+    dest[size - 1] = '\0';
+
+  /* If there is still space in dest, but are here, we reached the end of src. */
+  if (to_copy > 1)
+    return res;
+
+  /*
+   * If we haven't reached the end of the string, iterate through to determine
+   * the strings total length.
+   */
+  while (*src++ != '\0' && ++res)
+   ;
+
+  return res;
+}
+
 /* XXX: If grub_memmove is too slow, we must implement grub_memcpy.  */
 static inline void *
 grub_memcpy (void *dest, const void *src, grub_size_t n)