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