1
0
mirror of https://github.com/systemd/systemd synced 2024-07-09 04:26:06 +00:00

string-util: allow taking SIZE_MAX as size to shorten to

This is useful for two reasons:

1. it addresses a potential overflow in a graceful way

2. Gives callers the ability to just pass SIZE_MAX for a NOP

Prompted by: #31341
This commit is contained in:
Lennart Poettering 2024-03-06 09:43:09 +01:00 committed by Luca Boccassi
parent 10d50d9eac
commit d49dc7bbe7
2 changed files with 8 additions and 0 deletions

View File

@ -620,6 +620,9 @@ char *cellescape(char *buf, size_t len, const char *s) {
char* strshorten(char *s, size_t l) {
assert(s);
if (l >= SIZE_MAX-1) /* Would not change anything */
return s;
if (strnlen(s, l+1) > l)
s[l] = 0;

View File

@ -299,8 +299,13 @@ TEST(ascii_strlower) {
TEST(strshorten) {
char s[] = "foobar";
assert_se(strlen(strshorten(s, SIZE_MAX)) == 6);
assert_se(strlen(strshorten(s, SIZE_MAX-1)) == 6);
assert_se(strlen(strshorten(s, SIZE_MAX-2)) == 6);
assert_se(strlen(strshorten(s, 6)) == 6);
assert_se(strlen(strshorten(s, 7)) == 6);
assert_se(strlen(strshorten(s, 12)) == 6);
assert_se(strlen(strshorten(s, 5)) == 5);
assert_se(strlen(strshorten(s, 2)) == 2);
assert_se(strlen(strshorten(s, 0)) == 0);
}