Skip to main content

google_protobuf/upb_kernel/
message.rs

1use super::*;
2
3#[derive(Debug)]
4#[doc(hidden)]
5pub struct OwnedMessageInner<T> {
6    ptr: MessagePtr<T>,
7    arena: Arena,
8}
9
10impl<T: Message> Default for OwnedMessageInner<T> {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl<T: Message> OwnedMessageInner<T> {
17    pub fn new() -> Self {
18        let arena = Arena::new();
19        let ptr = MessagePtr::new(&arena).expect("alloc should never fail");
20        Self { ptr, arena }
21    }
22
23    /// # Safety
24    /// - The underlying pointer must of type `T` and be allocated on `arena`.
25    pub unsafe fn wrap_raw(raw: RawMessage, arena: Arena) -> Self {
26        // SAFETY:
27        // - Caller guaranteed `raw` is valid and of type `T`
28        let ptr = unsafe { MessagePtr::wrap(raw) };
29        OwnedMessageInner { ptr, arena }
30    }
31
32    pub fn ptr_mut(&mut self) -> MessagePtr<T> {
33        self.ptr
34    }
35
36    pub fn ptr(&self) -> MessagePtr<T> {
37        self.ptr
38    }
39
40    pub fn raw(&self) -> RawMessage {
41        self.ptr.raw()
42    }
43
44    #[allow(clippy::needless_pass_by_ref_mut)] // Sound access requires mutable access.
45    pub fn arena(&mut self) -> &Arena {
46        &self.arena
47    }
48}
49
50/// Mutators that point to their original message use this to do so.
51///
52/// Since UPB expects runtimes to manage their own arenas, this needs to have
53/// access to an `Arena`.
54///
55/// This has two possible designs:
56/// - Store two pointers here, `RawMessage` and `&'msg Arena`. This doesn't
57///   place any restriction on the layout of generated messages and their
58///   mutators. This makes a vtable-based mutator three pointers, which can no
59///   longer be returned in registers on most platforms.
60/// - Store one pointer here, `&'msg OwnedMessageInner`, where `OwnedMessageInner` stores
61///   a `RawMessage` and an `Arena`. This would require all generated messages
62///   to store `OwnedMessageInner`, and since their mutators need to be able to
63///   generate `BytesMut`, would also require `BytesMut` to store a `&'msg
64///   OwnedMessageInner` since they can't store an owned `Arena`.
65///
66/// The following invariants must be upheld:
67///
68/// - No concurrent mutation for any two fields in a message: this means
69///   mutators cannot be `Send` but are `Sync`.
70/// - If there are multiple accessible `Mut` to a single message at a time, they
71///   must be different fields, and not be in the same oneof. As such, a `Mut`
72///   cannot be `Clone` but *can* reborrow itself with `.as_mut()`, which
73///   converts `&'b mut Mut<'a, T>` to `Mut<'b, T>`.
74#[derive(Debug)]
75#[doc(hidden)]
76pub struct MessageMutInner<'msg, T> {
77    pub(crate) ptr: MessagePtr<T>,
78    pub(crate) arena: &'msg Arena,
79}
80
81impl<'msg, T: Message> MessageMutInner<'msg, T> {
82    /// # Safety
83    /// - `msg` must be a valid `RawMessage`
84    /// - `arena` must hold the memory for `msg`
85    pub unsafe fn wrap_raw(raw: RawMessage, arena: &'msg Arena) -> Self {
86        // SAFETY:
87        // - Caller guaranteed `raw` is valid and of type `T`
88        let ptr = unsafe { MessagePtr::wrap(raw) };
89        MessageMutInner { ptr, arena }
90    }
91
92    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
93    pub fn mut_of_owned(msg: &'msg mut OwnedMessageInner<T>) -> Self {
94        MessageMutInner { ptr: msg.ptr, arena: &msg.arena }
95    }
96
97    pub fn from_parent<ParentT>(
98        parent_msg: MessageMutInner<'msg, ParentT>,
99        ptr: MessagePtr<T>,
100    ) -> Self {
101        MessageMutInner { ptr, arena: parent_msg.arena }
102    }
103
104    pub fn ptr_mut(&mut self) -> MessagePtr<T> {
105        self.ptr
106    }
107
108    pub fn ptr(&self) -> MessagePtr<T> {
109        self.ptr
110    }
111
112    pub fn raw(&self) -> RawMessage {
113        self.ptr.raw()
114    }
115
116    pub fn arena(&self) -> &Arena {
117        self.arena
118    }
119
120    pub fn as_view(&self) -> MessageViewInner<'msg, T> {
121        MessageViewInner { ptr: self.ptr, _phantom: PhantomData }
122    }
123
124    pub fn reborrow<'shorter>(&mut self) -> MessageMutInner<'shorter, T>
125    where
126        'msg: 'shorter,
127    {
128        Self { ptr: self.ptr, arena: self.arena }
129    }
130}
131
132#[derive(Debug)]
133#[doc(hidden)]
134pub struct MessageViewInner<'msg, T> {
135    ptr: MessagePtr<T>,
136    _phantom: PhantomData<&'msg ()>,
137}
138
139impl<'msg, T: Message> Clone for MessageViewInner<'msg, T> {
140    fn clone(&self) -> Self {
141        *self
142    }
143}
144impl<'msg, T: Message> Copy for MessageViewInner<'msg, T> {}
145
146impl<'msg, T: Message> MessageViewInner<'msg, T> {
147    /// # Safety
148    /// - The underlying pointer must live as long as `'msg`.
149    pub unsafe fn wrap(ptr: MessagePtr<T>) -> Self {
150        // SAFETY:
151        // - Caller guaranteed `raw` is valid
152        MessageViewInner { ptr, _phantom: PhantomData }
153    }
154
155    /// # Safety
156    /// - The underlying pointer must of type `T` and live as long as `'msg`.
157    pub unsafe fn wrap_raw(raw: RawMessage) -> Self {
158        // SAFETY:
159        // - Caller guaranteed `raw` is valid and of type `T`
160        let ptr = unsafe { MessagePtr::wrap(raw) };
161        MessageViewInner { ptr, _phantom: PhantomData }
162    }
163
164    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
165    pub fn view_of_owned(owned: &'msg OwnedMessageInner<T>) -> Self {
166        MessageViewInner { ptr: owned.ptr, _phantom: PhantomData }
167    }
168
169    #[allow(clippy::needless_pass_by_ref_mut)] // Sound construction requires mutable access.
170    pub fn view_of_mut(msg_mut: MessageMutInner<'msg, T>) -> Self {
171        MessageViewInner { ptr: msg_mut.ptr, _phantom: PhantomData }
172    }
173
174    pub fn ptr(&self) -> MessagePtr<T> {
175        self.ptr
176    }
177
178    pub fn raw(&self) -> RawMessage {
179        self.ptr.raw()
180    }
181}
182
183/// The scratch size of 64 KiB matches the maximum supported size that a
184/// upb_Message can possibly be.
185const UPB_SCRATCH_SPACE_BYTES: usize = 65_536;
186
187/// Holds a zero-initialized block of memory for use by upb.
188///
189/// By default, if a message is not set in cpp, a default message is created.
190/// upb departs from this and returns a null ptr. However, since contiguous
191/// chunks of memory filled with zeroes are legit messages from upb's point of
192/// view, we can allocate a large block and refer to that when dealing
193/// with readonly access.
194#[repr(C, align(8))] // align to UPB_MALLOC_ALIGN = 8
195pub(crate) struct ScratchSpace([u8; UPB_SCRATCH_SPACE_BYTES]);
196impl ScratchSpace {
197    pub fn zeroed_block() -> RawMessage {
198        static ZEROED_BLOCK: ScratchSpace = ScratchSpace([0; UPB_SCRATCH_SPACE_BYTES]);
199        NonNull::from(&ZEROED_BLOCK).cast()
200    }
201}
202
203impl<T: Message> Default for MessageViewInner<'static, T> {
204    fn default() -> Self {
205        unsafe {
206            // SAFETY:
207            // - `ScratchSpace::zeroed_block()` is a valid const `RawMessage` for all possible T.
208            // - `ScratchSpace::zeroed_block()' has 'static lifetime.
209            Self::wrap_raw(ScratchSpace::zeroed_block())
210        }
211    }
212}
213
214/// Internal-only trait to support blanket impls that need const access to raw messages
215/// on codegen. Should never be used by application code.
216#[doc(hidden)]
217pub unsafe trait UpbGetMessagePtr: SealedInternal {
218    type Msg: AssociatedMiniTable + Message;
219
220    fn get_ptr(&self, _private: Private) -> MessagePtr<Self::Msg>;
221}
222
223/// Internal-only trait to support blanket impls that need mutable access to raw messages
224/// on codegen. Must not be implemented on View proxies. Should never be used by application code.
225#[doc(hidden)]
226pub unsafe trait UpbGetMessagePtrMut: SealedInternal {
227    type Msg: AssociatedMiniTable + Message;
228
229    fn get_ptr_mut(&mut self, _private: Private) -> MessagePtr<Self::Msg>;
230}
231
232/// Internal-only trait to support blanket impls that need const access to raw messages
233/// on codegen. Should never be used by application code.
234#[doc(hidden)]
235pub unsafe trait UpbGetArena: SealedInternal {
236    fn get_arena(&mut self, _private: Private) -> &Arena;
237}
238
239pub trait KernelMessage:
240    AssociatedMiniTable + UpbGetArena + UpbGetMessagePtr + UpbGetMessagePtrMut + OwnedMessageInterop
241{
242}
243
244impl<T> KernelMessage for T where
245    T: AssociatedMiniTable
246        + UpbGetArena
247        + UpbGetMessagePtr
248        + UpbGetMessagePtrMut
249        + OwnedMessageInterop
250{
251}
252
253pub trait KernelMessageView<'msg>:
254    UpbGetMessagePtr + MessageViewInterop<'msg> + From<MessageViewInner<'msg, Self::KMessage>>
255{
256    type KMessage;
257}
258
259impl<'msg, T> KernelMessageView<'msg> for T
260where
261    T: UpbGetMessagePtr + MessageViewInterop<'msg> + From<MessageViewInner<'msg, T::Msg>>,
262{
263    type KMessage = T::Msg;
264}
265
266pub trait KernelMessageMut<'msg>:
267    UpbGetMessagePtr
268    + UpbGetMessagePtrMut
269    + UpbGetArena
270    + MessageMutInterop<'msg>
271    + From<MessageMutInner<'msg, Self::KMessage>>
272{
273    type KMessage;
274}
275impl<'msg, T> KernelMessageMut<'msg> for T
276where
277    T: UpbGetMessagePtr
278        + UpbGetMessagePtrMut
279        + UpbGetArena
280        + MessageMutInterop<'msg>
281        + From<MessageMutInner<'msg, <T as UpbGetMessagePtr>::Msg>>,
282{
283    type KMessage = <T as UpbGetMessagePtr>::Msg;
284}
285
286/// Message equality definition which may have both false-negatives and false-positives in the face
287/// of unknown fields.
288///
289/// This behavior is deliberately held back from being exposed as an `Eq` trait for messages. The
290/// reason is that it is impossible to properly compare unknown fields for message equality, since
291/// without the schema you cannot know how to interpret the wire format properly for comparison.
292///
293/// False negative cases (where message_eq will return false on unknown fields where it
294/// would return true if the fields were known) are common and will occur in production: for
295/// example, as map and repeated fields look exactly the same, map field order is unstable, the
296/// comparison cannot know to treat it as unordered and will return false when it was the same
297/// map but in a different order.
298///
299/// False positives cases (where message_eq will return true on unknown fields where it would have
300/// return false if the fields were known) are possible but uncommon in practice. One example
301/// of this direction can occur if two fields are defined in the same oneof and both are present on
302/// the wire but in opposite order, without the schema these messages appear equal but with the
303/// schema they are not-equal.
304///
305/// This lossy behavior in the face of unknown fields is especially problematic in the face of
306/// extensions and other treeshaking behaviors where a given field being known or not to binary is a
307/// spooky-action-at-a-distance behavior, which may lead to surprising changes in outcome in
308/// equality tests based on changes made arbitrarily distant from the code performing the equality
309/// check.
310///
311/// Broadly this is recommended for use in tests (where unknown field behaviors are rarely a
312/// concern), and in limited/targeted cases where the lossy behavior in the face of unknown fields
313/// behavior is unlikely to be a problem.
314pub fn message_eq<T>(a: &T, b: &T) -> bool
315where
316    T: AsView + Debug,
317    <T as AsView>::Proxied: AssociatedMiniTable,
318    for<'a> View<'a, <T as AsView>::Proxied>: UpbGetMessagePtr,
319{
320    unsafe {
321        upb_Message_IsEqual(
322            a.as_view().get_ptr(Private).raw(),
323            b.as_view().get_ptr(Private).raw(),
324            <T as AsView>::Proxied::mini_table(),
325            0,
326        )
327    }
328}
329
330impl<T> MatcherEq for T
331where
332    Self: AsView + Debug,
333    <Self as AsView>::Proxied: AssociatedMiniTable,
334    for<'a> View<'a, <Self as AsView>::Proxied>: UpbGetMessagePtr,
335{
336    fn matches(&self, o: &Self) -> bool {
337        message_eq(self, o)
338    }
339}
340
341impl<T: UpbGetMessagePtrMut> Clear for T {
342    fn clear(&mut self) {
343        unsafe { self.get_ptr_mut(Private).clear() }
344    }
345}
346
347fn clear_and_parse_helper<T>(
348    msg: &mut T,
349    data: &[u8],
350    decode_options: i32,
351) -> Result<(), ParseError>
352where
353    T: UpbGetMessagePtrMut + UpbGetArena,
354{
355    Clear::clear(msg);
356    // SAFETY:
357    // - `msg` is a valid mutable message.
358    // - `mini_table` is the one associated with `msg`
359    // - `msg.arena().raw()` is held for the same lifetime as `msg`.
360    unsafe {
361        upb::wire::decode_with_options(
362            data,
363            msg.get_ptr_mut(Private),
364            generated_extension_registry().as_ptr(),
365            msg.get_arena(Private),
366            decode_options,
367        )
368    }
369    .map(|_| ())
370    .map_err(|_| ParseError)
371}
372
373impl<T> ClearAndParse for T
374where
375    Self: UpbGetMessagePtrMut + UpbGetArena,
376{
377    fn clear_and_parse(&mut self, data: &[u8]) -> Result<(), ParseError> {
378        clear_and_parse_helper(self, data, upb::wire::decode_options::CHECK_REQUIRED)
379    }
380
381    fn clear_and_parse_dont_enforce_required(&mut self, data: &[u8]) -> Result<(), ParseError> {
382        clear_and_parse_helper(self, data, 0)
383    }
384}
385
386impl<T> Serialize for T
387where
388    Self: UpbGetMessagePtr,
389{
390    fn serialize(&self) -> Result<Vec<u8>, SerializeError> {
391        //~ TODO: This discards the info we have about the reason
392        //~ of the failure, we should try to keep it instead.
393        upb::wire::encode(self.get_ptr(Private)).map_err(|_| SerializeError)
394    }
395
396    fn serialized_len(&self) -> usize {
397        upb::wire::byte_size(self.get_ptr(Private))
398    }
399}
400
401impl<T> TakeFrom for T
402where
403    Self: CopyFrom + AsMut,
404    for<'a> Mut<'a, <Self as AsMut>::MutProxied>: Clear,
405{
406    fn take_from(&mut self, mut src: impl AsMut<MutProxied = Self::Proxied>) {
407        let mut src = src.as_mut();
408        // TODO: b/393559271 - Optimize this copy out.
409        CopyFrom::copy_from(self, AsView::as_view(&src));
410        Clear::clear(&mut src);
411    }
412}
413
414impl<T> CopyFrom for T
415where
416    Self: AsView + UpbGetArena + UpbGetMessagePtr,
417    Self::Proxied: AssociatedMiniTable,
418    for<'a> View<'a, Self::Proxied>: UpbGetMessagePtr,
419{
420    fn copy_from(&mut self, src: impl AsView<Proxied = Self::Proxied>) {
421        // SAFETY: self and src are both valid `T`s associated with
422        // `Self::mini_table()`.
423        unsafe {
424            assert!(upb_Message_DeepCopy(
425                self.get_ptr(Private).raw(),
426                src.as_view().get_ptr(Private).raw(),
427                <Self::Proxied as AssociatedMiniTable>::mini_table(),
428                self.get_arena(Private).raw()
429            ));
430        }
431    }
432}
433
434impl<T> MergeFrom for T
435where
436    Self: AsView + UpbGetArena + UpbGetMessagePtr,
437    Self::Proxied: AssociatedMiniTable,
438    for<'a> View<'a, Self::Proxied>: UpbGetMessagePtr,
439{
440    fn merge_from(&mut self, src: impl AsView<Proxied = Self::Proxied>) {
441        // SAFETY: self and src are both valid `T`s.
442        unsafe {
443            assert!(upb_Message_MergeFrom(
444                self.get_ptr(Private).raw(),
445                src.as_view().get_ptr(Private).raw(),
446                <Self::Proxied as AssociatedMiniTable>::mini_table(),
447                generated_extension_registry().as_ptr(),
448                self.get_arena(Private).raw()
449            ));
450        }
451    }
452}
453
454/// # Safety
455/// - The field at `index` must be a message field of type `T`.
456pub unsafe fn message_set_sub_message<
457    'msg,
458    P: Message + AssociatedMiniTable,
459    T: Message + UpbGetMessagePtrMut + UpbGetArena,
460>(
461    parent: MessageMutInner<'msg, P>,
462    index: u32,
463    val: impl IntoProxied<T>,
464) {
465    // The message and arena are dropped after the setter. The
466    // memory remains allocated as we fuse the arena with the
467    // parent message's arena.
468    let mut child = val.into_proxied(Private);
469    parent.arena.fuse(child.get_arena(Private));
470
471    let child_ptr = child.get_ptr_mut(Private);
472    unsafe {
473        // SAFETY:
474        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
475        // - The caller guarantees that `index` refers to a valid message field of type `T`.
476        // - The child's arena has been fused into the parent's arena above.
477        parent.ptr.set_base_field_message_at_index(index, child_ptr);
478    }
479}
480
481/// # Safety
482/// - The field at `index` must be a string field.
483pub unsafe fn message_set_string_field<'msg, P: Message + AssociatedMiniTable>(
484    parent: MessageMutInner<'msg, P>,
485    index: u32,
486    val: impl IntoProxied<ProtoString>,
487) {
488    let s = val.into_proxied(Private);
489    let (view, arena) = s.into_inner(Private).into_raw_parts();
490    parent.arena().fuse(&arena);
491    unsafe {
492        // SAFETY:
493        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
494        // - The caller guarantees that `index` refers to a valid string field.
495        // - The string's arena has been fused into the parent's arena above.
496        parent.ptr.set_base_field_string_at_index(index, view);
497    }
498}
499
500/// # Safety
501/// - The field at `index` must be a bytes field.
502pub unsafe fn message_set_bytes_field<'msg, P: Message + AssociatedMiniTable>(
503    parent: MessageMutInner<'msg, P>,
504    index: u32,
505    val: impl IntoProxied<ProtoBytes>,
506) {
507    let s = val.into_proxied(Private);
508    let (view, arena) = s.into_inner(Private).into_raw_parts();
509    parent.arena().fuse(&arena);
510    unsafe {
511        // SAFETY:
512        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
513        // - The caller guarantees that `index` refers to a valid bytes field.
514        // - The string's arena has been fused into the parent's arena above.
515        parent.ptr.set_base_field_string_at_index(index, view);
516    }
517}
518
519/// # Safety
520/// - The field at `index` must be a repeated field of `T`.
521pub unsafe fn message_set_repeated_field<'msg, P: Message + AssociatedMiniTable, T: Singular>(
522    parent: MessageMutInner<'msg, P>,
523    index: u32,
524    val: impl IntoProxied<Repeated<T>>,
525) {
526    let child = val.into_proxied(Private);
527    let inner = child.inner(Private);
528    parent.arena().fuse(inner.arena());
529    unsafe {
530        // SAFETY:
531        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
532        // - The caller guarantees that `index` refers to a valid repeated field.
533        // - The repeated field's arena has been fused into the parent's arena above.
534        parent.ptr.set_array_at_index(index, inner.raw());
535    }
536}
537
538/// # Safety
539/// - The field at `index` must be a map field with key type `K` and value type `V`.
540pub unsafe fn message_set_map_field<
541    'msg,
542    P: Message + AssociatedMiniTable,
543    K: MapKey,
544    V: MapValue,
545>(
546    parent: MessageMutInner<'msg, P>,
547    index: u32,
548    val: impl IntoProxied<Map<K, V>>,
549) {
550    let mut child = val.into_proxied(Private);
551    let child_as_mut = child.as_mut();
552    let mut inner = child_as_mut.inner(Private);
553
554    parent.arena().fuse(inner.arena());
555    unsafe {
556        // SAFETY:
557        // - `parent.ptr` is valid as it comes from a `MessageMutInner`.
558        // - The caller guarantees that `index` refers to a valid map field.
559        // - The map's arena has been fused into the parent's arena above.
560        parent.ptr.set_map_at_index(index, inner.as_raw());
561    }
562}