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
use super::error::{Error, Result};
use core::fmt::{Debug, Formatter};
use core::marker::PhantomData;
use core::mem::forget;
use core::num::NonZeroU32;
use minicbor::data::Tag;
use minicbor::decode::{Decode, Decoder};
use minicbor::encode::{Encode, Encoder, Write};
use oc_wasm_sys::descriptor as sys;

/// The Identifier CBOR tag number.
const IDENTIFIER: u64 = 39;

/// CBOR-encodes an opaque value descriptor.
///
/// This produces an integer with the Identifier (39) tag.
fn cbor_encode<W: Write>(
	descriptor: u32,
	e: &mut Encoder<W>,
) -> core::result::Result<(), minicbor::encode::Error<W::Error>> {
	e.tag(Tag::Unassigned(IDENTIFIER))?.u32(descriptor)?;
	Ok(())
}

/// A value that can be converted into an opaque value descriptor.
///
/// A value implementing this trait holds, borrows, or is otherwise able to provide an opaque value
/// descriptor as a `u32`.
pub trait AsRaw {
	/// Returns the raw descriptor value.
	#[must_use = "This function is only useful for its return value"]
	fn as_raw(&self) -> u32;
}

/// A value that can be borrowed as an opaque value descriptor.
///
/// A value implementing this trait is able to produce a [`Borrowed`](Borrowed) value referring to
/// a descriptor.
#[allow(clippy::module_name_repetitions)] // This is the best name I could come up with.
pub trait AsDescriptor {
	/// Borrows the descriptor.
	#[must_use = "This function is only useful for its return value"]
	fn as_descriptor(&self) -> Borrowed<'_>;
}

/// A value that can be converted into an opaque value descriptor.
///
/// A value implementing this trait is able to produce an [`Owned`](Owned) value referring to a
/// descriptor by consuming itself.
#[allow(clippy::module_name_repetitions)] // This is the best name I could come up with.
pub trait IntoDescriptor {
	/// Converts to the descriptor.
	#[must_use = "This function is only useful for its return value"]
	fn into_descriptor(self) -> Owned;
}

/// An owned opaque value descriptor.
///
/// A value of this type encapsulates an opaque value descriptor. Cloning it duplicates the
/// descriptor. Dropping it closes the descriptor. CBOR-encoding it yields an integer with the
/// Identifier (39) tag.
#[derive(Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Owned(NonZeroU32);

impl Owned {
	/// Wraps a raw integer descriptor in a `Descriptor` object.
	///
	/// # Safety
	/// The caller must ensure that the passed-in value is a valid, open descriptor. Passing a
	/// closed descriptor may result in dropping the object closing an unrelated opaque value which
	/// happened to be allocated the same descriptor value. Passing an invalid descriptor value may
	/// violate the niche requirements and result in undefined behaviour.
	///
	/// The caller must ensure that only one `Descriptor` object for a given value exists at a
	/// time, because dropping a `Descriptor` object closes the descriptor.
	#[allow(clippy::must_use_candidate)] // This could be called and immediately dropped to close an unwanted descriptor.
	pub const unsafe fn new(raw: u32) -> Self {
		// SAFETY: The caller is required to pass a valid descriptor. Any valid descriptor is a
		// small nonnegative integer. Therefore, any descriptor plus one is a small positive
		// integer.
		Self(NonZeroU32::new_unchecked(raw + 1))
	}

	/// Destroys a `Descriptor` object and returns the raw value.
	///
	/// The caller must ensure that the descriptor is eventually closed. This function is safe
	/// because Rust’s safety guarantees to not include reliable freeing of resources; however,
	/// care should be taken when calling it.
	#[must_use = "The returned descriptor will leak if not manually closed"]
	pub const fn into_inner(self) -> u32 {
		let ret = self.as_raw();
		forget(self);
		ret
	}

	/// Returns the raw descriptor value.
	#[must_use = "This function is only useful for its return value"]
	pub const fn as_raw(&self) -> u32 {
		self.0.get() - 1
	}

	/// Duplicates the descriptor.
	///
	/// # Errors
	/// * [`TooManyDescriptors`](Error::TooManyDescriptors) is returned if the descriptor table is
	///   too full and some descriptors must be closed.
	pub fn dup(&self) -> Result<Self> {
		// SAFETY: dup can be invoked with any valid descriptor.
		let new_desc = Error::from_i32(unsafe { sys::dup(self.as_raw()) })?;
		// SAFETY: dup returns a fresh, new descriptor on success.
		Ok(unsafe { Self::new(new_desc) })
	}
}

impl AsRaw for Owned {
	fn as_raw(&self) -> u32 {
		self.0.get() - 1
	}
}

impl AsDescriptor for Owned {
	fn as_descriptor(&self) -> Borrowed<'_> {
		Borrowed(self.0, PhantomData)
	}
}

