From 46da4c4e090e0412cee0777f1e8b219964781da7 Mon Sep 17 00:00:00 2001
From: Eneas U de Queiroz <cotequeiroz@gmail.com>
Date: Fri, 8 Oct 2021 14:39:52 -0300
Subject: [PATCH] Avoid problems with 64-bit time_t

The clock_gettime() calls are being handled by calling
syscall(__NR_clock_gettime, ...), which is not portable between systems
using 32-bit and 64-bit time_t.  This is being done to avoid having to
link agains librt.

So, use the standard function, and add a test to see if we can compile
a test without the library, including it otherwise.

Signed-off-by: Eneas U de Queiroz <cotequeiroz@gmail.com>
---
 Makefile.flags   | 6 ++++++
 coreutils/date.c | 6 ++----
 libbb/time.c     | 2 +-
 3 files changed, 9 insertions(+), 5 deletions(-)

--- a/Makefile.flags
+++ b/Makefile.flags
@@ -124,6 +124,12 @@ CFLAGS += --sysroot=$(CONFIG_SYSROOT)
 export SYSROOT=$(CONFIG_SYSROOT)
 endif
 
+# glibc versions before 2.17 need to link with -rt to use clock_gettime
+RT_NEEDED := $(shell echo 'int main(void){struct timespec tp; return clock_gettime(CLOCK_MONOTONIC, &tp);}' >rttest.c; $(CC) $(CFLAGS) -include time.h -o /dev/null rttest.c >/dev/null 2>&1 || echo "y"; rm rttest.c)
+ifeq ($(RT_NEEDED),y)
+LDLIBS += rt
+endif
+
 # Android has no separate crypt library
 # gcc-4.2.1 fails if we try to feed C source on stdin:
 #  echo 'int main(void){return 0;}' | $(CC) $(CFLAGS) -lcrypt -o /dev/null -xc -
--- a/coreutils/date.c
+++ b/coreutils/date.c
@@ -37,7 +37,7 @@
 //config:config FEATURE_DATE_NANO
 //config:	bool "Support %[num]N nanosecond format specifier"
 //config:	default n
-//config:	depends on DATE  # syscall(__NR_clock_gettime)
+//config:	depends on DATE  # clock_gettime()
 //config:	select PLATFORM_LINUX
 //config:	help
 //config:	  Support %[num]N format specifier. Adds ~250 bytes of code.
@@ -265,9 +265,7 @@ int date_main(int argc UNUSED_PARAM, cha
 #endif
 	} else {
 #if ENABLE_FEATURE_DATE_NANO
-		/* libc has incredibly messy way of doing this,
-		 * typically requiring -lrt. We just skip all this mess */
-		syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
+		clock_gettime(CLOCK_REALTIME, &ts);
 #else
 		time(&ts.tv_sec);
 #endif
--- a/libbb/time.c
+++ b/libbb/time.c
@@ -243,7 +243,7 @@ char* FAST_FUNC strftime_YYYYMMDDHHMMSS(
  * typically requiring -lrt. We just skip all this mess */
 static void get_mono(struct timespec *ts)
 {
-	if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, ts))
+	if (clock_gettime(CLOCK_MONOTONIC, ts))
 		bb_error_msg_and_die("clock_gettime(MONOTONIC) failed");
 }
 unsigned long long FAST_FUNC monotonic_ns(void)
