-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
477 lines (467 loc) · 13.3 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
//! A type to wrap `&'static` references such that they can be safely sent
//! between other processes running the same binary.
//!
//! **[Crates.io](https://crates.io/crates/relative) │ [Repo](https://github.com/alecmocatta/relative)**
//!
//! References are adjusted relative to a base when (de)serialised, which
//! is what enables it to work across binaries that are dynamically loaded at
//! different addresses under multiple invocations.
//!
//! It being the same binary is checked by serialising the
//! [`build_id`](https://docs.rs/build_id) alongside the relative pointer, which
//! is validated at deserialisation.
//!
//! # Example
//! ### Local process
//! ```
//! # use relative::*;
//! let x: &'static [u16;4] = &[2,3,5,8];
//! // unsafe as it's up to the user to ensure the reference is into static memory
//! let relative = unsafe{Data::from(x)};
//! // send `relative` to remote...
//! ```
//! ### Remote process
//! ```
//! # use relative::*;
//! # let x: &'static [u16;4] = &[2,3,5,8];
//! # let relative = unsafe{Data::from(x)};
//! // receive `relative`
//! println!("{:?}", relative.to());
//! // prints "[2, 3, 5, 8]"
//! ```
//!
//! # Note
//!
//! This currently requires Rust nightly.
#![doc(html_root_url = "https://docs.rs/relative/0.1.3")]
#![feature(core_intrinsics, raw, used)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results,
clippy::pedantic
)] // from https://github.com/rust-unofficial/patterns/blob/master/anti_patterns/deny-warnings.md
#![allow(
stable_features,
clippy::inline_always,
clippy::doc_markdown,
clippy::trivially_copy_pass_by_ref
)]
extern crate build_id;
#[cfg(test)]
extern crate metatype;
extern crate serde;
extern crate uuid;
#[cfg(test)]
#[macro_use]
extern crate serde_derive;
#[cfg(test)]
extern crate bincode;
#[cfg(test)]
extern crate serde_json;
#[cfg(test)]
mod tests;
use std::{any, cmp, fmt, hash, intrinsics, marker, mem, raw};
#[doc(hidden)]
#[used]
#[no_mangle]
pub static RELATIVE_DATA_BASE: () = ();
#[doc(hidden)]
#[no_mangle]
#[inline(never)]
pub fn relative_code_base() {
unsafe { intrinsics::unreachable() }
}
#[doc(hidden)]
#[used]
#[no_mangle]
pub static RELATIVE_VTABLE_BASE: &(any::Any + Sync) = &() as &(any::Any + Sync);
/// Wraps function pointers such that they can be safely sent between other
/// processes running the same binary.
///
/// For references into the code aka text segment.
///
/// The base used is the address of a function:
/// ```rust,ignore
/// #[no_mangle]
/// #[inline(never)]
/// pub fn relative_code_base() {
/// unsafe { intrinsics::unreachable() }
/// }
///
/// let base = relative_code_base as usize;
/// ```
pub struct Code<T: ?Sized>(usize, marker::PhantomData<fn(T)>);
impl<T: ?Sized> Code<T> {
#[inline(always)]
fn new(p: usize) -> Self {
Code(p, marker::PhantomData)
}
/// Create a `Code<T>` from a `*const ()`.
///
/// This is unsafe as it is up to the user to ensure the pointer lies within
/// static memory.
///
/// i.e. the pointer needs to be positioned the same relative to the base in
/// every invocation, through e.g. being in the same segment, or the binary
/// being statically linked.
#[inline(always)]
pub unsafe fn from(ptr: *const ()) -> Self {
let base = relative_code_base as usize;
// println!("from: {}: {}", base, intrinsics::type_name::<T>());
Self::new((ptr as usize).wrapping_sub(base))
}
/// Get back a `*const ()` from a `Code<T>`.
#[inline(always)]
pub fn to(&self) -> *const () {
let base = relative_code_base as usize;
// println!("to: {}: {}", base, intrinsics::type_name::<T>());
base.wrapping_add(self.0) as *const ()
}
}
impl<T: ?Sized> Clone for Code<T> {
#[inline(always)]
fn clone(&self) -> Self {
Code(self.0, marker::PhantomData)
}
}
impl<T: ?Sized> Copy for Code<T> {}
impl<T: ?Sized> PartialEq for Code<T> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: ?Sized> Eq for Code<T> {}
impl<T: ?Sized> hash::Hash for Code<T> {
#[inline(always)]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl<T: ?Sized> PartialOrd for Code<T> {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl<T: ?Sized> Ord for Code<T> {
#[inline(always)]
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.0.cmp(&other.0)
}
}
impl<T: ?Sized> fmt::Debug for Code<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Code")
.field(unsafe { intrinsics::type_name::<T>() }, &self.0)
.finish()
}
}
impl<T: ?Sized + 'static> serde::ser::Serialize for Code<T> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
<(uuid::Uuid, u64, usize) as serde::ser::Serialize>::serialize(
&(
build_id::get(),
unsafe { intrinsics::type_id::<T>() },
self.0,
),
serializer,
)
}
}
impl<'de, T: ?Sized + 'static> serde::de::Deserialize<'de> for Code<T> {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
<(uuid::Uuid, u64, usize) as serde::de::Deserialize<'de>>::deserialize(deserializer)
.and_then(|(build, id, ptr)| {
let local = build_id::get();
if build == local {
if id == unsafe { intrinsics::type_id::<T>() } {
Ok(Self::new(ptr))
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference to wrong type ???:{}, expected {}:{}",
id,
unsafe { intrinsics::type_name::<T>() },
unsafe { intrinsics::type_id::<T>() }
)))
}
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference came from a different binary {}, expected {}",
build, local
)))
}
})
}
}
/// Wraps `&'static` references such that they can be safely sent between other
/// processes running the same binary.
///
/// For references into the data and BSS segments.
///
/// The base used is the address of a zero sized static item:
/// ```rust,ignore
/// #[used]
/// #[no_mangle]
/// pub static RELATIVE_DATA_BASE: () = ();
///
/// let base = &RELATIVE_DATA_BASE as *const () as usize;
/// ```
pub struct Data<T>(usize, marker::PhantomData<fn(T)>);
impl<T> Data<T> {
#[inline(always)]
fn new(p: usize) -> Self {
Data(p, marker::PhantomData)
}
/// Create a `Data<T>` from a `&'static T`.
///
/// This is unsafe as it is up to the user to ensure the pointer lies within
/// static memory.
///
/// i.e. the pointer needs to be positioned the same relative to the base in
/// every invocation, through e.g. being in the same segment, or the binary
/// being statically linked.
#[inline(always)]
pub unsafe fn from(ptr: &'static T) -> Self {
let base = &RELATIVE_DATA_BASE as *const () as usize;
// println!("from: {}: {}", base, intrinsics::type_name::<T>());
Self::new((ptr as *const T as usize).wrapping_sub(base))
}
/// Get back a `&'static T` from a `Data<T>`.
#[inline(always)]
pub fn to(&self) -> &'static T {
let base = &RELATIVE_DATA_BASE as *const () as usize;
// println!("to: {}: {}", base, intrinsics::type_name::<T>());
unsafe { &*(base.wrapping_add(self.0) as *const T) }
}
}
impl<T> Clone for Data<T> {
#[inline(always)]
fn clone(&self) -> Self {
Data(self.0, marker::PhantomData)
}
}
impl<T> Copy for Data<T> {}
impl<T> PartialEq for Data<T> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T> Eq for Data<T> {}
impl<T> hash::Hash for Data<T> {
#[inline(always)]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl<T> PartialOrd for Data<T> {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl<T> Ord for Data<T> {
#[inline(always)]
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.0.cmp(&other.0)
}
}
impl<T> fmt::Debug for Data<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Data")
.field(unsafe { intrinsics::type_name::<T>() }, &self.0)
.finish()
}
}
impl<T: 'static> serde::ser::Serialize for Data<T> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
<(uuid::Uuid, u64, usize) as serde::ser::Serialize>::serialize(
&(
build_id::get(),
unsafe { intrinsics::type_id::<T>() },
self.0,
),
serializer,
)
}
}
impl<'de, T: 'static> serde::de::Deserialize<'de> for Data<T> {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
<(uuid::Uuid, u64, usize) as serde::de::Deserialize<'de>>::deserialize(deserializer)
.and_then(|(build, id, ptr)| {
let local = build_id::get();
if build == local {
if id == unsafe { intrinsics::type_id::<T>() } {
Ok(Self::new(ptr))
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference to wrong type ???:{}, expected {}:{}",
id,
unsafe { intrinsics::type_name::<T>() },
unsafe { intrinsics::type_id::<T>() }
)))
}
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference came from a different binary {}, expected {}",
build, local
)))
}
})
}
}
/// Wraps `&'static` references to vtables such that they can be safely sent
/// between other processes running the same binary.
///
/// For references into the segment that houses the vtables, typically the
/// read-only data segment aka rodata.
///
/// The base used is the vtable of a static trait object:
/// ```rust,ignore
/// #[doc(hidden)]
/// #[used]
/// #[no_mangle]
/// pub static RELATIVE_VTABLE_BASE: &(any::Any+Sync) = &() as &(any::Any+Sync);
///
/// let base = mem::transmute::<*const any::Any, raw::TraitObject>(RELATIVE_VTABLE_BASE).vtable as usize;
/// ```
pub struct Vtable<T: ?Sized>(usize, marker::PhantomData<fn(T)>);
impl<T: ?Sized> Vtable<T> {
#[inline(always)]
fn new(p: usize) -> Self {
Vtable(p, marker::PhantomData)
}
/// Create a `Vtable<T>` from a `&'static ()`.
///
/// This is unsafe as it is up to the user to ensure the pointer lies within
/// static memory.
///
/// i.e. the pointer needs to be positioned the same relative to the base in
/// every invocation, through e.g. being in the same segment, or the binary
/// being statically linked.
#[inline(always)]
pub unsafe fn from(ptr: &'static ()) -> Self {
let base = mem::transmute::<*const any::Any, raw::TraitObject>(RELATIVE_VTABLE_BASE).vtable
as usize;
// let data_base = &RELATIVE_DATA_BASE as *const () as usize;
// println!("from: {}: {}", base.wrapping_sub(data_base), unsafe{intrinsics::type_name::<T>()});
Self::new((ptr as *const () as usize).wrapping_sub(base))
}
/// Get back a `&'static ()` from a `Vtable<T>`.
#[inline(always)]
pub fn to(&self) -> &'static () {
let base =
unsafe { mem::transmute::<*const any::Any, raw::TraitObject>(RELATIVE_VTABLE_BASE) }
.vtable as usize;
// let data_base = &RELATIVE_DATA_BASE as *const () as usize;
// println!("to: {}: {}", base.wrapping_sub(data_base), unsafe{intrinsics::type_name::<T>()});
unsafe { &*(base.wrapping_add(self.0) as *const ()) }
}
}
impl<T: ?Sized> Clone for Vtable<T> {
#[inline(always)]
fn clone(&self) -> Self {
Vtable(self.0, marker::PhantomData)
}
}
impl<T: ?Sized> Copy for Vtable<T> {}
impl<T: ?Sized> PartialEq for Vtable<T> {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T: ?Sized> Eq for Vtable<T> {}
impl<T: ?Sized> hash::Hash for Vtable<T> {
#[inline(always)]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.0.hash(state)
}
}
impl<T: ?Sized> PartialOrd for Vtable<T> {
#[inline(always)]
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl<T: ?Sized> Ord for Vtable<T> {
#[inline(always)]
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.0.cmp(&other.0)
}
}
impl<T: ?Sized> fmt::Debug for Vtable<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.debug_struct("Vtable")
.field(unsafe { intrinsics::type_name::<T>() }, &self.0)
.finish()
}
}
impl<T: ?Sized + 'static> serde::ser::Serialize for Vtable<T> {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
<(uuid::Uuid, u64, usize) as serde::ser::Serialize>::serialize(
&(
build_id::get(),
unsafe { intrinsics::type_id::<T>() },
self.0,
),
serializer,
)
}
}
impl<'de, T: ?Sized + 'static> serde::de::Deserialize<'de> for Vtable<T> {
#[inline]
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
<(uuid::Uuid, u64, usize) as serde::de::Deserialize<'de>>::deserialize(deserializer)
.and_then(|(build, id, ptr)| {
let local = build_id::get();
if build == local {
if id == unsafe { intrinsics::type_id::<T>() } {
Ok(Self::new(ptr))
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference to wrong type ???:{}, expected {}:{}",
id,
unsafe { intrinsics::type_name::<T>() },
unsafe { intrinsics::type_id::<T>() }
)))
}
} else {
Err(serde::de::Error::custom(format_args!(
"relative reference came from a different binary {}, expected {}",
build, local
)))
}
})
}
}