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
use std::alloc::{handle_alloc_error, Layout};
mod r#box;
mod cow;
mod option;
mod primitive;
mod slice;
mod string;
mod vec;
pub(crate) fn alloc<T>(layout: Layout) -> *mut T {
// SAFETY: nothing that can go wrong here, the memory
// is allocated by the C library and returned straight
// away
let p = unsafe { libc::aligned_alloc(layout.align(), layout.size()).cast::<T>() };
if p.is_null() {
handle_alloc_error(layout);
}
p
}
#[allow(clippy::undocumented_unsafe_blocks)]
#[cfg(test)]
pub(crate) mod tests {
use crate::foreign::*;
use std::ffi::{c_char, c_void, CStr, CString};
use std::marker::PhantomData;
use std::mem;
use std::ptr;
// Note that neither `PointerWithLifetime` nor `PrimitiveWithLifetime`
// implement `FromForeign`. Doing so would let the caller choose the
// lifetime (see test_pointer_dangling_but_unsafe below).
pub struct PointerWithLifetime<'s>(*const c_char, PhantomData<&'s CStr>);
impl FreeForeign for PointerWithLifetime<'_> {
type Foreign = *const c_char;
unsafe fn free_foreign(p: *mut Self::Foreign) {
libc::free(p.cast::<c_void>());
}
}
impl<'s> PointerWithLifetime<'s> {
fn new(bp: &BorrowedPointer<CStr, &'s CStr>) -> Self {
PointerWithLifetime(bp.as_ptr(), PhantomData)
}
fn as_ptr(&self) -> *const *const c_char {
&self.0
}
}
impl<'s> BorrowForeign for PointerWithLifetime<'s> {
type Storage<'a>
= &'a Self
where
Self: 'a;
fn borrow_foreign(&self) -> BorrowedPointer<Self, Self::Storage<'_>> {
// SAFETY: no cells in sight, therefore the pointer in the
// shared reference cannot change as long as the reference is alive
unsafe { BorrowedPointer::new_borrowed(self, |raw| ptr::addr_of!((*raw).0)) }
}
}
impl<'s> BorrowForeignMut for PointerWithLifetime<'s> {
type Storage<'a>
= BorrowedStorage<'a, Self>
where
Self: 'a;
fn borrow_foreign_mut(&mut self) -> BorrowedMutPointer<Self, Self::Storage<'_>> {
// SAFETY: this type's Foreign is the pointer it holds, so
// the C representation is the address of field 0.
unsafe { BorrowedMutPointer::new_borrowed(self, |raw| ptr::addr_of_mut!((*raw).0)) }
}
}
/// A primitive type that borrows, whose C representation is itself.
/// Unlike [`PointerWithLifetime`], whose `Foreign` is a `*const c_char`,
/// this satisfies the `FreeForeign<Foreign = T>` so it can be converted
/// even in a slice, array or `Vec`.
#[derive(Copy, Clone)]
#[repr(transparent)]
pub(crate) struct PrimitiveWithLifetime<'s>(pub(crate) u8, PhantomData<&'s u8>);
impl<'s> PrimitiveWithLifetime<'s> {
/// Ties `'s` to a real borrow. Constructing one from a copied value
/// would leave the lifetime unconstrained, inference would settle on
/// `'static`, and any test using it would prove nothing.
pub(crate) fn new(r: &'s u8) -> Self {
PrimitiveWithLifetime(*r, PhantomData)
}
}
impl<'s> FreeForeign for PrimitiveWithLifetime<'s> {
type Foreign = PrimitiveWithLifetime<'s>;
unsafe fn free_foreign(p: *mut Self::Foreign) {
libc::free(p.cast::<c_void>());
}
}
impl<'s> CloneToForeign for PrimitiveWithLifetime<'s> {
fn clone_to_foreign(&self) -> OwnedPointer<Self> {
// SAFETY: copying into a freshly allocated block
unsafe {
let p = libc::malloc(mem::size_of::<Self>()).cast::<Self::Foreign>();
assert!(!p.is_null());
*p = *self;
OwnedPointer::new(p)
}
}
}
unsafe impl<'s> FixedAlloc for PrimitiveWithLifetime<'s> {
unsafe fn clone_into_foreign(dest: *mut Self::Foreign, src: &Self) {
ptr::write(dest, *src);
}
}
impl<'s> BorrowForeignMut for PrimitiveWithLifetime<'s> {
// Storage<'a>, not Storage<'s>: the storage records the *borrow*.
// Naming 's here would leave 'a unconstrained, so the result would
// not borrow self at all and two of them could exist at once.
type Storage<'a>
= BorrowedStorage<'a, Self>
where
Self: 'a;
fn borrow_foreign_mut(&mut self) -> BorrowedMutPointer<Self, Self::Storage<'_>> {
// SAFETY: the C representation of this type is itself,
// since it is #[repr(transparent)]
unsafe { BorrowedMutPointer::new_borrowed(self, |raw| raw) }
}
}
#[test]
fn test_borrow_struct() {
let s = CString::new("hello world").unwrap();
let mut st = PointerWithLifetime::new(&s.borrow_foreign());
// does not compile:
// drop(s);
let b = st.borrow_foreign();
let p = st.as_ptr();
assert_eq!(b.as_ptr(), p);
assert_eq!(st.borrow_foreign_mut().as_ptr(), p);
// does not compile:
// assert_eq!(b.as_ptr(), p);
}
#[test]
fn test_borrow_box() {
let s = CString::new("hello world").unwrap();
let st = PointerWithLifetime::new(&s.borrow_foreign());
let mut st = Box::new(st);
// does not compile:
// drop(s);
let b = st.borrow_foreign();
let p = st.as_ptr();
assert_eq!(b.as_ptr(), p);
assert_eq!(st.borrow_foreign_mut().as_ptr(), p);
// does not compile:
// assert_eq!(b.as_ptr(), p);
}
#[test]
fn test_pointer_dangling_but_unsafe() {
let _owned: OwnedPointer<PointerWithLifetime<'static>> = {
let s = CString::new("hello").unwrap();
unsafe {
let cell =
libc::malloc(std::mem::size_of::<*const c_char>()).cast::<*const c_char>();
*cell = PointerWithLifetime::new(&s.borrow_foreign()).0;
OwnedPointer::new(cell)
}
// `s` is dropped here. The pointer stored in `owned`
// is dangling, but...
};
// ... it cannot be used here from safe code: this does not compile.
// let s = owned.into_native();
}
#[test]
fn test_borrow_struct_via_box() {
let s = CString::new("hello world").unwrap();
let st = PointerWithLifetime::new(&s.borrow_foreign());
let st = Box::new(st);
// does not compile:
// drop(s);
let p = st.as_ptr();
assert_eq!(st.into_foreign().as_ptr(), p);
}
}