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
//! Data structure to store a list of userspace applications.

use callback::AppId;
use core::marker::PhantomData;
use core::mem::size_of;
use core::ops::{Deref, DerefMut};
use core::ptr::{read_volatile, write_volatile, Unique};
use debug;
use process::{self, Error};

pub static mut CONTAINER_COUNTER: usize = 0;

pub struct Grant<T: Default> {
    grant_num: usize,
    ptr: PhantomData<T>,
}

pub struct AppliedGrant<T> {
    appid: usize,
    grant: *mut T,
    _phantom: PhantomData<T>,
}

/// This function contains the mapping of kernel "app" numbers to their
/// functions for getting a pointer to their grant region. Normal apps are
/// stored in a processes array, and finding apps is a matter of iterating that
/// array. Kernel "apps" currently (June 2018) have no such structure, so
/// finding them is a bit more ad-hoc.
pub unsafe fn kernel_grant_for<T>(app_id: usize) -> *mut T {
    match app_id {
        debug::APPID_IDX => debug::get_grant(),
        _ => panic!("lookup for invalid kernel grant {}", app_id),
    }
}

impl<T> AppliedGrant<T> {
    pub fn enter<F, R>(self, fun: F) -> R
    where
        F: FnOnce(&mut Owned<T>, &mut Allocator) -> R,
        R: Copy,
    {
        if AppId::is_kernel_idx(self.appid) {
            let mut allocator = Allocator {
                app: None,
                app_id: self.appid,
            };
            let mut root = unsafe { Owned::new(self.grant, self.appid) };
            fun(&mut root, &mut allocator)
        } else {
            let mut allocator = Allocator {
                app: unsafe { process::PROCS[self.appid].as_mut() },
                app_id: self.appid,
            };
            let mut root = unsafe { Owned::new(self.grant, self.appid) };
            fun(&mut root, &mut allocator)
        }
    }
}

pub struct Allocator<'a> {
    app: Option<&'a mut &'a mut process::Process<'a>>,
    app_id: usize,
}

pub struct Owned<T: ?Sized> {
    data: Unique<T>,
    app_id: usize,
}

impl<T: ?Sized> Owned<T> {
    unsafe fn new(data: *mut T, app_id: usize) -> Owned<T> {
        Owned {
            data: Unique::new_unchecked(data),
            app_id: app_id,
        }
    }

    pub fn appid(&self) -> AppId {
        AppId::new(self.app_id)
    }
}

impl<T: ?Sized> Drop for Owned<T> {
    fn drop(&mut self) {
        unsafe {
            let app_id = self.app_id;
            let data = self.data.as_ptr() as *mut u8;
            if AppId::is_kernel_idx(app_id) {
                /* kernel free is nop */
;
            } else {
                match process::PROCS[app_id] {
                    None => {}
                    Some(ref mut app) => {
                        app.free(data);
                    }
                }
            }
        }
    }
}

impl<T: ?Sized> Deref for Owned<T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { self.data.as_ref() }
    }
}

impl<T: ?Sized> DerefMut for Owned<T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { self.data.as_mut() }
    }
}

impl Allocator<'a> {
    pub fn alloc<T>(&mut self, data: T) -> Result<Owned<T>, Error> {
        unsafe {
            let app_id = self.app_id;
            match self.app.as_mut() {
                Some(app) => app
                    .alloc(size_of::<T>())
                    .map_or(Err(Error::OutOfMemory), |arr| {
                        let mut owned = Owned::new(arr.as_mut_ptr() as *mut T, app_id);
                        *owned = data;
                        Ok(owned)
                    }),
                None => {
                    if !AppId::is_kernel_idx(app_id) {
                        panic!("No app for allocator for {}", app_id);
                    }
                    panic!("Request to allocate in kernel grant");
                }
            }
        }
    }
}

pub struct Borrowed<'a, T: 'a + ?Sized> {
    data: &'a mut T,
    app_id: usize,
}

impl<T: 'a + ?Sized> Borrowed<'a, T> {
    pub fn new(data: &'a mut T, app_id: usize) -> Borrowed<T> {
        Borrowed {
            data: data,
            app_id: app_id,
        }
    }

