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
use crate::VirtAddr;
use alloc::{string::String, vec::Vec};
use core::{
fmt::{Debug, Formatter},
marker::PhantomData,
ops::{Deref, DerefMut},
};
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct UserPtr<T, P: Policy>(*mut T, PhantomData<P>);
pub trait Policy {}
pub trait Read: Policy {}
pub trait Write: Policy {}
pub struct In;
pub struct Out;
pub struct InOut;
impl Policy for In {}
impl Policy for Out {}
impl Policy for InOut {}
impl Read for In {}
impl Write for Out {}
impl Read for InOut {}
impl Write for InOut {}
pub type UserInPtr<T> = UserPtr<T, In>;
pub type UserOutPtr<T> = UserPtr<T, Out>;
pub type UserInOutPtr<T> = UserPtr<T, InOut>;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Error {
InvalidUtf8,
InvalidPointer,
BufferTooSmall,
InvalidLength,
InvalidVectorAddress,
}
type Result<T> = core::result::Result<T, Error>;
impl<T, P: Policy> Debug for UserPtr<T, P> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?}", self.0)
}
}
unsafe impl<T, P: Policy> Send for UserPtr<T, P> {}
unsafe impl<T, P: Policy> Sync for UserPtr<T, P> {}
impl<T, P: Policy> From<usize> for UserPtr<T, P> {
fn from(ptr: usize) -> Self {
UserPtr(ptr as _, PhantomData)
}
}
impl<T, P: Policy> UserPtr<T, P> {
pub fn from_addr_size(addr: usize, size: usize) -> Result<Self> {
if size >= core::mem::size_of::<T>() {
Ok(Self::from(addr))
} else {
Err(Error::BufferTooSmall)
}
}
pub fn is_null(&self) -> bool {
self.0.is_null()
}
pub fn add(&self, count: usize) -> Self {
Self(unsafe { self.0.add(count) }, PhantomData)
}
pub fn as_addr(&self) -> VirtAddr {
self.0 as _
}
pub fn check(&self) -> Result<()> {
if !self.0.is_null() && (self.0 as usize) % core::mem::align_of::<T>() == 0 {
Ok(())
} else {
Err(Error::InvalidPointer)
}
}
}
impl<T, P: Read> UserPtr<T, P> {
#[allow(clippy::should_implement_trait)]
pub fn as_ref(&self) -> &'static T {
unsafe { &*self.0 }
}
pub fn read(&self) -> Result<T> {
self.check()?;
Ok(unsafe { self.0.read() })
}
pub fn read_if_not_null(&self) -> Result<Option<T>> {
if !self.0.is_null() {
Ok(Some(self.read()?))
} else {
Ok(None)
}
}
pub fn as_slice(&self, len: usize) -> Result<&'static [T]> {
if len == 0 {
Ok(&[])
} else {
self.check()?;
Ok(unsafe { core::slice::from_raw_parts(self.0, len) })
}
}
#[allow(clippy::uninit_vec)]
pub fn read_array(&self, len: usize) -> Result<Vec<T>> {
if len == 0 {
Ok(Vec::default())
} else {
self.check()?;
let mut ret = Vec::<T>::with_capacity(len);
unsafe {
ret.set_len(len);
ret.as_mut_ptr().copy_from_nonoverlapping(self.0, len);
}
Ok(ret)
}
}
}
impl<P: Read> UserPtr<u8, P> {
pub fn as_str(&self, len: usize) -> Result<&'static str> {
core::str::from_utf8(self.as_slice(len)?).map_err(|_| Error::InvalidUtf8)
}
pub fn as_c_str(&self) -> Result<&'static str> {
self.as_str(unsafe { (0usize..).find(|&i| *self.0.add(i) == 0).unwrap() })
}
}
impl<P: 'static + Read> UserPtr<UserPtr<u8, P>, P> {
pub fn read_cstring_array(&self) -> Result<Vec<String>> {
self.check()?;
let mut result = Vec::new();
let mut pptr = self.0;
loop {
let sptr = unsafe { pptr.read() };
if sptr.is_null() {
break;
}
result.push(sptr.as_c_str()?.into());
pptr = unsafe { pptr.add(1) };
}
Ok(result)
}
}
impl<T, P: Write> UserPtr<T, P> {
pub fn write(&mut self, value: T) -> Result<()> {
self.check()?;
unsafe { self.0.write(value) };
Ok(())
}
pub fn write_if_not_null(&mut self, value: T) -> Result<()> {
if !self.0.is_null() {
self.write(value)
} else {
Ok(())
}
}
pub fn write_array(&mut self, values: &[T]) -> Result<()> {
if !values.is_empty() {
self.check()?;
unsafe {
self.0
.copy_from_nonoverlapping(values.as_ptr(), values.len())
};
}
Ok(())
}
}
impl<P: Write> UserPtr<u8, P> {
pub fn write_cstring(&mut self, s: &str) -> Result<()> {
let bytes = s.as_bytes();
self.write_array(bytes)?;
unsafe { self.0.add(bytes.len()).write(0) };
Ok(())
}
}
#[repr(C)]
pub struct IoVec<P: Policy> {
ptr: UserPtr<u8, P>,
len: usize,
}
impl<P: Policy> core::fmt::Debug for IoVec<P> {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
write!(f, "IoVec ptr:{:?} len :{:?}", self.ptr.0, self.len)
}
}
pub type IoVecIn = IoVec<In>;
pub type IoVecOut = IoVec<Out>;
pub type IoVecsOut = IoVecs<Out>;
pub struct IoVecs<P: 'static + Policy> {
vec: Vec<IoVec<P>>,
}
impl<P: Policy> Debug for IoVecs<P> {
fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
write!(f, "IoVec len :{:?}", self.vec.len())
}
}
impl IoVecs<Out> {
pub fn new(iov_ptr: UserInPtr<IoVec<Out>>, iov_count: usize) -> IoVecs<Out> {
iov_ptr.read_iovecs(iov_count).unwrap()
}
}
impl<P: Policy> UserInPtr<IoVec<P>> {
pub fn read_iovecs(&self, count: usize) -> Result<IoVecs<P>> {
if self.0.is_null() {
return Err(Error::InvalidPointer);
}
let vec = self.read_array(count)?;
let mut total_count = 0usize;
for io_vec in vec.iter() {
let (result, overflow) = total_count.overflowing_add(io_vec.len());
if overflow {
return Err(Error::InvalidLength);
}
total_count = result;
}
Ok(IoVecs { vec })
}
}
impl<P: Policy> IoVecs<P> {
pub fn total_len(&self) -> usize {
self.vec.iter().map(|vec| vec.len).sum()
}
}
impl<P: Read> IoVecs<P> {
pub fn read_to_vec(&self) -> Result<Vec<u8>> {
let mut buf = Vec::new();
for vec in self.vec.iter() {
buf.extend_from_slice(vec.ptr.as_slice(vec.len)?);
}
Ok(buf)
}
}
impl<P: Write> IoVecs<P> {
pub fn write_from_buf(&mut self, mut buf: &[u8]) -> Result<usize> {
let buf_len = buf.len();
for vec in self.vec.iter_mut() {
let copy_len = vec.len.min(buf.len());
if copy_len == 0 {
continue;
}
vec.ptr.write_array(&buf[..copy_len])?;
buf = &buf[copy_len..];
}
Ok(buf_len - buf.len())
}
}
impl<P: Policy> Deref for IoVecs<P> {
type Target = [IoVec<P>];
fn deref(&self) -> &Self::Target {
self.vec.as_slice()
}
}
impl<P: Write> DerefMut for IoVecs<P> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.vec.as_mut_slice()
}
}
impl<P: Policy> IoVec<P> {
pub fn is_null(&self) -> bool {
self.ptr.is_null()
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn check(&self) -> Result<()> {
self.ptr.check()
}
pub fn as_slice(&self) -> Result<&[u8]> {
self.as_mut_slice().map(|s| &*s)
}
pub fn as_mut_slice(&self) -> Result<&mut [u8]> {
if !self.ptr.is_null() {
Ok(unsafe { core::slice::from_raw_parts_mut(self.ptr.0, self.len) })
} else {
Err(Error::InvalidVectorAddress)
}
}
}