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