[m-rev.] diff: fix overflow check in string.m

Peter Wang novalazy at gmail.com
Fri Jun 17 10:49:16 AEST 2011


Branches: main

Fix overflow check for string.substring and other recently deprecated substring
routines.  Signed integer overflow is undefined behaviour in C, and gcc
(by default) actually uses this fact to enable some otherwise dubious
optimisations.

library/string.m:
	Detect overflow in string.convert_endpoints _before_ it happens.

diff --git a/library/string.m b/library/string.m
index 8604de2..fe7aeda 100644
--- a/library/string.m
+++ b/library/string.m
@@ -5560,9 +5560,12 @@ convert_endpoints(Start, Count, ClampStart, ClampEnd) :-
     ( Count =< 0 ->
         ClampEnd = ClampStart
     ;
-        End = ClampStart + Count,
         % Check for overflow.
-        ClampEnd = ( End =< 0 -> max_int ; End )
+        ( ClampStart > max_int - Count ->
+            ClampEnd = max_int
+        ;
+            ClampEnd = ClampStart + Count
+        )
     ).
 
 %-----------------------------------------------------------------------------%

--------------------------------------------------------------------------
mercury-reviews mailing list
Post messages to:       mercury-reviews at csse.unimelb.edu.au
Administrative Queries: owner-mercury-reviews at csse.unimelb.edu.au
Subscriptions:          mercury-reviews-request at csse.unimelb.edu.au
--------------------------------------------------------------------------



More information about the reviews mailing list