[flang-commits] [PATCH] D88798: [flang] Fix heap overflow in Real formatting.

Michael Kruse via Phabricator via flang-commits flang-commits at lists.llvm.org
Sun Oct 4 04:15:30 PDT 2020


Meinersbur created this revision.
Meinersbur added reviewers: isuruf, sscalpone, klausler, tskeith, DavidTruby.
Meinersbur added a project: Flang.
Herald added a reviewer: jdoerfert.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.
Meinersbur requested review of this revision.

The reinterpret_cast is problematic because 1. it violates the strict aliasing assumption and 2. the types can be of different size. In particular, BinaryFloatingPointNumber is always a power-of-2 whereas the source type can be smaller (like for 80-bit real). Therefore, when dereferencing the BinaryFloatingPointNumber, the accesses exceeds the source type's allocation size.

Fix by using memcpy to a zero-initialized buffer of the larger size.

Found using AddressSanitizer.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D88798

Files:
  flang/lib/Evaluate/real.cpp


Index: flang/lib/Evaluate/real.cpp
===================================================================
--- flang/lib/Evaluate/real.cpp
+++ flang/lib/Evaluate/real.cpp
@@ -496,14 +496,17 @@
     }
   } else {
     using B = decimal::BinaryFloatingPointNumber<P>;
-    const auto *value{reinterpret_cast<const B *>(this)};
+    typename B::RawType b{0};
+    assert(sizeof b >= sizeof word_);
+    memcpy(&b, &word_, sizeof word_);
+    B value{b};
     char buffer[24000]; // accommodate real*16
     decimal::DecimalConversionFlags flags{}; // default: exact representation
     if (minimal) {
       flags = decimal::Minimize;
     }
     auto result{decimal::ConvertToDecimal<P>(buffer, sizeof buffer, flags,
-        static_cast<int>(sizeof buffer), decimal::RoundNearest, *value)};
+        static_cast<int>(sizeof buffer), decimal::RoundNearest, value)};
     const char *p{result.str};
     if (DEREF(p) == '-' || *p == '+') {
       o << *p++;


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D88798.296039.patch
Type: text/x-patch
Size: 951 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20201004/70839c3d/attachment.bin>


More information about the flang-commits mailing list