servo_arc/lib.rs
1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! Fork of Arc for Servo. This has the following advantages over std::sync::Arc:
12//!
13//! * We don't waste storage on the weak reference count.
14//! * We don't do extra RMU operations to handle the possibility of weak references.
15//! * We can experiment with arena allocation (todo).
16//! * We can add methods to support our custom use cases [1].
17//! * We have support for dynamically-sized types (see from_header_and_iter).
18//! * We have support for thin arcs to unsized types (see ThinArc).
19//! * We have support for references to static data, which don't do any
20//! refcounting.
21//!
22//! [1]: https://bugzilla.mozilla.org/show_bug.cgi?id=1360883
23
24// The semantics of `Arc` are already documented in the Rust docs, so we don't
25// duplicate those here.
26#![allow(missing_docs)]
27
28#[cfg(feature = "servo")]
29use serde::{Deserialize, Serialize};
30use stable_deref_trait::{CloneStableDeref, StableDeref};
31use std::alloc::{self, Layout};
32use std::borrow;
33use std::cmp::Ordering;
34use std::fmt;
35use std::hash::{Hash, Hasher};
36use std::marker::PhantomData;
37use std::mem::{self, align_of, size_of};
38use std::ops::{Deref, DerefMut};
39use std::os::raw::c_void;
40use std::process;
41use std::ptr;
42use std::sync::atomic;
43use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};
44
45/// A soft limit on the amount of references that may be made to an `Arc`.
46///
47/// Going above this limit will abort your program (although not
48/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references.
49const MAX_REFCOUNT: usize = isize::MAX as usize;
50
51/// Special refcount value that means the data is not reference counted,
52/// and that the `Arc` is really acting as a read-only static reference.
53const STATIC_REFCOUNT: usize = usize::MAX;
54
55/// An atomically reference counted shared pointer
56///
57/// See the documentation for [`Arc`] in the standard library. Unlike the
58/// standard library `Arc`, this `Arc` does not support weak reference counting.
59///
60/// See the discussion in https://github.com/rust-lang/rust/pull/60594 for the
61/// usage of PhantomData.
62///
63/// [`Arc`]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
64///
65/// cbindgen:derive-eq=false
66/// cbindgen:derive-neq=false
67#[repr(C)]
68pub struct Arc<T: ?Sized> {
69 p: ptr::NonNull<ArcInner<T>>,
70 phantom: PhantomData<T>,
71}
72
73/// An `Arc` that is known to be uniquely owned
74///
75/// When `Arc`s are constructed, they are known to be
76/// uniquely owned. In such a case it is safe to mutate
77/// the contents of the `Arc`. Normally, one would just handle
78/// this by mutating the data on the stack before allocating the
79/// `Arc`, however it's possible the data is large or unsized
80/// and you need to heap-allocate it earlier in such a way
81/// that it can be freely converted into a regular `Arc` once you're
82/// done.
83///
84/// `UniqueArc` exists for this purpose, when constructed it performs
85/// the same allocations necessary for an `Arc`, however it allows mutable access.
86/// Once the mutation is finished, you can call `.shareable()` and get a regular `Arc`
87/// out of it.
88///
89/// Ignore the doctest below there's no way to skip building with refcount
90/// logging during doc tests (see rust-lang/rust#45599).
91///
92/// ```rust,ignore
93/// # use servo_arc::UniqueArc;
94/// let data = [1, 2, 3, 4, 5];
95/// let mut x = UniqueArc::new(data);
96/// x[4] = 7; // mutate!
97/// let y = x.shareable(); // y is an Arc<T>
98/// ```
99pub struct UniqueArc<T: ?Sized>(Arc<T>);
100
101impl<T> UniqueArc<T> {
102 #[inline]
103 /// Construct a new UniqueArc
104 pub fn new(data: T) -> Self {
105 UniqueArc(Arc::new(data))
106 }
107
108 /// Construct an uninitialized arc
109 #[inline]
110 pub fn new_uninit() -> UniqueArc<mem::MaybeUninit<T>> {
111 unsafe {
112 let layout = Layout::new::<ArcInner<mem::MaybeUninit<T>>>();
113 let ptr = alloc::alloc(layout);
114 let mut p = ptr::NonNull::new(ptr)
115 .unwrap_or_else(|| alloc::handle_alloc_error(layout))
116 .cast::<ArcInner<mem::MaybeUninit<T>>>();
117 ptr::write(&mut p.as_mut().count, atomic::AtomicUsize::new(1));
118 #[cfg(feature = "track_alloc_size")]
119 ptr::write(&mut p.as_mut().alloc_size, layout.size());
120
121 #[cfg(feature = "gecko_refcount_logging")]
122 {
123 NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8)
124 }
125
126 UniqueArc(Arc {
127 p,
128 phantom: PhantomData,
129 })
130 }
131 }
132
133 #[inline]
134 /// Convert to a shareable Arc<T> once we're done mutating it
135 pub fn shareable(self) -> Arc<T> {
136 self.0
137 }
138}
139
140impl<T> UniqueArc<mem::MaybeUninit<T>> {
141 /// Convert to an initialized Arc.
142 ///
143 /// # Safety
144 ///
145 /// See `MaybeUninit::assume_init`.
146 #[inline]
147 pub unsafe fn assume_init(this: Self) -> UniqueArc<T> {
148 UniqueArc(Arc {
149 p: mem::ManuallyDrop::new(this).0.p.cast(),
150 phantom: PhantomData,
151 })
152 }
153}
154
155impl<T> Deref for UniqueArc<T> {
156 type Target = T;
157 fn deref(&self) -> &T {
158 &self.0
159 }
160}
161
162impl<T> DerefMut for UniqueArc<T> {
163 fn deref_mut(&mut self) -> &mut T {
164 // We know this to be uniquely owned
165 unsafe { &mut (*self.0.ptr()).data }
166 }
167}
168
169unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
170unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}
171
172/// The object allocated by an Arc<T>
173///
174/// See https://github.com/mozilla/cbindgen/issues/937 for the derive-{eq,neq}=false. But we don't
175/// use those anyways so we can just disable them.
176/// cbindgen:derive-eq=false
177/// cbindgen:derive-neq=false
178#[repr(C)]
179struct ArcInner<T: ?Sized> {
180 count: atomic::AtomicUsize,
181 // NOTE(emilio): This needs to be here so that HeaderSlice<> is deallocated properly if the
182 // allocator relies on getting the right Layout. We don't need to track the right alignment,
183 // since we know that statically.
184 //
185 // This member could be completely avoided once min_specialization feature is stable (by
186 // implementing a trait for HeaderSlice that gives you the right layout). For now, servo-only
187 // since Gecko doesn't need it (its allocator doesn't need the size for the alignments we care
188 // about). See https://github.com/rust-lang/rust/issues/31844.
189 #[cfg(feature = "track_alloc_size")]
190 alloc_size: usize,
191 data: T,
192}
193
194unsafe impl<T: ?Sized + Sync + Send> Send for ArcInner<T> {}
195unsafe impl<T: ?Sized + Sync + Send> Sync for ArcInner<T> {}
196
197/// Computes the offset of the data field within ArcInner.
198fn data_offset<T>() -> usize {
199 let size = size_of::<ArcInner<()>>();
200 let align = align_of::<T>();
201 // https://github.com/rust-lang/rust/blob/1.36.0/src/libcore/alloc.rs#L187-L207
202 size.wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1)
203}
204
205impl<T> Arc<T> {
206 /// Construct an `Arc<T>`
207 #[inline]
208 pub fn new(data: T) -> Self {
209 let layout = Layout::new::<ArcInner<T>>();
210 let p = unsafe {
211 let ptr = ptr::NonNull::new(alloc::alloc(layout))
212 .unwrap_or_else(|| alloc::handle_alloc_error(layout))
213 .cast::<ArcInner<T>>();
214 ptr::write(
215 ptr.as_ptr(),
216 ArcInner {
217 count: atomic::AtomicUsize::new(1),
218 #[cfg(feature = "track_alloc_size")]
219 alloc_size: layout.size(),
220 data,
221 },
222 );
223 ptr
224 };
225
226 #[cfg(feature = "gecko_refcount_logging")]
227 unsafe {
228 // FIXME(emilio): Would be so amazing to have
229 // std::intrinsics::type_name() around, so that we could also report
230 // a real size.
231 NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8);
232 }
233
234 Arc {
235 p,
236 phantom: PhantomData,
237 }
238 }
239
240 /// Construct an intentionally-leaked arc.
241 #[inline]
242 pub fn new_leaked(data: T) -> Self {
243 let arc = Self::new(data);
244 arc.mark_as_intentionally_leaked();
245 arc
246 }
247
248 /// Convert the Arc<T> to a raw pointer, suitable for use across FFI
249 ///
250 /// Note: This returns a pointer to the data T, which is offset in the allocation.
251 #[inline]
252 pub fn into_raw(this: Self) -> *const T {
253 let ptr = unsafe { &((*this.ptr()).data) as *const _ };
254 mem::forget(this);
255 ptr
256 }
257
258 /// Reconstruct the Arc<T> from a raw pointer obtained from into_raw()
259 ///
260 /// # Safety
261 ///
262 /// Assumes that the pointer comes from an into_raw call. That is, this raw pointer will be
263 /// offset in the allocation and must be preceded by the atomic count.
264 #[inline]
265 pub unsafe fn from_raw(ptr: *const T) -> Self {
266 // To find the corresponding pointer to the `ArcInner` we need
267 // to subtract the offset of the `data` field from the pointer.
268 let ptr = unsafe { (ptr as *const u8).sub(data_offset::<T>()) };
269 Arc {
270 p: unsafe { ptr::NonNull::new_unchecked(ptr as *mut ArcInner<T>) },
271 phantom: PhantomData,
272 }
273 }
274
275 /// Like from_raw, but returns an addrefed arc instead.
276 ///
277 /// # Safety
278 ///
279 /// See `from_raw()`.
280 #[inline]
281 pub unsafe fn from_raw_addrefed(ptr: *const T) -> Self {
282 let arc = unsafe { Self::from_raw(ptr) };
283 mem::forget(arc.clone());
284 arc
285 }
286
287 /// Create a new static Arc<T> (one that won't reference count the object) and place it in the
288 /// allocation provided by the specified `alloc` function.
289 ///
290 /// # Safety
291 ///
292 /// `alloc` must return a pointer into a static allocation suitable for storing data with the
293 /// `Layout` passed into it. The pointer returned by `alloc` will not be freed.
294 #[inline]
295 pub unsafe fn new_static<F>(alloc: F, data: T) -> Arc<T>
296 where
297 F: FnOnce(Layout) -> *mut u8,
298 {
299 let layout = Layout::new::<ArcInner<T>>();
300 let ptr = alloc(layout) as *mut ArcInner<T>;
301
302 let x = ArcInner {
303 count: atomic::AtomicUsize::new(STATIC_REFCOUNT),
304 #[cfg(feature = "track_alloc_size")]
305 alloc_size: layout.size(),
306 data,
307 };
308
309 unsafe {
310 ptr::write(ptr, x);
311 }
312
313 Arc {
314 p: unsafe { ptr::NonNull::new_unchecked(ptr) },
315 phantom: PhantomData,
316 }
317 }
318
319 /// Produce a pointer to the data that can be converted back
320 /// to an Arc. This is basically an `&Arc<T>`, without the extra indirection.
321 /// It has the benefits of an `&T` but also knows about the underlying refcount
322 /// and can be converted into more `Arc<T>`s if necessary.
323 #[inline]
324 pub fn borrow_arc<'a>(&'a self) -> ArcBorrow<'a, T> {
325 ArcBorrow(&**self)
326 }
327
328 /// Returns the address on the heap of the Arc itself -- not the T within it -- for memory
329 /// reporting.
330 ///
331 /// If this is a static reference, this returns null.
332 pub fn heap_ptr(&self) -> *const c_void {
333 if self.inner().count.load(Relaxed) == STATIC_REFCOUNT {
334 ptr::null()
335 } else {
336 self.p.as_ptr() as *const ArcInner<T> as *const c_void
337 }
338 }
339}
340
341impl<T: ?Sized> Arc<T> {
342 #[inline]
343 fn inner(&self) -> &ArcInner<T> {
344 // This unsafety is ok because while this arc is alive we're guaranteed
345 // that the inner pointer is valid. Furthermore, we know that the
346 // `ArcInner` structure itself is `Sync` because the inner data is
347 // `Sync` as well, so we're ok loaning out an immutable pointer to these
348 // contents.
349 unsafe { &*self.ptr() }
350 }
351
352 #[inline(always)]
353 fn record_drop(&self) {
354 #[cfg(feature = "gecko_refcount_logging")]
355 unsafe {
356 NS_LogDtor(self.ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8);
357 }
358 }
359
360 /// Marks this `Arc` as intentionally leaked for the purposes of refcount
361 /// logging.
362 ///
363 /// It's a logic error to call this more than once, but it's not unsafe, as
364 /// it'd just report negative leaks.
365 ///
366 /// The allocation is expected to live for the rest of the process, so this
367 /// also marks it static: clone()/drop() then skip the atomic refcount
368 /// updates.
369 #[inline(always)]
370 pub fn mark_as_intentionally_leaked(&self) {
371 self.record_drop();
372 self.inner().count.store(STATIC_REFCOUNT, Relaxed);
373 }
374
375 // Non-inlined part of `drop`. Just invokes the destructor and calls the
376 // refcount logging machinery if enabled.
377 #[inline(never)]
378 unsafe fn drop_slow(&mut self) {
379 self.record_drop();
380 let inner = self.ptr();
381
382 unsafe {
383 let layout = Layout::for_value(&*inner);
384 #[cfg(feature = "track_alloc_size")]
385 let layout = Layout::from_size_align_unchecked((*inner).alloc_size, layout.align());
386
387 std::ptr::drop_in_place(inner);
388 alloc::dealloc(inner as *mut _, layout);
389 }
390 }
391
392 /// Test pointer equality between the two Arcs, i.e. they must be the _same_
393 /// allocation
394 #[inline]
395 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
396 this.raw_ptr() == other.raw_ptr()
397 }
398
399 fn ptr(&self) -> *mut ArcInner<T> {
400 self.p.as_ptr()
401 }
402
403 /// Returns a raw ptr to the underlying allocation.
404 pub fn raw_ptr(&self) -> ptr::NonNull<()> {
405 self.p.cast()
406 }
407}
408
409#[cfg(feature = "gecko_refcount_logging")]
410unsafe extern "C" {
411 fn NS_LogCtor(
412 aPtr: *mut std::os::raw::c_void,
413 aTypeName: *const std::os::raw::c_char,
414 aSize: u32,
415 );
416 fn NS_LogDtor(
417 aPtr: *mut std::os::raw::c_void,
418 aTypeName: *const std::os::raw::c_char,
419 aSize: u32,
420 );
421}
422
423impl<T: ?Sized> Clone for Arc<T> {
424 #[inline]
425 fn clone(&self) -> Self {
426 // NOTE(emilio): If you change anything here, make sure that the
427 // implementation in layout/style/ServoStyleConstsInlines.h matches!
428 //
429 // Using a relaxed ordering to check for STATIC_REFCOUNT is safe, since
430 // `count` never changes between STATIC_REFCOUNT and other values.
431 if self.inner().count.load(Relaxed) != STATIC_REFCOUNT {
432 // Using a relaxed ordering is alright here, as knowledge of the
433 // original reference prevents other threads from erroneously deleting
434 // the object.
435 //
436 // As explained in the [Boost documentation][1], Increasing the
437 // reference counter can always be done with memory_order_relaxed: New
438 // references to an object can only be formed from an existing
439 // reference, and passing an existing reference from one thread to
440 // another must already provide any required synchronization.
441 //
442 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
443 let old_size = self.inner().count.fetch_add(1, Relaxed);
444
445 // However we need to guard against massive refcounts in case someone
446 // is `mem::forget`ing Arcs. If we don't do this the count can overflow
447 // and users will use-after free. We racily saturate to `isize::MAX` on
448 // the assumption that there aren't ~2 billion threads incrementing
449 // the reference count at once. This branch will never be taken in
450 // any realistic program.
451 //
452 // We abort because such a program is incredibly degenerate, and we
453 // don't care to support it.
454 if old_size > MAX_REFCOUNT {
455 process::abort();
456 }
457 }
458
459 unsafe {
460 Arc {
461 p: ptr::NonNull::new_unchecked(self.ptr()),
462 phantom: PhantomData,
463 }
464 }
465 }
466}
467
468impl<T: ?Sized> Deref for Arc<T> {
469 type Target = T;
470
471 #[inline]
472 fn deref(&self) -> &T {
473 &self.inner().data
474 }
475}
476
477impl<T: Clone> Arc<T> {
478 /// Makes a mutable reference to the `Arc`, cloning if necessary
479 ///
480 /// This is functionally equivalent to [`Arc::make_mut`][mm] from the standard library.
481 ///
482 /// If this `Arc` is uniquely owned, `make_mut()` will provide a mutable
483 /// reference to the contents. If not, `make_mut()` will create a _new_ `Arc`
484 /// with a copy of the contents, update `this` to point to it, and provide
485 /// a mutable reference to its contents.
486 ///
487 /// This is useful for implementing copy-on-write schemes where you wish to
488 /// avoid copying things if your `Arc` is not shared.
489 ///
490 /// [mm]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html#method.make_mut
491 #[inline]
492 pub fn make_mut(this: &mut Self) -> &mut T {
493 if !this.is_unique() {
494 // Another pointer exists; clone
495 *this = Arc::new((**this).clone());
496 }
497
498 unsafe {
499 // This unsafety is ok because we're guaranteed that the pointer
500 // returned is the *only* pointer that will ever be returned to T. Our
501 // reference count is guaranteed to be 1 at this point, and we required
502 // the Arc itself to be `mut`, so we're returning the only possible
503 // reference to the inner data.
504 &mut (*this.ptr()).data
505 }
506 }
507}
508
509impl<T: ?Sized> Arc<T> {
510 /// Provides mutable access to the contents _if_ the `Arc` is uniquely owned.
511 #[inline]
512 pub fn get_mut(this: &mut Self) -> Option<&mut T> {
513 if this.is_unique() {
514 unsafe {
515 // See make_mut() for documentation of the threadsafety here.
516 Some(&mut (*this.ptr()).data)
517 }
518 } else {
519 None
520 }
521 }
522
523 /// Whether or not the `Arc` is a static reference.
524 #[inline]
525 pub fn is_static(&self) -> bool {
526 // Using a relaxed ordering to check for STATIC_REFCOUNT is safe, since
527 // `count` never changes between STATIC_REFCOUNT and other values.
528 self.inner().count.load(Relaxed) == STATIC_REFCOUNT
529 }
530
531 /// Whether or not the `Arc` is uniquely owned (is the refcount 1?) and not
532 /// a static reference.
533 #[inline]
534 pub fn is_unique(&self) -> bool {
535 // See the extensive discussion in [1] for why this needs to be Acquire.
536 //
537 // [1] https://github.com/servo/servo/issues/21186
538 self.inner().count.load(Acquire) == 1
539 }
540}
541
542impl<T: ?Sized> Drop for Arc<T> {
543 #[inline]
544 fn drop(&mut self) {
545 // NOTE(emilio): If you change anything here, make sure that the
546 // implementation in layout/style/ServoStyleConstsInlines.h matches!
547 if self.is_static() {
548 return;
549 }
550
551 // Because `fetch_sub` is already atomic, we do not need to synchronize
552 // with other threads unless we are going to delete the object.
553 if self.inner().count.fetch_sub(1, Release) != 1 {
554 return;
555 }
556
557 // FIXME(bholley): Use the updated comment when [2] is merged.
558 //
559 // This load is needed to prevent reordering of use of the data and
560 // deletion of the data. Because it is marked `Release`, the decreasing
561 // of the reference count synchronizes with this `Acquire` load. This
562 // means that use of the data happens before decreasing the reference
563 // count, which happens before this load, which happens before the
564 // deletion of the data.
565 //
566 // As explained in the [Boost documentation][1],
567 //
568 // > It is important to enforce any possible access to the object in one
569 // > thread (through an existing reference) to *happen before* deleting
570 // > the object in a different thread. This is achieved by a "release"
571 // > operation after dropping a reference (any access to the object
572 // > through this reference must obviously happened before), and an
573 // > "acquire" operation before deleting the object.
574 //
575 // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html)
576 // [2]: https://github.com/rust-lang/rust/pull/41714
577 self.inner().count.load(Acquire);
578
579 unsafe {
580 self.drop_slow();
581 }
582 }
583}
584
585impl<T: ?Sized + PartialEq> PartialEq for Arc<T> {
586 fn eq(&self, other: &Arc<T>) -> bool {
587 Self::ptr_eq(self, other) || *(*self) == *(*other)
588 }
589}
590
591impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> {
592 fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> {
593 (**self).partial_cmp(&**other)
594 }
595
596 fn lt(&self, other: &Arc<T>) -> bool {
597 *(*self) < *(*other)
598 }
599
600 fn le(&self, other: &Arc<T>) -> bool {
601 *(*self) <= *(*other)
602 }
603
604 fn gt(&self, other: &Arc<T>) -> bool {
605 *(*self) > *(*other)
606 }
607
608 fn ge(&self, other: &Arc<T>) -> bool {
609 *(*self) >= *(*other)
610 }
611}
612impl<T: ?Sized + Ord> Ord for Arc<T> {
613 fn cmp(&self, other: &Arc<T>) -> Ordering {
614 (**self).cmp(&**other)
615 }
616}
617impl<T: ?Sized + Eq> Eq for Arc<T> {}
618
619impl<T: ?Sized + fmt::Display> fmt::Display for Arc<T> {
620 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
621 fmt::Display::fmt(&**self, f)
622 }
623}
624
625impl<T: ?Sized + fmt::Debug> fmt::Debug for Arc<T> {
626 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
627 fmt::Debug::fmt(&**self, f)
628 }
629}
630
631impl<T: ?Sized> fmt::Pointer for Arc<T> {
632 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
633 fmt::Pointer::fmt(&self.ptr(), f)
634 }
635}
636
637impl<T: Default> Default for Arc<T> {
638 fn default() -> Arc<T> {
639 Arc::new(Default::default())
640 }
641}
642
643impl<T: ?Sized + Hash> Hash for Arc<T> {
644 fn hash<H: Hasher>(&self, state: &mut H) {
645 (**self).hash(state)
646 }
647}
648
649impl<T> From<T> for Arc<T> {
650 #[inline]
651 fn from(t: T) -> Self {
652 Arc::new(t)
653 }
654}
655
656impl<T: ?Sized> borrow::Borrow<T> for Arc<T> {
657 #[inline]
658 fn borrow(&self) -> &T {
659 self
660 }
661}
662
663impl<T: ?Sized> AsRef<T> for Arc<T> {
664 #[inline]
665 fn as_ref(&self) -> &T {
666 self
667 }
668}
669
670unsafe impl<T: ?Sized> StableDeref for Arc<T> {}
671unsafe impl<T: ?Sized> CloneStableDeref for Arc<T> {}
672
673#[cfg(feature = "servo")]
674impl<'de, T: Deserialize<'de>> Deserialize<'de> for Arc<T> {
675 fn deserialize<D>(deserializer: D) -> Result<Arc<T>, D::Error>
676 where
677 D: ::serde::de::Deserializer<'de>,
678 {
679 T::deserialize(deserializer).map(Arc::new)
680 }
681}
682
683#[cfg(feature = "servo")]
684impl<T: Serialize> Serialize for Arc<T> {
685 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
686 where
687 S: ::serde::ser::Serializer,
688 {
689 (**self).serialize(serializer)
690 }
691}
692
693/// Structure to allow Arc-managing some fixed-sized data and a variably-sized
694/// slice in a single allocation.
695///
696/// cbindgen:derive-eq=false
697/// cbindgen:derive-neq=false
698#[derive(Eq)]
699#[repr(C)]
700pub struct HeaderSlice<H, T> {
701 /// The fixed-sized data.
702 pub header: H,
703
704 /// The length of the slice at our end.
705 len: usize,
706
707 /// The dynamically-sized data.
708 data: [T; 0],
709}
710
711impl<H: PartialEq, T: PartialEq> PartialEq for HeaderSlice<H, T> {
712 fn eq(&self, other: &Self) -> bool {
713 self.header == other.header && self.slice() == other.slice()
714 }
715}
716
717impl<H, T> Drop for HeaderSlice<H, T> {
718 fn drop(&mut self) {
719 unsafe {
720 let mut ptr = self.data_mut();
721 for _ in 0..self.len {
722 std::ptr::drop_in_place(ptr);
723 ptr = ptr.offset(1);
724 }
725 }
726 }
727}
728
729impl<H: fmt::Debug, T: fmt::Debug> fmt::Debug for HeaderSlice<H, T> {
730 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
731 f.debug_struct("HeaderSlice")
732 .field("header", &self.header)
733 .field("slice", &self.slice())
734 .finish()
735 }
736}
737
738impl<H, T> HeaderSlice<H, T> {
739 /// Returns the dynamically sized slice in this HeaderSlice.
740 #[inline(always)]
741 pub fn slice(&self) -> &[T] {
742 unsafe { std::slice::from_raw_parts(self.data(), self.len) }
743 }
744
745 #[inline(always)]
746 fn data(&self) -> *const T {
747 std::ptr::addr_of!(self.data) as *const _
748 }
749
750 #[inline(always)]
751 fn data_mut(&mut self) -> *mut T {
752 std::ptr::addr_of_mut!(self.data) as *mut _
753 }
754
755 /// Returns the dynamically sized slice in this HeaderSlice.
756 #[inline(always)]
757 pub fn slice_mut(&mut self) -> &mut [T] {
758 unsafe { std::slice::from_raw_parts_mut(self.data_mut(), self.len) }
759 }
760
761 /// Returns the len of the slice.
762 #[inline(always)]
763 pub fn len(&self) -> usize {
764 self.len
765 }
766
767 /// Returns whether the slice is empty.
768 #[inline(always)]
769 pub fn is_empty(&self) -> bool {
770 self.len == 0
771 }
772}
773
774impl<H, T> Arc<HeaderSlice<H, T>> {
775 /// Creates an Arc for a HeaderSlice using the given header struct and
776 /// iterator to generate the slice.
777 ///
778 /// `is_static` indicates whether to create a static Arc.
779 ///
780 /// `alloc` is used to get a pointer to the memory into which the
781 /// dynamically sized ArcInner<HeaderSlice<H, T>> value will be
782 /// written. If `is_static` is true, then `alloc` must return a
783 /// pointer into some static memory allocation. If it is false,
784 /// then `alloc` must return an allocation that can be dellocated
785 /// by calling Box::from_raw::<ArcInner<HeaderSlice<H, T>>> on it.
786 #[inline]
787 pub fn from_header_and_iter_alloc<F, I>(
788 alloc: F,
789 header: H,
790 mut items: I,
791 num_items: usize,
792 is_static: bool,
793 ) -> Self
794 where
795 F: FnOnce(Layout) -> *mut u8,
796 I: Iterator<Item = T>,
797 {
798 assert_ne!(size_of::<T>(), 0, "Need to think about ZST");
799
800 let layout = Layout::new::<ArcInner<HeaderSlice<H, T>>>();
801 debug_assert!(layout.align() >= align_of::<T>());
802 debug_assert!(layout.align() >= align_of::<usize>());
803 let array_layout = Layout::array::<T>(num_items).expect("Overflow");
804 let (layout, _offset) = layout.extend(array_layout).expect("Overflow");
805 let p = unsafe {
806 // Allocate the buffer.
807 let buffer = alloc(layout);
808 let mut p = ptr::NonNull::new(buffer)
809 .unwrap_or_else(|| alloc::handle_alloc_error(layout))
810 .cast::<ArcInner<HeaderSlice<H, T>>>();
811
812 // Write the data.
813 //
814 // Note that any panics here (i.e. from the iterator) are safe, since
815 // we'll just leak the uninitialized memory.
816 let count = if is_static {
817 atomic::AtomicUsize::new(STATIC_REFCOUNT)
818 } else {
819 atomic::AtomicUsize::new(1)
820 };
821 ptr::write(&mut p.as_mut().count, count);
822 #[cfg(feature = "track_alloc_size")]
823 ptr::write(&mut p.as_mut().alloc_size, layout.size());
824 ptr::write(&mut p.as_mut().data.header, header);
825 ptr::write(&mut p.as_mut().data.len, num_items);
826 if num_items != 0 {
827 let mut current = std::ptr::addr_of_mut!(p.as_mut().data.data) as *mut T;
828 for _ in 0..num_items {
829 ptr::write(
830 current,
831 items
832 .next()
833 .expect("ExactSizeIterator over-reported length"),
834 );
835 current = current.offset(1);
836 }
837 // We should have consumed the buffer exactly, maybe accounting
838 // for some padding from the alignment.
839 debug_assert!(
840 (buffer.add(layout.size()) as usize - current as *mut u8 as usize)
841 < layout.align()
842 );
843 }
844 assert!(
845 items.next().is_none(),
846 "ExactSizeIterator under-reported length"
847 );
848 p
849 };
850 #[cfg(feature = "gecko_refcount_logging")]
851 unsafe {
852 if !is_static {
853 // FIXME(emilio): Would be so amazing to have
854 // std::intrinsics::type_name() around.
855 NS_LogCtor(p.as_ptr() as *mut _, b"ServoArc\0".as_ptr() as *const _, 8)
856 }
857 }
858
859 // Return the fat Arc.
860 assert_eq!(
861 size_of::<Self>(),
862 size_of::<usize>(),
863 "The Arc should be thin"
864 );
865
866 Arc {
867 p,
868 phantom: PhantomData,
869 }
870 }
871
872 /// Creates an Arc for a HeaderSlice using the given header struct and iterator to generate the
873 /// slice. Panics if num_items doesn't match the number of items.
874 #[inline]
875 pub fn from_header_and_iter_with_size<I>(header: H, items: I, num_items: usize) -> Self
876 where
877 I: Iterator<Item = T>,
878 {
879 Arc::from_header_and_iter_alloc(
880 |layout| unsafe { alloc::alloc(layout) },
881 header,
882 items,
883 num_items,
884 /* is_static = */ false,
885 )
886 }
887
888 /// Creates an Arc for a HeaderSlice using the given header struct and
889 /// iterator to generate the slice. The resulting Arc will be fat.
890 #[inline]
891 pub fn from_header_and_iter<I>(header: H, items: I) -> Self
892 where
893 I: Iterator<Item = T> + ExactSizeIterator,
894 {
895 let len = items.len();
896 Self::from_header_and_iter_with_size(header, items, len)
897 }
898}
899
900/// This is functionally equivalent to Arc<(H, [T])>
901///
902/// When you create an `Arc` containing a dynamically sized type like a slice, the `Arc` is
903/// represented on the stack as a "fat pointer", where the length of the slice is stored alongside
904/// the `Arc`'s pointer. In some situations you may wish to have a thin pointer instead, perhaps
905/// for FFI compatibility or space efficiency. `ThinArc` solves this by storing the length in the
906/// allocation itself, via `HeaderSlice`.
907pub type ThinArc<H, T> = Arc<HeaderSlice<H, T>>;
908
909/// See `ArcUnion`. This is a version that works for `ThinArc`s.
910pub type ThinArcUnion<H1, T1, H2, T2> = ArcUnion<HeaderSlice<H1, T1>, HeaderSlice<H2, T2>>;
911
912impl<H, T> UniqueArc<HeaderSlice<H, T>> {
913 #[inline]
914 pub fn from_header_and_iter<I>(header: H, items: I) -> Self
915 where
916 I: Iterator<Item = T> + ExactSizeIterator,
917 {
918 Self(Arc::from_header_and_iter(header, items))
919 }
920
921 #[inline]
922 pub fn from_header_and_iter_with_size<I>(header: H, items: I, num_items: usize) -> Self
923 where
924 I: Iterator<Item = T>,
925 {
926 Self(Arc::from_header_and_iter_with_size(
927 header, items, num_items,
928 ))
929 }
930
931 /// Returns a mutable reference to the header.
932 pub fn header_mut(&mut self) -> &mut H {
933 // We know this to be uniquely owned
934 unsafe { &mut (*self.0.ptr()).data.header }
935 }
936
937 /// Returns a mutable reference to the slice.
938 pub fn data_mut(&mut self) -> &mut [T] {
939 // We know this to be uniquely owned
940 unsafe { (*self.0.ptr()).data.slice_mut() }
941 }
942}
943
944/// A "borrowed `Arc`". This is a pointer to
945/// a T that is known to have been allocated within an
946/// `Arc`.
947///
948/// This is equivalent in guarantees to `&Arc<T>`, however it is
949/// a bit more flexible. To obtain an `&Arc<T>` you must have
950/// an `Arc<T>` instance somewhere pinned down until we're done with it.
951/// It's also a direct pointer to `T`, so using this involves less pointer-chasing
952///
953/// However, C++ code may hand us refcounted things as pointers to T directly,
954/// so we have to conjure up a temporary `Arc` on the stack each time.
955///
956/// `ArcBorrow` lets us deal with borrows of known-refcounted objects
957/// without needing to worry about where the `Arc<T>` is.
958#[derive(Debug, Eq, PartialEq)]
959pub struct ArcBorrow<'a, T: 'a>(&'a T);
960
961impl<'a, T> Copy for ArcBorrow<'a, T> {}
962impl<'a, T> Clone for ArcBorrow<'a, T> {
963 #[inline]
964 fn clone(&self) -> Self {
965 *self
966 }
967}
968
969impl<'a, T> ArcBorrow<'a, T> {
970 /// Clone this as an `Arc<T>`. This bumps the refcount.
971 #[inline]
972 pub fn clone_arc(&self) -> Arc<T> {
973 let arc = unsafe { Arc::from_raw(self.0) };
974 // addref it!
975 mem::forget(arc.clone());
976 arc
977 }
978
979 /// For constructing from a reference known to be Arc-backed.
980 ///
981 /// # Safety
982 ///
983 /// The reference must come from an object that's arc-allocated.
984 #[inline]
985 pub unsafe fn from_ref(r: &'a T) -> Self {
986 ArcBorrow(r)
987 }
988
989 /// Compare two `ArcBorrow`s via pointer equality. Will only return
990 /// true if they come from the same allocation
991 #[inline]
992 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
993 std::ptr::eq(this.0, other.0)
994 }
995
996 /// Temporarily converts |self| into a bonafide Arc and exposes it to the
997 /// provided callback. The refcount is not modified.
998 #[inline]
999 pub fn with_arc<F, U>(&self, f: F) -> U
1000 where
1001 F: FnOnce(&Arc<T>) -> U,
1002 T: 'static,
1003 {
1004 // Synthesize transient Arc, which never touches the refcount.
1005 let transient = unsafe { mem::ManuallyDrop::new(Arc::from_raw(self.0)) };
1006
1007 // Expose the transient Arc to the callback, which may clone it if it wants.
1008 let result = f(&transient);
1009
1010 // Forward the result.
1011 result
1012 }
1013
1014 /// Similar to deref, but uses the lifetime |a| rather than the lifetime of
1015 /// self, which is incompatible with the signature of the Deref trait.
1016 #[inline]
1017 pub fn get(&self) -> &'a T {
1018 self.0
1019 }
1020}
1021
1022impl<'a, T> Deref for ArcBorrow<'a, T> {
1023 type Target = T;
1024
1025 #[inline]
1026 fn deref(&self) -> &T {
1027 self.0
1028 }
1029}
1030
1031/// A tagged union that can represent `Arc<A>` or `Arc<B>` while only consuming a
1032/// single word. The type is also `NonNull`, and thus can be stored in an Option
1033/// without increasing size.
1034///
1035/// This is functionally equivalent to
1036/// `enum ArcUnion<A, B> { First(Arc<A>), Second(Arc<B>)` but only takes up
1037/// up a single word of stack space.
1038///
1039/// This could probably be extended to support four types if necessary.
1040pub struct ArcUnion<A, B> {
1041 p: ptr::NonNull<()>,
1042 phantom_a: PhantomData<A>,
1043 phantom_b: PhantomData<B>,
1044}
1045
1046unsafe impl<A: Sync + Send, B: Send + Sync> Send for ArcUnion<A, B> {}
1047unsafe impl<A: Sync + Send, B: Send + Sync> Sync for ArcUnion<A, B> {}
1048
1049impl<A: PartialEq, B: PartialEq> PartialEq for ArcUnion<A, B> {
1050 fn eq(&self, other: &Self) -> bool {
1051 use crate::ArcUnionBorrow::*;
1052 match (self.borrow(), other.borrow()) {
1053 (First(x), First(y)) => x == y,
1054 (Second(x), Second(y)) => x == y,
1055 (_, _) => false,
1056 }
1057 }
1058}
1059
1060impl<A: Eq, B: Eq> Eq for ArcUnion<A, B> {}
1061
1062/// This represents a borrow of an `ArcUnion`.
1063#[derive(Debug)]
1064pub enum ArcUnionBorrow<'a, A: 'a, B: 'a> {
1065 First(ArcBorrow<'a, A>),
1066 Second(ArcBorrow<'a, B>),
1067}
1068
1069impl<A, B> ArcUnion<A, B> {
1070 unsafe fn new(ptr: *mut ()) -> Self {
1071 ArcUnion {
1072 p: unsafe { ptr::NonNull::new_unchecked(ptr) },
1073 phantom_a: PhantomData,
1074 phantom_b: PhantomData,
1075 }
1076 }
1077
1078 /// Returns true if the two values are pointer-equal.
1079 #[inline]
1080 pub fn ptr_eq(this: &Self, other: &Self) -> bool {
1081 this.p == other.p
1082 }
1083
1084 #[inline]
1085 pub fn ptr(&self) -> ptr::NonNull<()> {
1086 self.p
1087 }
1088
1089 /// Returns an enum representing a borrow of either A or B.
1090 #[inline]
1091 pub fn borrow(&self) -> ArcUnionBorrow<'_, A, B> {
1092 if self.is_first() {
1093 let ptr = self.p.as_ptr() as *const ArcInner<A>;
1094 let borrow = unsafe { ArcBorrow::from_ref(&(*ptr).data) };
1095 ArcUnionBorrow::First(borrow)
1096 } else {
1097 let ptr = ((self.p.as_ptr() as usize) & !0x1) as *const ArcInner<B>;
1098 let borrow = unsafe { ArcBorrow::from_ref(&(*ptr).data) };
1099 ArcUnionBorrow::Second(borrow)
1100 }
1101 }
1102
1103 /// Creates an `ArcUnion` from an instance of the first type.
1104 pub fn from_first(other: Arc<A>) -> Self {
1105 let union = unsafe { Self::new(other.ptr() as *mut _) };
1106 mem::forget(other);
1107 union
1108 }
1109
1110 /// Creates an `ArcUnion` from an instance of the second type.
1111 pub fn from_second(other: Arc<B>) -> Self {
1112 let union = unsafe { Self::new(((other.ptr() as usize) | 0x1) as *mut _) };
1113 mem::forget(other);
1114 union
1115 }
1116
1117 /// Returns true if this `ArcUnion` contains the first type.
1118 pub fn is_first(&self) -> bool {
1119 self.p.as_ptr() as usize & 0x1 == 0
1120 }
1121
1122 /// Returns true if this `ArcUnion` contains the second type.
1123 pub fn is_second(&self) -> bool {
1124 !self.is_first()
1125 }
1126
1127 /// Returns a borrow of the first type if applicable, otherwise `None`.
1128 pub fn as_first(&self) -> Option<ArcBorrow<'_, A>> {
1129 match self.borrow() {
1130 ArcUnionBorrow::First(x) => Some(x),
1131 ArcUnionBorrow::Second(_) => None,
1132 }
1133 }
1134
1135 /// Returns a borrow of the second type if applicable, otherwise None.
1136 pub fn as_second(&self) -> Option<ArcBorrow<'_, B>> {
1137 match self.borrow() {
1138 ArcUnionBorrow::First(_) => None,
1139 ArcUnionBorrow::Second(x) => Some(x),
1140 }
1141 }
1142}
1143
1144impl<A, B> Clone for ArcUnion<A, B> {
1145 fn clone(&self) -> Self {
1146 match self.borrow() {
1147 ArcUnionBorrow::First(x) => ArcUnion::from_first(x.clone_arc()),
1148 ArcUnionBorrow::Second(x) => ArcUnion::from_second(x.clone_arc()),
1149 }
1150 }
1151}
1152
1153impl<A, B> Drop for ArcUnion<A, B> {
1154 fn drop(&mut self) {
1155 match self.borrow() {
1156 ArcUnionBorrow::First(x) => unsafe {
1157 let _ = Arc::from_raw(&*x);
1158 },
1159 ArcUnionBorrow::Second(x) => unsafe {
1160 let _ = Arc::from_raw(&*x);
1161 },
1162 }
1163 }
1164}
1165
1166impl<A: fmt::Debug, B: fmt::Debug> fmt::Debug for ArcUnion<A, B> {
1167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1168 fmt::Debug::fmt(&self.borrow(), f)
1169 }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174 use super::{Arc, ThinArc};
1175 use std::clone::Clone;
1176 use std::ops::Drop;
1177 use std::sync::atomic;
1178 use std::sync::atomic::Ordering::{Acquire, SeqCst};
1179
1180 #[derive(PartialEq)]
1181 struct Canary(*mut atomic::AtomicUsize);
1182
1183 impl Drop for Canary {
1184 fn drop(&mut self) {
1185 unsafe {
1186 (*self.0).fetch_add(1, SeqCst);
1187 }
1188 }
1189 }
1190
1191 #[test]
1192 fn empty_thin() {
1193 let x = Arc::from_header_and_iter(100u32, std::iter::empty::<i32>());
1194 assert_eq!(x.header, 100);
1195 assert!(x.slice().is_empty());
1196 }
1197
1198 #[test]
1199 fn thin_assert_padding() {
1200 #[derive(Clone, Default)]
1201 #[repr(C)]
1202 struct Padded {
1203 i: u16,
1204 }
1205
1206 // The header will have more alignment than `Padded`
1207 let items = vec![Padded { i: 0xdead }, Padded { i: 0xbeef }];
1208 let a = ThinArc::from_header_and_iter(0i32, items.into_iter());
1209 assert_eq!(a.len(), 2);
1210 assert_eq!(a.slice()[0].i, 0xdead);
1211 assert_eq!(a.slice()[1].i, 0xbeef);
1212 }
1213
1214 #[test]
1215 fn slices_and_thin() {
1216 let mut canary = atomic::AtomicUsize::new(0);
1217 let c = Canary(&mut canary as *mut atomic::AtomicUsize);
1218 let v = vec![5, 6];
1219 {
1220 let x = Arc::from_header_and_iter(c, v.into_iter());
1221 let _ = x.clone();
1222 let _ = x == x;
1223 }
1224 assert_eq!(canary.load(Acquire), 1);
1225 }
1226}