Skip to content

Commit bf042e2

Browse files
committed
Port time() and times()
1 parent 39e65a4 commit bf042e2

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

libc-bottom-half/clocks/times.c

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
#define _WASI_EMULATED_PROCESS_CLOCKS
22
#include <time.h>
33
#include <sys/times.h>
4+
#ifdef __wasilibc_use_wasip2
5+
#include <wasi/wasip2.h>
6+
#else
47
#include <wasi/api.h>
8+
#endif
59
#include <common/time.h>
610

711
_Static_assert(
@@ -14,6 +18,17 @@ _Static_assert(
1418
clock_t __clock(void);
1519

1620
clock_t times(struct tms *buffer) {
21+
#ifdef __wasilibc_use_wasip2
22+
clock_t user = __clock();
23+
*buffer = (struct tms){
24+
.tms_utime = user,
25+
// WASI doesn't provide a way to spawn a new process, so always 0.
26+
.tms_cutime = 0
27+
};
28+
29+
monotonic_clock_instant_t realtime = monotonic_clock_now();
30+
#else
31+
1732
__wasi_timestamp_t user = __clock();
1833
*buffer = (struct tms){
1934
.tms_utime = user,
@@ -23,5 +38,6 @@ clock_t times(struct tms *buffer) {
2338

2439
__wasi_timestamp_t realtime = 0;
2540
(void)__wasi_clock_time_get(__WASI_CLOCKID_MONOTONIC, 0, &realtime);
41+
#endif
2642
return realtime;
2743
}

libc-bottom-half/cloudlibc/src/libc/time/time.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,22 @@
44

55
#include <common/time.h>
66

7+
#ifdef __wasilibc_use_wasip2
8+
#include <wasi/wasip2.h>
9+
#else
710
#include <wasi/api.h>
11+
#endif
812
#include <time.h>
913

1014
time_t time(time_t *tloc) {
15+
#ifdef __wasilibc_use_wasip2
16+
wall_clock_datetime_t res;
17+
wall_clock_now(&res);
18+
uint64_t ts = (res.seconds * NSEC_PER_SEC) + res.nanoseconds;
19+
#else
1120
__wasi_timestamp_t ts = 0;
1221
(void)__wasi_clock_time_get(__WASI_CLOCKID_REALTIME, NSEC_PER_SEC, &ts);
22+
#endif
1323
if (tloc != NULL)
1424
*tloc = ts / NSEC_PER_SEC;
1525
return ts / NSEC_PER_SEC;

test/src/misc/time_and_times.c

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//! add-flags.py(CFLAGS): -D_WASI_EMULATED_PROCESS_CLOCKS
2+
//! add-flags.py(LDFLAGS): -lwasi-emulated-process-clocks
3+
#include <stdlib.h>
4+
#include <stdio.h>
5+
#include <time.h>
6+
#include <string.h>
7+
#include <errno.h>
8+
#include <sys/times.h>
9+
#include "test.h"
10+
11+
#define TEST(c, ...) ((c) ? 1 : (t_error(#c" failed: " __VA_ARGS__),0))
12+
13+
int main(void)
14+
{
15+
time_t t;
16+
struct tms buffer;
17+
18+
clock_t result = times(&buffer);
19+
TEST(result > 0);
20+
TEST(buffer.tms_utime > 0);
21+
TEST(buffer.tms_cutime == 0); // always 0 under WASI
22+
23+
time_t t1 = time(&t);
24+
TEST(t==t1);
25+
TEST(t > 0);
26+
27+
return t_status;
28+
}

0 commit comments

Comments
 (0)