Fix potential handle reuse in Mojo

Fixed: 1270333
Change-Id: Ife188d519092e4e634355fd53d97c85009771b76
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3414063
Auto-Submit: Ken Rockot <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/main@{#962946}
diff --git a/mojo/core/handle_table.cc b/mojo/core/handle_table.cc
index 9426281d..a044f1c8 100644
--- a/mojo/core/handle_table.cc
+++ b/mojo/core/handle_table.cc
@@ -65,13 +65,19 @@
     const std::vector<Dispatcher::DispatcherInTransit>& dispatchers,
     MojoHandle* handles) {
   // Oops, we're out of handles.
-  if (next_available_handle_ == MOJO_HANDLE_INVALID)
+  if (next_available_handle_ == MOJO_HANDLE_INVALID) {
     return false;
+  }
 
-  DCHECK_LE(dispatchers.size(), std::numeric_limits<uint32_t>::max());
+  // MOJO_HANDLE_INVALID is zero.
+  DCHECK_GE(next_available_handle_, 1u);
+
   // If this insertion would cause handle overflow, we're out of handles.
-  if (next_available_handle_ + dispatchers.size() < next_available_handle_)
+  const uint32_t num_handles_available =
+      std::numeric_limits<uint32_t>::max() - next_available_handle_ + 1;
+  if (num_handles_available < dispatchers.size()) {
     return false;
+  }
 
   for (size_t i = 0; i < dispatchers.size(); ++i) {
     MojoHandle handle = MOJO_HANDLE_INVALID;