eBPF-based security platform
string: copy a string literal into an array without a length
Daniel Borkmann1f2777659bdd
diff --git a/include/shirudo/string.h b/include/shirudo/string.hindex 3cd683b1..95725e4c 100644--- a/include/shirudo/string.h+++ b/include/shirudo/string.h@@ -45,6 +45,18 @@ int parse_s64(const char *s, size_t len, __s64 min, __s64 max, __s64 *out);*/ssize_t strscpy(char *dst, const char *src, size_t size);+/*+ * Copy the string literal lit, terminator and all, into the array dst.+ * It cannot be cut: a lit that is no string literal, a dst that is a+ * pointer rather than an array, and a lit longer than dst fail the+ * build.+ */+#define strscpy_literal(dst, lit) do { \+ BUILD_BUG_ON_MSG(sizeof(lit) > sizeof(dst) + __must_be_array(dst), \+ #lit " does not fit in " #dst); \+ memcpy(dst, "" lit, sizeof(lit)); \+} while (0)+/** The len bytes at src as a string in the cap bytes at dst, terminated:* 0, -EINVAL when a NUL is among them, where a string would end short ofdiff --git a/testing/unit/string.c b/testing/unit/string.cindex d4839b77..6cb10599 100644--- a/testing/unit/string.c+++ b/testing/unit/string.c@@ -195,6 +195,27 @@ static void strscpy_cuts_and_says_so(void)EXPECT_EQ(none[0], 'x');}+static void strscpy_literal_copies_with_its_terminator(void)+{+ struct {+ char six[6];+ char after;+ } s;+ char big[8], one[1];++ memset(&s, 'x', sizeof(s));+ strscpy_literal(s.six, "hello");+ EXPECT_STREQ(s.six, "hello");+ EXPECT_EQ(s.after, 'x');+ memset(big, 'x', sizeof(big));+ strscpy_literal(big, "hi");+ EXPECT_STREQ(big, "hi");+ EXPECT_EQ(big[3], 'x');+ one[0] = 'x';+ strscpy_literal(one, "");+ EXPECT_STREQ(one, "");+}+static void strsprintf_writes_what_fits_whole(void){char eight[8], big[64];@@ -847,6 +868,7 @@ static const struct unit_case cases[] = {UNIT_CASE(signed_number_keeps_bounds_and_form),UNIT_CASE(strscpy_copies_what_fits_whole),UNIT_CASE(strscpy_cuts_and_says_so),+ UNIT_CASE(strscpy_literal_copies_with_its_terminator),UNIT_CASE(strsprintf_writes_what_fits_whole),UNIT_CASE(strsprintf_leaves_nothing_when_cut),UNIT_CASE(xasprintf_allocates_the_size_needed),