Found by Vittorio Zecca when using the sanitizer on libgomp
(bootstrap-ubsan) on pr66311.f90, which uses '(-huge(0_16))-1'.

The error then occurs in libgfortran/runtime/string.c's
  gfc_itoa (GFC_INTEGER_LARGEST n, char *buffer, size_t len)
where (as shown 'n') is signed and 't' is:
  GFC_UINTEGER_LARGEST t;

As proposed by Vittorio (comment 2) and acknowledged by Jakub
(comment 3), the conversion to UINT has to happen before the
negation.


For completeness, the result is the following.
(Test is similar in pr66311.f90, albeit slightly different.)

      write(buffer,*) huge(0_16)
      if (buffer /= "  170141183460469231731687303715884105727") stop 1

      write(buffer,*) huge(0_16)-1
      if (buffer /= "  170141183460469231731687303715884105726") stop 2

      write(buffer,*) -(huge(0_16)-1)
      if (buffer /= " -170141183460469231731687303715884105726") stop 3

      ! Undefined behaviour as (-huge(0_16)) overflows:
      write(buffer,*) -huge(0_16)-1
      if (buffer /= " -170141183460469231731687303715884105728") stop 4


I intent to commit the patch later as obvious unless there are further comments.

Tobias

-----------------
Mentor Graphics (Deutschland) GmbH, Arnulfstrasse 201, 80634 München 
Registergericht München HRB 106955, Geschäftsführer: Thomas Heurung, Frank 
Thürauf
libgfortran: Fix negation for largest integer [PR81986]

libgfortran/ChangeLog:

2021-03-01  Vittorio Zecca  <zec...@gmail.com>
	    Tobias Burnus  <tob...@codesourcery.com>

	PR libfortran/81986
	* runtime/string.c (gfc_itoa):

diff --git a/libgfortran/runtime/string.c b/libgfortran/runtime/string.c
index 37c4da0a98a..536a9cd3f2b 100644
--- a/libgfortran/runtime/string.c
+++ b/libgfortran/runtime/string.c
@@ -196,7 +196,7 @@ gfc_itoa (GFC_INTEGER_LARGEST n, char *buffer, size_t len)
   if (n < 0)
     {
       negative = 1;
-      t = -n; /*must use unsigned to protect from overflow*/
+      t = -(GFC_UINTEGER_LARGEST) n;  /* Must use unsigned to protect from overflow. */
     }
 
   p = buffer + GFC_ITOA_BUF_SIZE - 1;

Reply via email to