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
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::mem; use std::ptr; use std::ops::Deref; use std::marker::PhantomData; use std::cell::Cell; use std::sync::atomic::{self, AtomicUsize, Ordering}; use nserror::{NsresultExt, nsresult, NS_OK}; use libc; use interfaces::nsrefcnt; /// A trait representing a type which can be reference counted invasively. /// The object is responsible for freeing its backing memory when its /// reference count reaches 0. pub unsafe trait RefCounted { /// Increment the reference count. unsafe fn addref(&self); /// Decrement the reference count, potentially freeing backing memory. unsafe fn release(&self); } /// A smart pointer holding a RefCounted object. The object itself manages its /// own memory. RefPtr will invoke the addref and release methods at the /// appropriate times to facilitate the bookkeeping. pub struct RefPtr<T: RefCounted + 'static> { // We're going to cheat and store the internal reference as an &'static T // instead of an *const T or Shared<T>, because Shared and NonZero are // unstable, and we need to build on stable rust. // I believe that this is "safe enough", as this module is private and // no other module can read this reference. _ptr: &'static T, // As we aren't using Shared<T>, we need to add this phantomdata to // prevent unsoundness in dropck _marker: PhantomData<T>, } impl <T: RefCounted + 'static> RefPtr<T> { /// Construct a new RefPtr from a reference to the refcounted object. #[inline] pub fn new(p: &T) -> RefPtr<T> { unsafe { p.addref(); RefPtr { _ptr: mem::transmute(p), _marker: PhantomData, } } } /// Construct a RefPtr from a raw pointer, addrefing it. #[inline] pub unsafe fn from_raw(p: *const T) -> Option<RefPtr<T>> { if p.is_null() { return None; } (*p).addref(); Some(RefPtr { _ptr: &*p, _marker: PhantomData, }) } /// Construct a RefPtr from a raw pointer, without addrefing it. #[inline] pub unsafe fn from_raw_dont_addref(p: *const T) -> Option<RefPtr<T>> { if p.is_null() { return None; } Some(RefPtr { _ptr: &*p, _marker: PhantomData, }) } /// Write this RefPtr's value into an outparameter. #[inline] pub unsafe fn forget(self, into: &mut *const T) { *into = &*self as *const T; mem::forget(self); } } impl <T: RefCounted + 'static> Deref for RefPtr<T> { type Target = T; #[inline] fn deref(&self) -> &T { self._ptr } } impl <T: RefCounted + 'static> Drop for RefPtr<T> { #[inline] fn drop(&mut self) { unsafe { self._ptr.release(); } } } impl <T: RefCounted + 'static> Clone for RefPtr<T> { #[inline] fn clone(&self) -> RefPtr<T> { RefPtr::new(self) } } /// A helper struct for constructing `RefPtr<T>` from raw pointer outparameters. /// Holds a `*const T` internally which will be released if non null when /// destructed, and can be easily transformed into an `Option<RefPtr<T>>`. /// /// It many cases it may be easier to use the `getter_addrefs` method. pub struct GetterAddrefs<T: RefCounted + 'static> { _ptr: *const T, _marker: PhantomData<T>, } impl <T: RefCounted + 'static> GetterAddrefs<T> { /// Create a `GetterAddrefs`, initializing it with the null pointer. #[inline] pub fn new() -> GetterAddrefs<T> { GetterAddrefs { _ptr: ptr::null(), _marker: PhantomData, } } /// Get a reference to the internal `*const T`. This method is unsafe, /// as the destructor of this class depends on the internal `*const T` /// being either a valid reference to a value of type `T`, or null. #[inline] pub unsafe fn ptr(&mut self) -> &mut *const T { &mut self._ptr } /// Get a reference to the internal `*const T` as a `*mut libc::c_void`. /// This is useful to pass to functions like `GetInterface` which take a /// void pointer outparameter. #[inline] pub unsafe fn void_ptr(&mut self) -> *mut *mut libc::c_void { &mut self._ptr as *mut *const T as *mut *mut libc::c_void } /// Transform this `GetterAddrefs` into an `Option<RefPtr<T>>`, without /// performing any addrefs or releases. #[inline] pub fn refptr(self) -> Option<RefPtr<T>> { let p = self._ptr; // Don't run the destructor because we don't want to release the stored // pointer. mem::forget(self); unsafe { RefPtr::from_raw_dont_addref(p) } } } impl <T: RefCounted + 'static> Drop for GetterAddrefs<T> { #[inline] fn drop(&mut self) { if !self._ptr.is_null() { unsafe { (*self._ptr).release(); } } } } /// Helper method for calling XPCOM methods which return a reference counted /// value through an outparameter. Takes a lambda, which is called with a valid /// outparameter argument (`*mut *const T`), and returns a `nsresult`. Returns /// either a `RefPtr<T>` with the value returned from the outparameter, or a /// `nsresult`. /// /// # NOTE: /// /// Can return `Err(NS_OK)` if the call succeeded, but the outparameter was set /// to NULL. /// /// # Usage /// /// ``` /// let x: Result<RefPtr<T>, nsresult> = /// getter_addrefs(|p| iosvc.NewURI(uri, ptr::null(), ptr::null(), p)); /// ``` #[inline] pub fn getter_addrefs<T: RefCounted, F>(f: F) -> Result<RefPtr<T>, nsresult> where F: FnOnce(*mut *const T) -> nsresult { let mut ga = GetterAddrefs::<T>::new(); let rv = f(unsafe { ga.ptr() }); if rv.failed() { return Err(rv); } ga.refptr().ok_or(NS_OK) } /// The type of the reference count type for xpcom structs. /// /// `#[derive(xpcom)]` will use this type for the `__refcnt` field when /// `#[refcnt = "nonatomic"]` is used. #[derive(Debug)] pub struct Refcnt(Cell<nsrefcnt>); impl Refcnt { /// Create a new reference count value. This is unsafe as manipulating /// Refcnt values is an easy footgun. pub unsafe fn new() -> Self { Refcnt(Cell::new(0)) } /// Increment the reference count. Returns the new reference count. This is /// unsafe as modifying this value can cause a use-after-free. pub unsafe fn inc(&self) -> nsrefcnt { // XXX: Checked add? let new = self.0.get() + 1; self.0.set(new); new } /// Decrement the reference count. Returns the new reference count. This is /// unsafe as modifying this value can cause a use-after-free. pub unsafe fn dec(&self) -> nsrefcnt { // XXX: Checked sub? let new = self.0.get() - 1; self.0.set(new); new } /// Get the current value of the reference count. pub fn get(&self) -> nsrefcnt { self.0.get() } } /// The type of the atomic reference count used for xpcom structs. /// /// `#[derive(xpcom)]` will use this type for the `__refcnt` field when /// `#[refcnt = "atomic"]` is used. /// /// See `nsISupportsImpl.h`'s `ThreadSafeAutoRefCnt` class for reasoning behind /// memory ordering decisions. #[derive(Debug)] pub struct AtomicRefcnt(AtomicUsize); impl AtomicRefcnt { /// Create a new reference count value. This is unsafe as manipulating /// Refcnt values is an easy footgun. pub unsafe fn new() -> Self { AtomicRefcnt(AtomicUsize::new(0)) } /// Increment the reference count. Returns the new reference count. This is /// unsafe as modifying this value can cause a use-after-free. pub unsafe fn inc(&self) -> nsrefcnt { self.0.fetch_add(1, Ordering::Relaxed) as nsrefcnt + 1 } /// Decrement the reference count. Returns the new reference count. This is /// unsafe as modifying this value can cause a use-after-free. pub unsafe fn dec(&self) -> nsrefcnt { let result = self.0.fetch_sub(1, Ordering::Release) as nsrefcnt - 1; if result == 0 { // We're going to destroy the object on this thread. atomic::fence(Ordering::Acquire); } result } /// Get the current value of the reference count. pub fn get(&self) -> nsrefcnt { self.0.load(Ordering::Acquire) as nsrefcnt } }