From b0e9842602b22484e7b12974110d23c46e49e18d Mon Sep 17 00:00:00 2001 From: Noah Gold Date: Tue, 29 Sep 2020 20:21:49 -0700 Subject: [PATCH] Update safety comments for DataInit. Previously DataInit did not specify that any implementor `T` must not contain implicit padding, though implementors of DataInit often include a safety statement mentioning that they have no implicit padding. This CL updates DataInit to clarify that any implementor must certify it has no implicit padding to be safe / free of undefined behavior. BUG=none TEST=none (comment only change) Change-Id: Ieddce51949bfa65de65a891deae071a744b0a4ef Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosvm/+/2439301 Reviewed-by: Zach Reizner Tested-by: kokoro Commit-Queue: Noah Gold --- data_model/src/lib.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/data_model/src/lib.rs b/data_model/src/lib.rs index 9bec3a5443..a200c00fb5 100644 --- a/data_model/src/lib.rs +++ b/data_model/src/lib.rs @@ -8,11 +8,18 @@ use std::slice::{from_raw_parts, from_raw_parts_mut}; /// Types for which it is safe to initialize from raw data. /// -/// A type `T` is `DataInit` if and only if it can be initialized by reading its contents from a -/// byte array. This is generally true for all plain-old-data structs. It is notably not true for -/// any type that includes a reference. /// /// Implementing this trait guarantees that it is safe to instantiate the struct with random data. +/// +/// # Safety +/// A type `T` is `DataInit` if it can be initialized by reading its contents from a byte array. +/// This is generally true for all plain-old-data structs. It is notably not true for any type +/// that includes a reference. +/// +/// It is unsafe for `T` to be `DataInit` if `T` contains implicit padding. (LLVM considers access +/// to implicit padding to be undefined behavior, which can cause UB when working with `T`. +/// For details on structure padding in Rust, see +/// https://doc.rust-lang.org/reference/type-layout.html#the-c-representation pub unsafe trait DataInit: Copy + Send + Sync { /// Converts a slice of raw data into a reference of `Self`. ///