Debian Codegraph @

lib/clock_gettime.c

raw
1 /*
2 * Check: a unit test framework for C
3 * Copyright (C) 2001, 2002 Arien Malec
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
18 * MA 02110-1301, USA.
19 */
20
21 #include "libcompat.h"
22
23 #ifdef __APPLE__
24 #include <mach/clock.h>
25 #include <mach/mach.h>
26 #include <mach/mach_time.h>
27 #include <CoreServices/CoreServices.h>
28 #include <unistd.h>
29 #endif
30
31 #define NANOSECONDS_PER_SECOND 1000000000
32
33
34
35 int clock_gettime(clockid_t clk_id CK_ATTRIBUTE_UNUSED, struct timespec *ts)
36 {
37
38 #ifdef __APPLE__
39 /* Some versions of macOS and iOS do not have clock_gettime, use
40 * mach_absolute_time */
41
42 static mach_timebase_info_data_t sTimebaseInfo;
43 uint64_t rawTime;
44 uint64_t nanos;
45
46 rawTime = mach_absolute_time();
47
48 /*
49 * OS X has a function to convert abs time to nano seconds: AbsoluteToNanoseconds
50 * However, the function may not be available as we may not have
51 * access to CoreServices. Because of this, we convert the abs time
52 * to nano seconds manually.
53 */
54
55 /*
56 * First grab the time base used on the system, if this is the first
57 * time we are being called. We can check if the value is uninitialized,
58 * as the denominator will be zero.
59 */
60 if(sTimebaseInfo.denom == 0)
61 {
62 (void)mach_timebase_info(&sTimebaseInfo);
63 }
64
65 /*
66 * Do the conversion. We hope that the multiplication doesn't
67 * overflow; the price you pay for working in fixed point.
68 */
69 nanos = rawTime * sTimebaseInfo.numer / sTimebaseInfo.denom;
70
71 /*
72 * Fill in the timespec container
73 */
74 ts->tv_sec = nanos / NANOSECONDS_PER_SECOND;
75 ts->tv_nsec = nanos - (ts->tv_sec * NANOSECONDS_PER_SECOND);
76 #else
77 /*
78 * As there is no function to fall back onto to get the current
79 * time, zero out the time so the caller will have a sane value.
80 */
81 ts->tv_sec = 0;
82 ts->tv_nsec = 0;
83 #endif
84
85 return 0;
86 }