xref: /aosp_15_r20/external/pigweed/pw_chrono/wrap_time_system_clock.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 // This file provides an implementation of time and gettimeofday that can be
16 // used with ld's --wrap option.
17 
18 #include <time.h>
19 
20 #if __has_include(<sys/time.h>)
21 #include <sys/time.h>
22 #endif  // __has_include(<sys/time.h>)
23 
24 #include <sys/time.h>
25 
26 #include <chrono>
27 
28 #include "pw_chrono/system_clock.h"
29 
30 namespace pw::chrono {
31 
__wrap_time(time_t * t)32 extern "C" time_t __wrap_time(time_t* t) {
33   const pw::chrono::SystemClock::time_point now =
34       pw::chrono::SystemClock::now();
35   const time_t ret =
36       std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch())
37           .count();
38   if (t) {
39     *t = ret;
40   }
41   return ret;
42 }
43 
44 #if __has_include(<sys/time.h>)
45 
__wrap_gettimeofday(struct timeval * tv,void * tz)46 extern "C" int __wrap_gettimeofday(struct timeval* tv, void* tz) {
47   using namespace std::chrono_literals;
48   // The use of the timezone structure is obsolete (see docs "man
49   // gettimeofday"). Thus we don't consider it.
50   (void)tz;
51   // Get time since epoch from system clock.
52   const pw::chrono::SystemClock::time_point now =
53       pw::chrono::SystemClock::now();
54   const auto usec_since_epoch =
55       std::chrono::duration_cast<std::chrono::microseconds>(
56           now.time_since_epoch());
57   tv->tv_sec = (usec_since_epoch / 1s);
58   tv->tv_usec = (usec_since_epoch % 1s).count();
59   return 0;
60 }
61 
62 #endif  // __has_include(<sys/time.h>)
63 
64 }  // namespace pw::chrono
65