From de1865bd6d5871037ad9a463b54e24020709d392 Mon Sep 17 00:00:00 2001 From: Alistair Francis Date: Tue, 7 Nov 2023 12:32:57 +1000 Subject: [PATCH] libtock: Implement gettimeasticks Implement a helper function for the _gettimeofday() function, which can be used to fix build issues with C code that uses the gettimeofday syscall. Signed-off-by: Alistair Francis --- libtock/alarm.h | 14 ++++++++++++++ libtock/alarm_timer.c | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/libtock/alarm.h b/libtock/alarm.h index d79688b3c..9e82a884f 100644 --- a/libtock/alarm.h +++ b/libtock/alarm.h @@ -31,6 +31,8 @@ extern "C" { #include "tock.h" +#include + /** \brief Opaque handle to a single-shot alarm. * * An opaque handle to an alarm created by `alarm_at` or `alarm_in`. Memory @@ -69,6 +71,18 @@ int alarm_at(uint32_t reference, uint32_t dt, subscribe_upcall, void*, alarm_t * */ void alarm_cancel(alarm_t*); +// Use this to implement _gettimeofday yourself as libtock-c doesn't provide +// an implementation. +// +// See https://github.com/tock/libtock-c/pull/355#issuecomment-1841351091 for +// more details +// +// ```c +// int _gettimeofday(struct timeval *tv, void *tzvp) { +// return gettimeasticks(tv, tzvp); +// } +// ``` +int gettimeasticks(struct timeval *tv, void *tzvp); #ifdef __cplusplus } diff --git a/libtock/alarm_timer.c b/libtock/alarm_timer.c index bd5a2063c..27ef8b572 100644 --- a/libtock/alarm_timer.c +++ b/libtock/alarm_timer.c @@ -211,3 +211,19 @@ int yield_for_with_timeout(bool* cond, uint32_t ms) { timer_cancel(&timer); return RETURNCODE_SUCCESS; } + +int gettimeasticks(struct timeval *tv, __attribute__ ((unused)) void *tzvp) +{ + uint32_t frequency, now, seconds, remainder; + + alarm_internal_frequency(&frequency); + alarm_internal_read(&now); + + seconds = now / frequency; + remainder = now % frequency; + + tv->tv_sec = seconds; + tv->tv_usec = (remainder * 1000 * 1000) / frequency; + + return 0; +}