From b83524b19ca6e5e58dded77fad37f17a177766ff 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 1/2] 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>

--- 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 -e '#include <time.h>\nint main(void){struct timespec tp; return clock_gettime(CLOCK_MONOTONIC, &tp);}' >rttest.c; $(CC) $(CFLAGS) -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)
--- a/runit/runsv.c
+++ b/runit/runsv.c
@@ -55,7 +55,7 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAG
  * typically requiring -lrt. We just skip all this mess */
 static void gettimeofday_ns(struct timespec *ts)
 {
-	syscall(__NR_clock_gettime, CLOCK_REALTIME, ts);
+	clock_gettime(CLOCK_REALTIME, ts);
 }
 #else
 static void gettimeofday_ns(struct timespec *ts)