impl IntoDescriptor for Owned {
	fn into_descriptor(self) -> Owned {
		self
	}
}

impl Debug for Owned {
	fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
		self.as_raw().fmt(f)
	}
}

impl Drop for Owned {
	fn drop(&mut self) {
		// SAFETY: The contained descriptor is always valid. There can be only one Owned object in
		// existence for a given open descriptor. There is no safe way to close a descriptor other
		// than dropping the Owned object. Therefore, the descriptor is valid and closing it will
		// not break any other objects.
		unsafe { sys::close(self.as_raw()) };
	}
}

impl Encode for Owned {
	fn encode<W: Write>(
		&self,
		e: &mut Encoder<W>,
	) -> core::result::Result<(), minicbor::encode::Error<W::Error>> {
		cbor_encode(self.as_raw(), e)
	}
}

/// A borrowed opaque value descriptor.
///
/// A value of this type encapsulates an opaque value descriptor. Copying or cloning it produces a
/// new object containing the same descriptor. Dropping it does nothing. CBOR-encoding it yields an
/// integer with the Identifier (39) tag. While a value of this type exists, lifetime rules prevent
/// the modification or dropping of the [`Owned`](Owned) value from which it borrowed its
/// descriptor.
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Borrowed<'a>(NonZeroU32, PhantomData<&'a NonZeroU32>);

impl<'a> Borrowed<'a> {
	/// Returns the raw descriptor value.
	#[must_use = "This function is only useful for its return value"]
	pub const fn as_raw(self) -> u32 {
		self.0.get() - 1
	}
}

impl<'a> AsRaw for Borrowed<'a> {
	fn as_raw(&self) -> u32 {
		self.0.get() - 1
	}
}

impl<'a> AsDescriptor for Borrowed<'a> {
	fn as_descriptor(&self) -> Borrowed<'_> {
		*self
	}
}

impl<'a> Debug for Borrowed<'a> {
	fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
		self.as_raw().fmt(f)
	}
}

impl<'a> Encode for Borrowed<'a> {
	fn encode<W: Write>(
		&self,
		e: &mut Encoder<W>,
	) -> core::result::Result<(), minicbor::encode::Error<W::Error>> {
		cbor_encode(self.as_raw(), e)
	}
}

/// A CBOR-decoded opaque value descriptor.
///
/// A value of this type encapsulates an opaque value descriptor. It cannot be cloned. Dropping it
/// does nothing; this may cause a resource leak, but resource leaks are not considered unsafe
/// Rust, and under the circumstances, closing the descriptor could be unsafe (see the safety note
/// on [`into_owned`](Decoded::into_owned) for why). The intended use of this type is to
/// immediately call [`into_owned`](Decoded::into_owned) to convert the value into an
/// [`Owned`](Owned) instead.
#[derive(Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Decoded(NonZeroU32);

impl Decoded {
	/// Converts a `Decoded` descriptor into an [`Owned`](Owned) descriptor.
	///
	/// # Safety
	/// The caller must ensure that the `Decoded` descriptor is the only reference to the
	/// descriptor it holds, and that that descriptor is valid. Generally, this is accomplished by
	/// obtaining a `Decoded` descriptor by CBOR-decoding the result of a method call, because
	/// OC-Wasm guarantees that any opaque value returned from a method call is represented by a
	/// fresh descriptor.
	///
	/// The reason why this method is unsafe is that a caller could potentially craft an arbitrary
	/// CBOR sequence in a byte buffer, then decode it. If such a decoding operation were to return
	/// an [`Owned`](Owned) directly, this would be unsound, as the caller could decode a second
	/// [`Owned`](Owned) referring to the same descriptor as an existing [`Owned`](Owned) or an
	/// [`Owned`](Owned) referring to a closed descriptor. Instead, CBOR decoding (which is itself
	/// safe) can only create a `Decoded`, which does not claim exclusive ownership (or even
	/// validity) of the contained descriptor but also cannot actually be used as a descriptor; the
	/// caller is forced to promise those properties in order to convert to the actually useful
	/// [`Owned`](Owned) type via this `unsafe` method.
	#[allow(clippy::must_use_candidate)] // If caller doesn’t want the descriptor, they can do this and immediately drop.
	pub unsafe fn into_owned(self) -> Owned {
		Owned(self.0)
	}
}

impl Debug for Decoded {
	fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
		(self.0.get() - 1).fmt(f)
	}
}

impl<'b> Decode<'b> for Decoded {
	fn decode(d: &mut Decoder<'b>) -> core::result::Result<Self, minicbor::decode::Error> {
		let tag = d.tag()?;
		if tag != Tag::Unassigned(IDENTIFIER) {
			return Err(minicbor::decode::Error::Message("expected Identifier tag"));
		}
		Ok(Self(NonZeroU32::new(d.u32()? + 1).unwrap()))
	}
}