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