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