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