xref: /llvm-project/libc/src/time/time.cpp (revision f9c2377fb68e5051b3061186c507f7b87db2a8b2)
1 //===-- Linux implementation of the time function -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/time/time_func.h"
10 
11 #include "hdr/time_macros.h"
12 #include "src/__support/common.h"
13 #include "src/__support/macros/config.h"
14 #include "src/__support/time/clock_gettime.h"
15 #include "src/errno/libc_errno.h"
16 
17 namespace LIBC_NAMESPACE_DECL {
18 // avoid inconsitent clang-format behavior
19 using time_ptr_t = time_t *;
20 LLVM_LIBC_FUNCTION(time_t, time, (time_ptr_t tp)) {
21   struct timespec ts;
22   auto result = internal::clock_gettime(CLOCK_REALTIME, &ts);
23   if (!result.has_value()) {
24     libc_errno = result.error();
25     return -1;
26   }
27 
28   if (tp != nullptr)
29     *tp = time_t(ts.tv_sec);
30   return time_t(ts.tv_sec);
31 }
32 
33 } // namespace LIBC_NAMESPACE_DECL
34