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