]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
shared/utmp-wtmp: avoid gcc warning about strncpy truncation
authorZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 7 May 2019 12:15:46 +0000 (14:15 +0200)
committerZbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Tue, 7 May 2019 12:15:46 +0000 (14:15 +0200)
The fact that strncpy does the truncation is the whole point here, and gcc
shouldn't warn about this. We can avoid the warning and simplify the
whole procedure by directly copying the interesting part.

src/shared/utmp-wtmp.c

index 4b134b6c8ac6b3547a888498f03ac886148a4e67..db4811b118b784bbc8339e649232b307ae669d6f 100644 (file)
@@ -183,16 +183,14 @@ int utmp_put_reboot(usec_t t) {
         return write_entry_both(&store);
 }
 
-_pure_ static const char *sanitize_id(const char *id) {
+static void copy_suffix(char *buf, size_t buf_size, const char *src) {
         size_t l;
 
-        assert(id);
-        l = strlen(id);
-
-        if (l <= sizeof(((struct utmpx*) NULL)->ut_id))
-                return id;
-
-        return id + l - sizeof(((struct utmpx*) NULL)->ut_id);
+        l = strlen(src);
+        if (l < buf_size)
+                strncpy(buf, src, buf_size);
+        else
+                memcpy(buf, src + l - buf_size, buf_size);
 }
 
 int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line, int ut_type, const char *user) {
@@ -207,8 +205,8 @@ int utmp_put_init_process(const char *id, pid_t pid, pid_t sid, const char *line
 
         init_timestamp(&store, 0);
 
-        /* ut_id needs only be nul-terminated if it is shorter than sizeof(ut_id) */
-        strncpy(store.ut_id, sanitize_id(id), sizeof(store.ut_id));
+        /* Copy the whole string if it fits, or just the suffix without the terminating NUL. */
+        copy_suffix(store.ut_id, sizeof(store.ut_id), id);
 
         if (line)
                 strncpy(store.ut_line, basename(line), sizeof(store.ut_line));
@@ -244,8 +242,8 @@ int utmp_put_dead_process(const char *id, pid_t pid, int code, int status) {
 
         setutxent();
 
-        /* ut_id needs only be nul-terminated if it is shorter than sizeof(ut_id) */
-        strncpy(lookup.ut_id, sanitize_id(id), sizeof(lookup.ut_id));
+        /* Copy the whole string if it fits, or just the suffix without the terminating NUL. */
+        copy_suffix(store.ut_id, sizeof(store.ut_id), id);
 
         found = getutxid(&lookup);
         if (!found)