cd486f
cd486f
# HG changeset patch
cd486f
# User Jed Davis <jld@mozilla.com>
cd486f
# Date 1526943705 21600
cd486f
# Node ID 6bb3adfa15c6877f7874429462dad88f8c978c4f
cd486f
# Parent  4c71c8454879c841871ecf3afb7dbdc96bad97fc
cd486f
Bug 1436242 - Avoid undefined behavior in IPC fd-passing code.  r=froydnj
cd486f
cd486f
MozReview-Commit-ID: 3szIPUssgF5
cd486f
cd486f
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_posix.cc b/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
cd486f
--- a/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
cd486f
+++ b/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
cd486f
@@ -418,20 +418,37 @@ bool Channel::ChannelImpl::ProcessIncomi
cd486f
     const int* fds;
cd486f
     unsigned num_fds;
cd486f
     unsigned fds_i = 0;  // the index of the first unused descriptor
cd486f
 
cd486f
     if (input_overflow_fds_.empty()) {
cd486f
       fds = wire_fds;
cd486f
       num_fds = num_wire_fds;
cd486f
     } else {
cd486f
-      const size_t prev_size = input_overflow_fds_.size();
cd486f
-      input_overflow_fds_.resize(prev_size + num_wire_fds);
cd486f
-      memcpy(&input_overflow_fds_[prev_size], wire_fds,
cd486f
-             num_wire_fds * sizeof(int));
cd486f
+      // This code may look like a no-op in the case where
cd486f
+      // num_wire_fds == 0, but in fact:
cd486f
+      //
cd486f
+      // 1. wire_fds will be nullptr, so passing it to memcpy is
cd486f
+      // undefined behavior according to the C standard, even though
cd486f
+      // the memcpy length is 0.
cd486f
+      //
cd486f
+      // 2. prev_size will be an out-of-bounds index for
cd486f
+      // input_overflow_fds_; this is undefined behavior according to
cd486f
+      // the C++ standard, even though the element only has its
cd486f
+      // pointer taken and isn't accessed (and the corresponding
cd486f
+      // operation on a C array would be defined).
cd486f
+      //
cd486f
+      // UBSan makes #1 a fatal error, and assertions in libstdc++ do
cd486f
+      // the same for #2 if enabled.
cd486f
+      if (num_wire_fds > 0) {
cd486f
+        const size_t prev_size = input_overflow_fds_.size();
cd486f
+        input_overflow_fds_.resize(prev_size + num_wire_fds);
cd486f
+        memcpy(&input_overflow_fds_[prev_size], wire_fds,
cd486f
+               num_wire_fds * sizeof(int));
cd486f
+      }
cd486f
       fds = &input_overflow_fds_[0];
cd486f
       num_fds = input_overflow_fds_.size();
cd486f
     }
cd486f
 
cd486f
     // The data for the message we're currently reading consists of any data
cd486f
     // stored in incoming_message_ followed by data in input_buf_ (followed by
cd486f
     // other messages).
cd486f
 
cd486f