From 5f15d7c5817b07a6b18cbab17342c95cb7b42be4 Mon Sep 17 00:00:00 2001
From: Kuan-Wei Chiu <visitorckw@gmail.com>
Date: Fri, 20 Sep 2024 12:44:40 +0800
Subject: [PATCH] fix CVE-2024-30949

RISC-V: Fix timeval conversion in _gettimeofday()

Replace multiplication with division for microseconds calculation from
nanoseconds in _gettimeofday function.

---
 libgloss/riscv/sys_gettimeofday.c | 23 ++++++++++++++++++++++-
 1 file changed, 22 insertions(+), 1 deletion(-)

diff --git a/libgloss/riscv/sys_gettimeofday.c b/libgloss/riscv/sys_gettimeofday.c
index 457dcbc..5379a89 100644
--- a/libgloss/riscv/sys_gettimeofday.c
+++ b/libgloss/riscv/sys_gettimeofday.c
@@ -1,10 +1,31 @@
 #include <machine/syscall.h>
 #include <sys/time.h>
+#include <stdint.h>
 #include "internal_syscall.h"
 
 /* Get the current time.  Only relatively correct.  */
 int
 _gettimeofday(struct timeval *tp, void *tzp)
 {
-  return syscall_errno (SYS_gettimeofday, tp, 0, 0, 0, 0, 0);
+#if __riscv_xlen == 32
+  struct __timespec64
+  {
+    int64_t tv_sec;         /* Seconds */
+# if BYTE_ORDER == BIG_ENDIAN
+    int32_t __padding;      /* Padding */
+    int32_t tv_nsec;        /* Nanoseconds */
+# else
+    int32_t tv_nsec;        /* Nanoseconds */
+    int32_t __padding;      /* Padding */
+# endif
+  };
+  struct __timespec64 ts64;
+  int rv;
+  rv = syscall_errno (SYS_clock_gettime64, 2, 0, (long)&ts64, 0, 0, 0, 0);
+  tp->tv_sec = ts64.tv_sec;
+  tp->tv_usec = ts64.tv_nsec / 1000;
+  return rv;
+#else
+  return syscall_errno (SYS_gettimeofday, 1, tp, 0, 0, 0, 0, 0);
+#endif
 }
-- 
2.43.0

