[llvm] r301373 - [Support] Avoid UB in sys::fs::perms::operator~. NFC.

Ahmed Bougacha via llvm-commits llvm-commits at lists.llvm.org
Tue Apr 25 17:48:29 PDT 2017


Author: ab
Date: Tue Apr 25 19:48:28 2017
New Revision: 301373

URL: http://llvm.org/viewvc/llvm-project?rev=301373&view=rev
Log:
[Support] Avoid UB in sys::fs::perms::operator~. NFC.

This was exposed in r297945 and r301220: the intermediate complement
is a 32-bit value, and casting it to 'perms' invokes UB.

Modified:
    llvm/trunk/include/llvm/Support/FileSystem.h

Modified: llvm/trunk/include/llvm/Support/FileSystem.h
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/include/llvm/Support/FileSystem.h?rev=301373&r1=301372&r2=301373&view=diff
==============================================================================
--- llvm/trunk/include/llvm/Support/FileSystem.h (original)
+++ llvm/trunk/include/llvm/Support/FileSystem.h Tue Apr 25 19:48:28 2017
@@ -116,7 +116,9 @@ inline perms &operator&=(perms &l, perms
   return l;
 }
 inline perms operator~(perms x) {
-  return static_cast<perms>(~static_cast<unsigned short>(x));
+  // Avoid UB by explicitly truncating the (unsigned) ~ result.
+  return static_cast<perms>(
+      static_cast<unsigned short>(~static_cast<unsigned short>(x)));
 }
 
 class UniqueID {




More information about the llvm-commits mailing list