-
Notifications
You must be signed in to change notification settings - Fork 105
/
lib.rs
5650 lines (5281 loc) · 232 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Fuchsia Authors
//
// Licensed under the 2-Clause BSD License <LICENSE-BSD or
// https://opensource.org/license/bsd-2-clause>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
// After updating the following doc comment, make sure to run the following
// command to update `README.md` based on its contents:
//
// ./generate-readme.sh > README.md
//! *<span style="font-size: 100%; color:grey;">Want to help improve zerocopy?
//! Fill out our [user survey][user-survey]!</span>*
//!
//! ***<span style="font-size: 140%">Fast, safe, <span
//! style="color:red;">compile error</span>. Pick two.</span>***
//!
//! Zerocopy makes zero-cost memory manipulation effortless. We write `unsafe`
//! so you don't have to.
//!
//! # Overview
//!
//! Zerocopy provides four core marker traits, each of which can be derived
//! (e.g., `#[derive(FromZeroes)]`):
//! - [`FromZeroes`] indicates that a sequence of zero bytes represents a valid
//! instance of a type
//! - [`FromBytes`] indicates that a type may safely be converted from an
//! arbitrary byte sequence
//! - [`AsBytes`] indicates that a type may safely be converted *to* a byte
//! sequence
//! - [`Unaligned`] indicates that a type's alignment requirement is 1
//!
//! Types which implement a subset of these traits can then be converted to/from
//! byte sequences with little to no runtime overhead.
//!
//! Zerocopy also provides byte-order aware integer types that support these
//! conversions; see the [`byteorder`] module. These types are especially useful
//! for network parsing.
//!
//! [user-survey]: https://docs.google.com/forms/d/e/1FAIpQLSdzBNTN9tzwsmtyZxRFNL02K36IWCdHWW2ZBckyQS2xiO3i8Q/viewform?usp=published_options
//!
//! # Cargo Features
//!
//! - **`alloc`**
//! By default, `zerocopy` is `no_std`. When the `alloc` feature is enabled,
//! the `alloc` crate is added as a dependency, and some allocation-related
//! functionality is added.
//!
//! - **`byteorder`** (enabled by default)
//! Adds the [`byteorder`] module and a dependency on the `byteorder` crate.
//! The `byteorder` module provides byte order-aware equivalents of the
//! multi-byte primitive numerical types. Unlike their primitive equivalents,
//! the types in this module have no alignment requirement and support byte
//! order conversions. This can be useful in handling file formats, network
//! packet layouts, etc which don't provide alignment guarantees and which may
//! use a byte order different from that of the execution platform.
//!
//! - **`derive`**
//! Provides derives for the core marker traits via the `zerocopy-derive`
//! crate. These derives are re-exported from `zerocopy`, so it is not
//! necessary to depend on `zerocopy-derive` directly.
//!
//! However, you may experience better compile times if you instead directly
//! depend on both `zerocopy` and `zerocopy-derive` in your `Cargo.toml`,
//! since doing so will allow Rust to compile these crates in parallel. To do
//! so, do *not* enable the `derive` feature, and list both dependencies in
//! your `Cargo.toml` with the same leading non-zero version number; e.g:
//!
//! ```toml
//! [dependencies]
//! zerocopy = "0.X"
//! zerocopy-derive = "0.X"
//! ```
//!
//! - **`simd`**
//! When the `simd` feature is enabled, `FromZeroes`, `FromBytes`, and
//! `AsBytes` impls are emitted for all stable SIMD types which exist on the
//! target platform. Note that the layout of SIMD types is not yet stabilized,
//! so these impls may be removed in the future if layout changes make them
//! invalid. For more information, see the Unsafe Code Guidelines Reference
//! page on the [layout of packed SIMD vectors][simd-layout].
//!
//! - **`simd-nightly`**
//! Enables the `simd` feature and adds support for SIMD types which are only
//! available on nightly. Since these types are unstable, support for any type
//! may be removed at any point in the future.
//!
//! [simd-layout]: https://rust-lang.github.io/unsafe-code-guidelines/layout/packed-simd-vectors.html
//!
//! # Security Ethos
//!
//! Zerocopy is expressly designed for use in security-critical contexts. We
//! strive to ensure that that zerocopy code is sound under Rust's current
//! memory model, and *any future memory model*. We ensure this by:
//! - **...not 'guessing' about Rust's semantics.**
//! We annotate `unsafe` code with a precise rationale for its soundness that
//! cites a relevant section of Rust's official documentation. When Rust's
//! documented semantics are unclear, we work with the Rust Operational
//! Semantics Team to clarify Rust's documentation.
//! - **...rigorously testing our implementation.**
//! We run tests using [Miri], ensuring that zerocopy is sound across a wide
//! array of supported target platforms of varying endianness and pointer
//! width, and across both current and experimental memory models of Rust.
//! - **...formally proving the correctness of our implementation.**
//! We apply formal verification tools like [Kani][kani] to prove zerocopy's
//! correctness.
//!
//! For more information, see our full [soundness policy].
//!
//! [Miri]: https://github.com/rust-lang/miri
//! [Kani]: https://github.com/model-checking/kani
//! [soundness policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#soundness
//!
//! # Relationship to Project Safe Transmute
//!
//! [Project Safe Transmute] is an official initiative of the Rust Project to
//! develop language-level support for safer transmutation. The Project consults
//! with crates like zerocopy to identify aspects of safer transmutation that
//! would benefit from compiler support, and has developed an [experimental,
//! compiler-supported analysis][mcp-transmutability] which determines whether,
//! for a given type, any value of that type may be soundly transmuted into
//! another type. Once this functionality is sufficiently mature, zerocopy
//! intends to replace its internal transmutability analysis (implemented by our
//! custom derives) with the compiler-supported one. This change will likely be
//! an implementation detail that is invisible to zerocopy's users.
//!
//! Project Safe Transmute will not replace the need for most of zerocopy's
//! higher-level abstractions. The experimental compiler analysis is a tool for
//! checking the soundness of `unsafe` code, not a tool to avoid writing
//! `unsafe` code altogether. For the foreseeable future, crates like zerocopy
//! will still be required in order to provide higher-level abstractions on top
//! of the building block provided by Project Safe Transmute.
//!
//! [Project Safe Transmute]: https://rust-lang.github.io/rfcs/2835-project-safe-transmute.html
//! [mcp-transmutability]: https://github.com/rust-lang/compiler-team/issues/411
//!
//! # MSRV
//!
//! See our [MSRV policy].
//!
//! [MSRV policy]: https://github.com/google/zerocopy/blob/main/POLICIES.md#msrv
// Sometimes we want to use lints which were added after our MSRV.
// `unknown_lints` is `warn` by default and we deny warnings in CI, so without
// this attribute, any unknown lint would cause a CI failure when testing with
// our MSRV.
#![allow(unknown_lints)]
#![deny(renamed_and_removed_lints)]
#![deny(
anonymous_parameters,
deprecated_in_future,
illegal_floating_point_literal_pattern,
late_bound_lifetime_arguments,
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
path_statements,
patterns_in_fns_without_body,
rust_2018_idioms,
trivial_numeric_casts,
unreachable_pub,
unsafe_op_in_unsafe_fn,
unused_extern_crates,
unused_qualifications,
variant_size_differences
)]
#![cfg_attr(
__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS,
deny(fuzzy_provenance_casts, lossy_provenance_casts)
)]
#![deny(
clippy::all,
clippy::alloc_instead_of_core,
clippy::arithmetic_side_effects,
clippy::as_underscore,
clippy::assertions_on_result_states,
clippy::as_conversions,
clippy::correctness,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::get_unwrap,
clippy::indexing_slicing,
clippy::missing_inline_in_public_items,
clippy::missing_safety_doc,
clippy::obfuscated_if_else,
clippy::perf,
clippy::print_stdout,
clippy::std_instead_of_core,
clippy::style,
clippy::suspicious,
clippy::todo,
clippy::undocumented_unsafe_blocks,
clippy::unimplemented,
clippy::unnested_or_patterns,
clippy::unwrap_used,
clippy::use_debug
)]
#![deny(
rustdoc::bare_urls,
rustdoc::broken_intra_doc_links,
rustdoc::invalid_codeblock_attributes,
rustdoc::invalid_html_tags,
rustdoc::invalid_rust_codeblocks,
rustdoc::missing_crate_level_docs,
rustdoc::private_intra_doc_links
)]
// In test code, it makes sense to weight more heavily towards concise, readable
// code over correct or debuggable code.
#![cfg_attr(any(test, kani), allow(
// In tests, you get line numbers and have access to source code, so panic
// messages are less important. You also often unwrap a lot, which would
// make expect'ing instead very verbose.
clippy::unwrap_used,
// In tests, there's no harm to "panic risks" - the worst that can happen is
// that your test will fail, and you'll fix it. By contrast, panic risks in
// production code introduce the possibly of code panicking unexpectedly "in
// the field".
clippy::arithmetic_side_effects,
clippy::indexing_slicing,
))]
#![cfg_attr(not(test), no_std)]
#![cfg_attr(feature = "simd-nightly", feature(stdsimd))]
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![cfg_attr(
__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS,
feature(layout_for_ptr, strict_provenance)
)]
#[macro_use]
mod macros;
#[cfg(feature = "byteorder")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "byteorder")))]
pub mod byteorder;
#[doc(hidden)]
pub mod macro_util;
mod util;
// TODO(#252): If we make this pub, come up with a better name.
mod wrappers;
#[cfg(feature = "byteorder")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "byteorder")))]
pub use crate::byteorder::*;
pub use crate::wrappers::*;
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::{AsBytes, FromBytes, Unaligned};
// `pub use` separately here so that we can mark it `#[doc(hidden)]`.
//
// TODO(#29): Remove this or add a doc comment.
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
#[doc(hidden)]
pub use zerocopy_derive::KnownLayout;
use core::{
cell::{self, RefMut},
cmp::Ordering,
fmt::{self, Debug, Display, Formatter},
hash::Hasher,
marker::PhantomData,
mem::{self, ManuallyDrop, MaybeUninit},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128,
NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize, Wrapping,
},
ops::{Deref, DerefMut},
ptr::{self, NonNull},
slice,
};
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "alloc")]
use {
alloc::{boxed::Box, vec::Vec},
core::alloc::Layout,
};
// For each polyfill, as soon as the corresponding feature is stable, the
// polyfill import will be unused because method/function resolution will prefer
// the inherent method/function over a trait method/function. Thus, we suppress
// the `unused_imports` warning.
//
// See the documentation on `util::polyfills` for more information.
#[allow(unused_imports)]
use crate::util::polyfills::NonNullExt as _;
// This is a hack to allow zerocopy-derive derives to work in this crate. They
// assume that zerocopy is linked as an extern crate, so they access items from
// it as `zerocopy::Xxx`. This makes that still work.
#[cfg(any(feature = "derive", test))]
mod zerocopy {
pub(crate) use crate::*;
}
#[rustversion::nightly]
#[cfg(all(test, not(__INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS)))]
const _: () = {
#[deprecated = "some tests may be skipped due to missing RUSTFLAGS=\"--cfg __INTERNAL_USE_ONLY_NIGHLTY_FEATURES_IN_TESTS\""]
const _WARNING: () = ();
#[warn(deprecated)]
_WARNING
};
/// The layout of a type which might be dynamically-sized.
///
/// `DstLayout` describes the layout of sized types, slice types, and "slice
/// DSTs" - ie, those that are known by the type system to have a trailing slice
/// (as distinguished from `dyn Trait` types - such types *might* have a
/// trailing slice type, but the type system isn't aware of it).
///
/// # Safety
///
/// Unlike [`core::alloc::Layout`], `DstLayout` is only used to describe full
/// Rust types - ie, those that satisfy the layout requirements outlined by
/// [the reference]. Callers may assume that an instance of `DstLayout`
/// satisfies any conditions imposed on Rust types by the reference.
///
/// If `layout: DstLayout` describes a type, `T`, then it is guaranteed that:
/// - `layout.align` is equal to `T`'s alignment
/// - If `layout.size_info` is `SizeInfo::Sized { size }`, then `T: Sized` and
/// `size_of::<T>() == size`
/// - If `layout.size_info` is `SizeInfo::SliceDst(slice_layout)`, then
/// - `T` is a slice DST
/// - The `size` of an instance of `T` with `elems` trailing slice elements is
/// equal to `slice_layout.offset + slice_layout.elem_size * elems` rounded up
/// to the nearest multiple of `layout.align`. Any bytes in the range
/// `[slice_layout.offset + slice_layout.elem_size * elems, size)` are padding
/// and must not be assumed to be initialized.
///
/// [the reference]: https://doc.rust-lang.org/reference/type-layout.html
#[doc(hidden)]
#[allow(missing_debug_implementations, missing_copy_implementations)]
#[cfg_attr(test, derive(Copy, Clone, Debug, PartialEq, Eq))]
pub struct DstLayout {
_align: NonZeroUsize,
_size_info: SizeInfo,
}
#[cfg_attr(test, derive(Copy, Clone, Debug, PartialEq, Eq))]
enum SizeInfo<E = usize> {
Sized { _size: usize },
SliceDst(TrailingSliceLayout<E>),
}
#[cfg_attr(test, derive(Copy, Clone, Debug, PartialEq, Eq))]
struct TrailingSliceLayout<E = usize> {
// The offset of the first byte of the trailing slice field. Note that this
// is NOT the same as the minimum size of the type. For example, consider
// the following type:
//
// struct Foo {
// a: u16,
// b: u8,
// c: [u8],
// }
//
// In `Foo`, `c` is at byte offset 3. When `c.len() == 0`, `c` is followed
// by a padding byte.
_offset: usize,
// The size of the element type of the trailing slice field.
_elem_size: E,
}
impl SizeInfo {
/// Attempts to create a `SizeInfo` from `Self` in which `elem_size` is a
/// `NonZeroUsize`. If `elem_size` is 0, returns `None`.
const fn _try_to_nonzero_elem_size(&self) -> Option<SizeInfo<NonZeroUsize>> {
Some(match *self {
SizeInfo::Sized { _size } => SizeInfo::Sized { _size },
SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size }) => {
if let Some(_elem_size) = NonZeroUsize::new(_elem_size) {
SizeInfo::SliceDst(TrailingSliceLayout { _offset, _elem_size })
} else {
return None;
}
}
})
}
}
#[doc(hidden)]
#[derive(Copy, Clone)]
#[cfg_attr(test, derive(Debug))]
#[allow(missing_debug_implementations)]
pub enum _CastType {
_Prefix,
_Suffix,
}
impl DstLayout {
/// Constructs a `DstLayout` which describes `T`.
///
/// # Safety
///
/// Unsafe code may assume that `DstLayout` is the correct layout for `T`.
#[doc(hidden)]
#[inline]
pub const fn for_type<T>() -> DstLayout {
// SAFETY: `align` is correct by construction. `T: Sized`, and so it is
// sound to initialize `size_info` to `SizeInfo::Sized { size }`; the
// `size` field is also correct by construction.
DstLayout {
_align: match NonZeroUsize::new(mem::align_of::<T>()) {
Some(align) => align,
None => unreachable!(),
},
_size_info: SizeInfo::Sized { _size: mem::size_of::<T>() },
}
}
/// Constructs a `DstLayout` which describes `[T]`.
///
/// # Safety
///
/// Unsafe code may assume that `DstLayout` is the correct layout for `[T]`.
const fn for_slice<T>() -> DstLayout {
// SAFETY: The alignment of a slice is equal to the alignment of its
// element type, and so `align` is initialized correctly.
//
// Since this is just a slice type, there is no offset between the
// beginning of the type and the beginning of the slice, so it is
// correct to set `offset: 0`. The `elem_size` is correct by
// construction. Since `[T]` is a (degenerate case of a) slice DST, it
// is correct to initialize `size_info` to `SizeInfo::SliceDst`.
DstLayout {
_align: match NonZeroUsize::new(mem::align_of::<T>()) {
Some(align) => align,
None => unreachable!(),
},
_size_info: SizeInfo::SliceDst(TrailingSliceLayout {
_offset: 0,
_elem_size: mem::size_of::<T>(),
}),
}
}
/// Validates that a cast is sound from a layout perspective.
///
/// Validates that the size and alignment requirements of a type with the
/// layout described in `self` would not be violated by performing a
/// `cast_type` cast from a pointer with address `addr` which refers to a
/// memory region of size `bytes_len`.
///
/// If the cast is valid, `validate_cast_and_convert_metadata` returns
/// `(elems, split_at)`. If `self` describes a dynamically-sized type, then
/// `elems` is the maximum number of trailing slice elements for which a
/// cast would be valid (for sized types, `elem` is meaningless and should
/// be ignored). `split_at` is the index at which to split the memory region
/// in order for the prefix (suffix) to contain the result of the cast, and
/// in order for the remaining suffix (prefix) to contain the leftover
/// bytes.
///
/// There are three conditions under which a cast can fail:
/// - The smallest possible value for the type is larger than the provided
/// memory region
/// - A prefix cast is requested, and `addr` does not satisfy `self`'s
/// alignment requirement
/// - A suffix cast is requested, and `addr + bytes_len` does not satisfy
/// `self`'s alignment requirement (as a consequence, since all instances
/// of the type are a multiple of its alignment, no size for the type will
/// result in a starting address which is properly aligned)
///
/// # Safety
///
/// The caller may assume that this implementation is correct, and may rely
/// on that assumption for the soundness of their code. In particular, the
/// caller may assume that, if `validate_cast_and_convert_metadata` returns
/// `Some((elems, split_at))`, then:
/// - A pointer to the type (for dynamically sized types, this includes
/// `elems` as its pointer metadata) describes an object of size `size <=
/// bytes_len`
/// - If this is a prefix cast:
/// - `addr` satisfies `self`'s alignment
/// - `size == split_at`
/// - If this is a suffix cast:
/// - `split_at == bytes_len - size`
/// - `addr + split_at` satisfies `self`'s alignment
///
/// Note that this method does *not* ensure that a pointer constructed from
/// its return values will be a valid pointer. In particular, this method
/// does not reason about `isize` overflow, which is a requirement of many
/// Rust pointer APIs, and may at some point be determined to be a validity
/// invariant of pointer types themselves. This should never be a problem so
/// long as the arguments to this method are derived from a known-valid
/// pointer (e.g., one derived from a safe Rust reference), but it is
/// nonetheless the caller's responsibility to justify that pointer
/// arithmetic will not overflow based on a safety argument *other than* the
/// mere fact that this method returned successfully.
///
/// # Panics
///
/// `validate_cast_and_convert_metadata` will panic if `self` describes a
/// DST whose trailing slice element is zero-sized.
///
/// If `addr + bytes_len` overflows `usize`,
/// `validate_cast_and_convert_metadata` may panic, or it may return
/// incorrect results. No guarantees are made about when
/// `validate_cast_and_convert_metadata` will panic. The caller should not
/// rely on `validate_cast_and_convert_metadata` panicking in any particular
/// condition, even if `debug_assertions` are enabled.
const fn _validate_cast_and_convert_metadata(
&self,
addr: usize,
bytes_len: usize,
cast_type: _CastType,
) -> Option<(usize, usize)> {
// `debug_assert!`, but with `#[allow(clippy::arithmetic_side_effects)]`.
macro_rules! __debug_assert {
($e:expr $(, $msg:expr)?) => {
debug_assert!({
#[allow(clippy::arithmetic_side_effects)]
let e = $e;
e
} $(, $msg)?);
};
}
// Note that, in practice, `self` is always a compile-time constant. We
// do this check earlier than needed to ensure that we always panic as a
// result of bugs in the program (such as calling this function on an
// invalid type) instead of allowing this panic to be hidden if the cast
// would have failed anyway for runtime reasons (such as a too-small
// memory region).
//
// TODO(#67): Once our MSRV is 1.65, use let-else:
// https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements
let size_info = match self._size_info._try_to_nonzero_elem_size() {
Some(size_info) => size_info,
None => panic!("attempted to cast to slice type with zero-sized element"),
};
// Precondition
__debug_assert!(addr.checked_add(bytes_len).is_some(), "`addr` + `bytes_len` > usize::MAX");
// Alignment checks go in their own block to avoid introducing variables
// into the top-level scope.
{
// We check alignment for `addr` (for prefix casts) or `addr +
// bytes_len` (for suffix casts). For a prefix cast, the correctness
// of this check is trivial - `addr` is the address the object will
// live at.
//
// For a suffix cast, we know that all valid sizes for the type are
// a multiple of the alignment (and by safety precondition, we know
// `DstLayout` may only describe valid Rust types). Thus, a
// validly-sized instance which lives at a validly-aligned address
// must also end at a validly-aligned address. Thus, if the end
// address for a suffix cast (`addr + bytes_len`) is not aligned,
// then no valid start address will be aligned either.
let offset = match cast_type {
_CastType::_Prefix => 0,
_CastType::_Suffix => bytes_len,
};
// Addition is guaranteed not to overflow because `offset <=
// bytes_len`, and `addr + bytes_len <= usize::MAX` is a
// precondition of this method. Modulus is guaranteed not to divide
// by 0 because `align` is non-zero.
#[allow(clippy::arithmetic_side_effects)]
if (addr + offset) % self._align.get() != 0 {
return None;
}
}
let (elems, self_bytes) = match size_info {
SizeInfo::Sized { _size: size } => {
if size > bytes_len {
return None;
}
(0, size)
}
SizeInfo::SliceDst(TrailingSliceLayout { _offset: offset, _elem_size: elem_size }) => {
// Calculate the maximum number of bytes that could be consumed
// - any number of bytes larger than this will either not be a
// multiple of the alignment, or will be larger than
// `bytes_len`.
let max_total_bytes =
util::_round_down_to_next_multiple_of_alignment(bytes_len, self._align);
// Calculate the maximum number of bytes that could be consumed
// by the trailing slice.
//
// TODO(#67): Once our MSRV is 1.65, use let-else:
// https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements
let max_slice_and_padding_bytes = match max_total_bytes.checked_sub(offset) {
Some(max) => max,
// `bytes_len` too small even for 0 trailing slice elements.
None => return None,
};
// Calculate the number of elements that fit in
// `max_slice_and_padding_bytes`; any remaining bytes will be
// considered padding.
//
// Guaranteed not to divide by zero: `elem_size` is non-zero.
#[allow(clippy::arithmetic_side_effects)]
let elems = max_slice_and_padding_bytes / elem_size.get();
// Guaranteed not to overflow on multiplication: `usize::MAX >=
// max_slice_and_padding_bytes >= (max_slice_and_padding_bytes /
// elem_size) * elem_size`.
//
// Guaranteed not to overflow on addition:
// - max_slice_and_padding_bytes == max_total_bytes - offset
// - elems * elem_size <= max_slice_and_padding_bytes == max_total_bytes - offset
// - elems * elem_size + offset <= max_total_bytes <= usize::MAX
#[allow(clippy::arithmetic_side_effects)]
let without_padding = offset + elems * elem_size.get();
// `self_bytes` is equal to the offset bytes plus the bytes
// consumed by the trailing slice plus any padding bytes
// required to satisfy the alignment. Note that we have computed
// the maximum number of trailing slice elements that could fit
// in `self_bytes`, so any padding is guaranteed to be less than
// the size of an extra element.
//
// Guaranteed not to overflow:
// - By previous comment: without_padding == elems * elem_size +
// offset <= max_total_bytes
// - By construction, `max_total_bytes` is a multiple of
// `self._align`.
// - At most, adding padding needed to round `without_padding`
// up to the next multiple of the alignment will bring
// `self_bytes` up to `max_total_bytes`.
#[allow(clippy::arithmetic_side_effects)]
let self_bytes = without_padding
+ util::core_layout::_padding_needed_for(without_padding, self._align);
(elems, self_bytes)
}
};
__debug_assert!(self_bytes <= bytes_len);
let split_at = match cast_type {
_CastType::_Prefix => self_bytes,
// Guaranteed not to underflow:
// - In the `Sized` branch, only returns `size` if `size <=
// bytes_len`.
// - In the `SliceDst` branch, calculates `self_bytes <=
// max_toatl_bytes`, which is upper-bounded by `bytes_len`.
#[allow(clippy::arithmetic_side_effects)]
_CastType::_Suffix => bytes_len - self_bytes,
};
Some((elems, split_at))
}
}
/// A trait which carries information about a type's layout that is used by the
/// internals of this crate.
///
/// This trait is not meant for consumption by code outside of this crate. While
/// the normal semver stability guarantees apply with respect to which types
/// implement this trait and which trait implementations are implied by this
/// trait, no semver stability guarantees are made regarding its internals; they
/// may change at any time, and code which makes use of them may break.
///
/// # Safety
///
/// This trait does not convey any safety guarantees to code outside this crate.
#[doc(hidden)] // TODO: Remove this once KnownLayout is used by other APIs
pub unsafe trait KnownLayout {
// The `Self: Sized` bound makes it so that `KnownLayout` can still be
// object safe. It's not currently object safe thanks to `const LAYOUT`, and
// it likely won't be in the future, but there's no reason not to be
// forwards-compatible with object safety.
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
#[doc(hidden)]
const LAYOUT: DstLayout;
/// SAFETY: The returned pointer has the same address and provenance as
/// `bytes`. If `Self` is a DST, the returned pointer's referent has `elems`
/// elements in its trailing slice. If `Self` is sized, `elems` is ignored.
#[doc(hidden)]
fn raw_from_ptr_len(bytes: NonNull<u8>, elems: usize) -> NonNull<Self>;
}
// SAFETY: Delegates safety to `DstLayout::for_slice`.
unsafe impl<T: KnownLayout> KnownLayout for [T] {
#[allow(clippy::missing_inline_in_public_items)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized,
{
}
const LAYOUT: DstLayout = DstLayout::for_slice::<T>();
// SAFETY: `.cast` preserves address and provenance. The returned pointer
// refers to an object with `elems` elements by construction.
#[inline(always)]
fn raw_from_ptr_len(data: NonNull<u8>, elems: usize) -> NonNull<Self> {
// TODO(#67): Remove this allow. See NonNullExt for more details.
#[allow(unstable_name_collisions)]
NonNull::slice_from_raw_parts(data.cast::<T>(), elems)
}
}
#[rustfmt::skip]
impl_known_layout!(
(),
u8, i8, u16, i16, u32, i32, u64, i64, u128, i128, usize, isize, f32, f64,
bool, char,
NonZeroU8, NonZeroI8, NonZeroU16, NonZeroI16, NonZeroU32, NonZeroI32,
NonZeroU64, NonZeroI64, NonZeroU128, NonZeroI128, NonZeroUsize, NonZeroIsize
);
#[rustfmt::skip]
impl_known_layout!(
T => Option<T>,
T: ?Sized => PhantomData<T>,
T => Wrapping<T>,
T => MaybeUninit<T>,
T: ?Sized => *const T,
T: ?Sized => *mut T,
);
impl_known_layout!(const N: usize, T => [T; N]);
safety_comment! {
/// SAFETY:
/// `str` and `ManuallyDrop<[T]>` [1] have the same representations as
/// `[u8]` and `[T]` repsectively. `str` has different bit validity than
/// `[u8]`, but that doesn't affect the soundness of this impl.
///
/// [1] Per https://doc.rust-lang.org/nightly/core/mem/struct.ManuallyDrop.html:
///
/// `ManuallyDrop<T>` is guaranteed to have the same layout and bit
/// validity as `T`
///
/// TODO(#429): Once this text (added in
/// https://github.com/rust-lang/rust/pull/115522) is available on stable,
/// quote the stable docs instead of the nightly docs.
unsafe_impl_known_layout!(#[repr([u8])] str);
unsafe_impl_known_layout!(T: ?Sized + KnownLayout => #[repr(T)] ManuallyDrop<T>);
}
/// Analyzes whether a type is [`FromZeroes`].
///
/// This derive analyzes, at compile time, whether the annotated type satisfies
/// the [safety conditions] of `FromZeroes` and implements `FromZeroes` if it is
/// sound to do so. This derive can be applied to structs, enums, and unions;
/// e.g.:
///
/// ```
/// # use zerocopy_derive::FromZeroes;
/// #[derive(FromZeroes)]
/// struct MyStruct {
/// # /*
/// ...
/// # */
/// }
///
/// #[derive(FromZeroes)]
/// #[repr(u8)]
/// enum MyEnum {
/// # Variant0,
/// # /*
/// ...
/// # */
/// }
///
/// #[derive(FromZeroes)]
/// union MyUnion {
/// # variant: u8,
/// # /*
/// ...
/// # */
/// }
/// ```
///
/// [safety conditions]: trait@FromZeroes#safety
///
/// # Analysis
///
/// *This section describes, roughly, the analysis performed by this derive to
/// determine whether it is sound to implement `FromZeroes` for a given type.
/// Unless you are modifying the implementation of this derive, or attempting to
/// manually implement `FromZeroes` for a type yourself, you don't need to read
/// this section.*
///
/// If a type has the following properties, then this derive can implement
/// `FromZeroes` for that type:
///
/// - If the type is a struct, all of its fields must be `FromZeroes`.
/// - If the type is an enum, it must be C-like (meaning that all variants have
/// no fields) and it must have a variant with a discriminant of `0`. See [the
/// reference] for a description of how discriminant values are chosen.
/// - The type must not contain any [`UnsafeCell`]s (this is required in order
/// for it to be sound to construct a `&[u8]` and a `&T` to the same region of
/// memory). The type may contain references or pointers to `UnsafeCell`s so
/// long as those values can themselves be initialized from zeroes
/// (`FromZeroes` is not currently implemented for, e.g.,
/// `Option<&UnsafeCell<_>>`, but it could be one day).
///
/// This analysis is subject to change. Unsafe code may *only* rely on the
/// documented [safety conditions] of `FromZeroes`, and must *not* rely on the
/// implementation details of this derive.
///
/// [the reference]: https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-fieldless-enumerations
/// [`UnsafeCell`]: core::cell::UnsafeCell
///
/// ## Why isn't an explicit representation required for structs?
///
/// Neither this derive, nor the [safety conditions] of `FromZeroes`, requires
/// that structs are marked with `#[repr(C)]`.
///
/// Per the [Rust reference](reference),
///
/// > The representation of a type can change the padding between fields, but
/// does not change the layout of the fields themselves.
///
/// [reference]: https://doc.rust-lang.org/reference/type-layout.html#representations
///
/// Since the layout of structs only consists of padding bytes and field bytes,
/// a struct is soundly `FromZeroes` if:
/// 1. its padding is soundly `FromZeroes`, and
/// 2. its fields are soundly `FromZeroes`.
///
/// The answer to the first question is always yes: padding bytes do not have
/// any validity constraints. A [discussion] of this question in the Unsafe Code
/// Guidelines Working Group concluded that it would be virtually unimaginable
/// for future versions of rustc to add validity constraints to padding bytes.
///
/// [discussion]: https://github.com/rust-lang/unsafe-code-guidelines/issues/174
///
/// Whether a struct is soundly `FromZeroes` therefore solely depends on whether
/// its fields are `FromZeroes`.
// TODO(#146): Document why we don't require an enum to have an explicit `repr`
// attribute.
#[cfg(any(feature = "derive", test))]
#[cfg_attr(doc_cfg, doc(cfg(feature = "derive")))]
pub use zerocopy_derive::FromZeroes;
/// Types for which a sequence of bytes all set to zero represents a valid
/// instance of the type.
///
/// Any memory region of the appropriate length which is guaranteed to contain
/// only zero bytes can be viewed as any `FromZeroes` type with no runtime
/// overhead. This is useful whenever memory is known to be in a zeroed state,
/// such memory returned from some allocation routines.
///
/// # Implementation
///
/// **Do not implement this trait yourself!** Instead, use
/// [`#[derive(FromZeroes)]`][derive] (requires the `derive` Cargo feature);
/// e.g.:
///
/// ```
/// # use zerocopy_derive::FromZeroes;
/// #[derive(FromZeroes)]
/// struct MyStruct {
/// # /*
/// ...
/// # */
/// }
///
/// #[derive(FromZeroes)]
/// #[repr(u8)]
/// enum MyEnum {
/// # Variant0,
/// # /*
/// ...
/// # */
/// }
///
/// #[derive(FromZeroes)]
/// union MyUnion {
/// # variant: u8,
/// # /*
/// ...
/// # */
/// }
/// ```
///
/// This derive performs a sophisticated, compile-time safety analysis to
/// determine whether a type is `FromZeroes`.
///
/// # Safety
///
/// *This section describes what is required in order for `T: FromZeroes`, and
/// what unsafe code may assume of such types. If you don't plan on implementing
/// `FromZeroes` manually, and you don't plan on writing unsafe code that
/// operates on `FromZeroes` types, then you don't need to read this section.*
///
/// If `T: FromZeroes`, then unsafe code may assume that:
/// - It is sound to treat any initialized sequence of zero bytes of length
/// `size_of::<T>()` as a `T`.
/// - Given `b: &[u8]` where `b.len() == size_of::<T>()`, `b` is aligned to
/// `align_of::<T>()`, and `b` contains only zero bytes, it is sound to
/// construct a `t: &T` at the same address as `b`, and it is sound for both
/// `b` and `t` to be live at the same time.
///
/// If a type is marked as `FromZeroes` which violates this contract, it may
/// cause undefined behavior.
///
/// `#[derive(FromZeroes)]` only permits [types which satisfy these requirements][derive-analysis].
///
#[cfg_attr(
feature = "derive",
doc = "[derive]: zerocopy_derive::FromZeroes",
doc = "[derive-analysis]: zerocopy_derive::FromZeroes#analysis"
)]
#[cfg_attr(
not(feature = "derive"),
doc = concat!("[derive]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeroes.html"),
doc = concat!("[derive-analysis]: https://docs.rs/zerocopy/", env!("CARGO_PKG_VERSION"), "/zerocopy/derive.FromZeroes.html#analysis"),
)]
pub unsafe trait FromZeroes {
// The `Self: Sized` bound makes it so that `FromZeroes` is still object
// safe.
#[doc(hidden)]
fn only_derive_is_allowed_to_implement_this_trait()
where
Self: Sized;
/// Overwrites `self` with zeroes.
///
/// Sets every byte in `self` to 0. While this is similar to doing `*self =
/// Self::new_zeroed()`, it differs in that `zero` does not semantically
/// drop the current value and replace it with a new one - it simply
/// modifies the bytes of the existing value.
///
/// # Examples
///
/// ```
/// # use zerocopy::FromZeroes;
/// # use zerocopy_derive::*;
/// #
/// #[derive(FromZeroes)]
/// #[repr(C)]
/// struct PacketHeader {
/// src_port: [u8; 2],
/// dst_port: [u8; 2],
/// length: [u8; 2],
/// checksum: [u8; 2],
/// }
///
/// let mut header = PacketHeader {
/// src_port: 100u16.to_be_bytes(),
/// dst_port: 200u16.to_be_bytes(),
/// length: 300u16.to_be_bytes(),
/// checksum: 400u16.to_be_bytes(),
/// };
///
/// header.zero();
///
/// assert_eq!(header.src_port, [0, 0]);
/// assert_eq!(header.dst_port, [0, 0]);
/// assert_eq!(header.length, [0, 0]);
/// assert_eq!(header.checksum, [0, 0]);
/// ```
#[inline(always)]
fn zero(&mut self) {
let slf: *mut Self = self;
let len = mem::size_of_val(self);
// SAFETY:
// - `self` is guaranteed by the type system to be valid for writes of
// size `size_of_val(self)`.
// - `u8`'s alignment is 1, and thus `self` is guaranteed to be aligned
// as required by `u8`.
// - Since `Self: FromZeroes`, the all-zeroes instance is a valid
// instance of `Self.`
unsafe { ptr::write_bytes(slf.cast::<u8>(), 0, len) };
}
/// Creates an instance of `Self` from zeroed bytes.
///
/// # Examples
///
/// ```
/// # use zerocopy::FromZeroes;
/// # use zerocopy_derive::*;
/// #
/// #[derive(FromZeroes)]
/// #[repr(C)]
/// struct PacketHeader {
/// src_port: [u8; 2],
/// dst_port: [u8; 2],
/// length: [u8; 2],
/// checksum: [u8; 2],
/// }
///
/// let header: PacketHeader = FromZeroes::new_zeroed();
///
/// assert_eq!(header.src_port, [0, 0]);
/// assert_eq!(header.dst_port, [0, 0]);
/// assert_eq!(header.length, [0, 0]);
/// assert_eq!(header.checksum, [0, 0]);
/// ```
#[inline(always)]
fn new_zeroed() -> Self
where
Self: Sized,
{
// SAFETY: `FromZeroes` says that the all-zeroes bit pattern is legal.