Coverage Report

Created: 2024-06-03 09:43

/libfido2/fuzz/clock.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2021 Yubico AB. All rights reserved.
3
 * Use of this source code is governed by a BSD-style
4
 * license that can be found in the LICENSE file.
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#include <stdint.h>
9
#include <time.h>
10
11
#include "mutator_aux.h"
12
13
/*
14
 * A pseudo-random monotonic clock with a probabilistic discontinuity to
15
 * the end of time (as measured by struct timespec).
16
 */
17
18
extern int prng_up;
19
extern int __wrap_clock_gettime(clockid_t, struct timespec *);
20
extern int __real_clock_gettime(clockid_t, struct timespec *);
21
extern int __wrap_usleep(unsigned int);
22
static TLS struct timespec fuzz_clock;
23
24
static void
25
tick(unsigned int usec)
26
1.32M
{
27
1.32M
        long long drift;
28
29
        /*
30
         * Simulate a jump to the end of time with 0.125% probability.
31
         * This condition should be gracefully handled by callers of
32
         * clock_gettime().
33
         */
34
1.32M
        if (uniform_random(800) < 1) {
35
1.59k
                fuzz_clock.tv_sec = LLONG_MAX;
36
1.59k
                fuzz_clock.tv_nsec = LONG_MAX;
37
1.59k
                return;
38
1.59k
        }
39
40
1.32M
        drift = usec * 1000LL + (long long)uniform_random(10000000); /* 10ms */
41
1.32M
        if (LLONG_MAX - drift < (long long)fuzz_clock.tv_nsec) {
42
1.32k
                fuzz_clock_reset(); /* Not much we can do here. */
43
1.32M
        } else if (drift + (long long)fuzz_clock.tv_nsec < 1000000000) {
44
1.25M
                fuzz_clock.tv_nsec += (long)(drift);
45
1.25M
        } else {
46
65.6k
                fuzz_clock.tv_sec  += (long)(drift / 1000000000);
47
65.6k
                fuzz_clock.tv_nsec += (long)(drift % 1000000000);
48
65.6k
        }
49
1.32M
}
50
51
int
52
__wrap_clock_gettime(clockid_t clk_id, struct timespec *tp)
53
1.32M
{
54
1.32M
        if (!prng_up || clk_id != CLOCK_MONOTONIC)
55
0
                return __real_clock_gettime(clk_id, tp);
56
1.32M
        if (uniform_random(400) < 1)
57
2.22k
                return -1;
58
59
1.32M
        tick(0);
60
1.32M
        *tp = fuzz_clock;
61
62
1.32M
        return 0;
63
1.32M
}
64
65
int
66
__wrap_usleep(unsigned int usec)
67
2.50k
{
68
2.50k
        if (uniform_random(400) < 1)
69
3
                return -1;
70
71
2.49k
        tick(usec);
72
73
2.49k
        return 0;
74
2.50k
}
75
76
void
77
fuzz_clock_reset(void)
78
31.4k
{
79
31.4k
        memset(&fuzz_clock, 0, sizeof(fuzz_clock));
80
31.4k
}