From f1444aaf7211aa81e5b6fbbaa389619d5d65fa98 Mon Sep 17 00:00:00 2001 From: Chirantan Ekbote Date: Mon, 30 Nov 2020 17:14:49 +0900 Subject: [PATCH] data_model: Implement Send + Sync for IoSliceMut Pointers in rust don't implement Send or Sync and so any struct that contains a raw pointer doesn't implement those traits either. However, there's nothing inherently unsafe about sending a pointer across thread boundaries. The only unsafety comes from actually de-referencing the pointer, which already requires an unsafe block. Explicitly implement Send + Sync for IoSliceMut since the iovec internally holds a *mut c_void, which prevents those traits from being auto-implemented. Send + Sync is also implemented by std::io::IoSliceMut, which is almost exactly the same as our IoSliceMut, so that can provide some additional reassurance that this is safe. Also add a missing copyright header in the file. BUG=none TEST=unit tests Change-Id: Ic21fc0de9b29923420f36ab166fec80d4d4cf2e3 Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/2571146 Reviewed-by: Noah Gold Reviewed-by: Dylan Reid Tested-by: kokoro Commit-Queue: Chirantan Ekbote --- data_model/src/sys.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/data_model/src/sys.rs b/data_model/src/sys.rs index 8201c43809..646cced4ce 100644 --- a/data_model/src/sys.rs +++ b/data_model/src/sys.rs @@ -1,3 +1,7 @@ +// Copyright 2020 The Chromium OS Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + use std::ffi::c_void; use std::fmt::{self, Debug}; use std::marker::PhantomData; @@ -70,6 +74,13 @@ impl<'a> IoSliceMut<'a> { } } +// It's safe to implement Send + Sync for this type for the same reason that `std::io::IoSliceMut` +// is Send + Sync. Internally, it contains a pointer and a length. The integer length is safely Send +// + Sync. There's nothing wrong with sending a pointer between threads and de-referencing the +// pointer requires an unsafe block anyway. See also https://github.com/rust-lang/rust/pull/70342. +unsafe impl<'a> Send for IoSliceMut<'a> {} +unsafe impl<'a> Sync for IoSliceMut<'a> {} + struct DebugIovec(iovec); impl Debug for DebugIovec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {