]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
time-util: encode our assumption that clock_gettime() never can return 0 or USEC_INFINITY
authorLennart Poettering <lennart@amutable.com>
Sun, 12 Apr 2026 19:44:59 +0000 (21:44 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 13 Apr 2026 06:52:43 +0000 (08:52 +0200)
We generally assume that valid times returned by clock_gettime() are > 0
and < USEC_INFINITY. If this wouldn't hold all kinds of things would
break, because we couldn't distuingish our niche values from regular
values anymore.

Let's hence encode our assumptions in C, already to help static
analyzers and LLMs.

Inspired by: https://github.com/systemd/systemd/pull/41601#pullrequestreview-4094645891

src/basic/time-util.c

index 1e426bb8f988be4e3bdd48bf9ccbbc0c696e3892..78c33c7553ce6be3abacc4d74170ec164ed44278 100644 (file)
@@ -49,7 +49,15 @@ usec_t now(clockid_t clock_id) {
 
         assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
 
-        return timespec_load(&ts);
+        usec_t n = timespec_load(&ts);
+
+        /* We use both 0 and USEC_INFINITY as niche values. If the current time collides with either, things are
+         * really weird and really broken. Let's not allow this to go through, it would break too many of our
+         * assumptions in code. */
+        assert(n > 0);
+        assert(n < USEC_INFINITY);
+
+        return n;
 }
 
 nsec_t now_nsec(clockid_t clock_id) {
@@ -57,7 +65,12 @@ nsec_t now_nsec(clockid_t clock_id) {
 
         assert_se(clock_gettime(map_clock_id(clock_id), &ts) == 0);
 
-        return timespec_load_nsec(&ts);
+        nsec_t n = timespec_load_nsec(&ts);
+
+        assert(n > 0);
+        assert(n < NSEC_INFINITY);
+
+        return n;
 }
 
 dual_timestamp* dual_timestamp_now(dual_timestamp *ts) {