[3/7] Fix overflow errors in sbttous and sbttoms

Message ID 20250710021918.112394-4-sebastian.huber@embedded-brains.de
State New
Headers
Series Synchronize <sys/time.h> with FreeBSD |

Commit Message

Sebastian Huber July 10, 2025, 2:19 a.m. UTC
  From: Alan Somers <asomers@FreeBSD.org>

Both of these functions would overflow for very large inputs.  Add tests
for them.  Also, add tests for the inverse functions, *stosbt, whose
overflow errors were fixed by 4c30b9ecd47.

PR:		263073
MFC after:	1 week
Sponsored by:	Axcient
Reviewed by:	imp
Differential Revision: https://reviews.freebsd.org/D34809
---
 newlib/libc/include/sys/time.h | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
  

Patch

diff --git a/newlib/libc/include/sys/time.h b/newlib/libc/include/sys/time.h
index 006d1f663..35575d59d 100644
--- a/newlib/libc/include/sys/time.h
+++ b/newlib/libc/include/sys/time.h
@@ -220,7 +220,11 @@  static __inline int64_t
 sbttous(sbintime_t _sbt)
 {
 
-	return ((1000000 * _sbt) >> 32);
+#ifdef KASSERT
+	KASSERT(_sbt >= 0, ("Negative values illegal for sbttous: %jx", _sbt));
+#endif
+	return ((_sbt >> 32) * 1000000 +
+		(1000000 * (_sbt & 0xffffffffu) >> 32));
 }
 
 static __inline sbintime_t
@@ -240,8 +244,10 @@  ustosbt(int64_t _us)
 static __inline int64_t
 sbttoms(sbintime_t _sbt)
 {
-
-	return ((1000 * _sbt) >> 32);
+#ifdef KASSERT
+	KASSERT(_sbt >= 0, ("Negative values illegal for sbttoms: %jx", _sbt));
+#endif
+	return ((_sbt >> 32) * 1000 + (1000 * (_sbt & 0xffffffffu) >> 32));
 }
 
 static __inline sbintime_t