    pub fn appid(&self) -> AppId {
        AppId::new(self.app_id)
    }
}

impl<T: 'a + ?Sized> Deref for Borrowed<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.data
    }
}

impl<T: 'a + ?Sized> DerefMut for Borrowed<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.data
    }
}

impl<T: Default> Grant<T> {
    pub unsafe fn create() -> Grant<T> {
        let ctr = read_volatile(&CONTAINER_COUNTER);
        write_volatile(&mut CONTAINER_COUNTER, ctr + 1);
        Grant {
            grant_num: ctr,
            ptr: PhantomData,
        }
    }

    pub fn grant(&self, appid: AppId) -> Option<AppliedGrant<T>> {
        unsafe {
            let app_id = appid.idx();
            if AppId::is_kernel(appid) {
                let cntr = kernel_grant_for::<T>(app_id);
                Some(AppliedGrant {
                    appid: app_id,
                    grant: cntr,
                    _phantom: PhantomData,
                })
            } else {
                match process::PROCS[app_id] {
                    Some(ref mut app) => {
                        let cntr = app.grant_for::<T>(self.grant_num);
                        if cntr.is_null() {
                            None
                        } else {
                            Some(AppliedGrant {
                                appid: app_id,
                                grant: cntr,
                                _phantom: PhantomData,
                            })
                        }
                    }
                    None => None,
                }
            }
        }
    }

    pub fn enter<F, R>(&self, appid: AppId, fun: F) -> Result<R, Error>
    where
        F: FnOnce(&mut Borrowed<T>, &mut Allocator) -> R,
        R: Copy,
    {
        unsafe {
            let app_id = appid.idx();
            if AppId::is_kernel(appid) {
                let root_ptr = kernel_grant_for::<T>(app_id);
                let mut root = Borrowed::new(&mut *root_ptr, app_id);
                let mut allocator = Allocator {
                    app: None,
                    app_id: app_id,
                };
                let res = fun(&mut root, &mut allocator);
                Ok(res)
            } else {
                match process::PROCS[app_id] {
                    Some(ref mut app) => app.grant_for_or_alloc::<T>(self.grant_num).map_or(
                        Err(Error::OutOfMemory),
                        move |root_ptr| {
                            let mut root = Borrowed::new(&mut *root_ptr, app_id);
                            let mut allocator = Allocator {
                                app: Some(app),
                                app_id: app_id,
                            };
                            let res = fun(&mut root, &mut allocator);
                            Ok(res)
                        },
                    ),
                    None => Err(Error::NoSuchApp),
                }
            }
        }
    }

    pub fn each<F>(&self, fun: F)
    where
        F: Fn(&mut Owned<T>),
    {
        unsafe {
            let itr = process::PROCS.iter_mut().filter_map(|p| p.as_mut());
            for (app_id, app) in itr.enumerate() {
                let root_ptr = app.grant_for::<T>(self.grant_num);
                if !root_ptr.is_null() {
                    let mut root = Owned::new(root_ptr, app_id);
                    fun(&mut root);
                }
            }
            // After iterating all possible normal apps, try the debug app.
            let root_ptr = kernel_grant_for::<T>(debug::APPID_IDX);
            if !root_ptr.is_null() {
                let mut root = Owned::new(root_ptr, debug::APPID_IDX);
                fun(&mut root);
            }
        }
    }

    pub fn iter(&self) -> Iter<T> {
        unsafe {
            Iter {
                grant: self,
                index: 0,
                len: process::PROCS.len(),
            }
        }
    }
}

pub struct Iter<'a, T: 'a + Default> {
    grant: &'a Grant<T>,
    index: usize,
    len: usize,
}

impl<T: Default> Iterator for Iter<'a, T> {
    type Item = AppliedGrant<T>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.index < self.len {
            let idx = self.index;
            self.index += 1;
            let res = self.grant.grant(AppId::new(idx));
            if res.is_some() {
                return res;
            }
        }
        // After running through all real apps, pass the debug app (idx 255) to
        // the grant iterator in case it has state the capsule needs to process.
        if self.index == self.len {
            self.index += 1;
            let res = self.grant.grant(AppId::new(debug::APPID_IDX));
            if res.is_some() {
                return res;
            }
        }
        None
    }
}