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