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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use {
    super::*, crate::ipc::*, crate::object::*, alloc::sync::Arc, alloc::vec, alloc::vec::Vec,
    core::mem::size_of, futures::channel::oneshot, kernel_hal::UserContext, spin::Mutex,
};

/// Kernel-owned exception channel endpoint.
pub struct Exceptionate {
    type_: ExceptionChannelType,
    inner: Mutex<ExceptionateInner>,
}

enum ExceptionateInner {
    Init,
    Bind {
        channel: Arc<Channel>,
        rights: Rights,
    },
    Shutdown,
}

impl Exceptionate {
    /// Create an `Exceptionate`.
    pub(super) fn new(type_: ExceptionChannelType) -> Arc<Self> {
        Arc::new(Exceptionate {
            type_,
            inner: Mutex::new(ExceptionateInner::Init),
        })
    }

    /// Shutdown the exceptionate.
    pub(super) fn shutdown(&self) {
        *self.inner.lock() = ExceptionateInner::Shutdown;
    }

    /// Create an exception channel endpoint for user.
    pub fn create_channel(&self, rights: Rights) -> ZxResult<Arc<Channel>> {
        let mut inner = self.inner.lock();
        match &*inner {
            ExceptionateInner::Shutdown => return Err(ZxError::BAD_STATE),
            ExceptionateInner::Bind { channel, .. } if channel.peer().is_ok() => {
                // already has a valid channel
                return Err(ZxError::ALREADY_BOUND);
            }
            _ => {}
        }
        let (channel, user_channel) = Channel::create();
        *inner = ExceptionateInner::Bind { channel, rights };
        Ok(user_channel)
    }

    /// Whether the user-owned channel endpoint is alive.
    pub(super) fn has_channel(&self) -> bool {
        let inner = self.inner.lock();
        matches!(&*inner, ExceptionateInner::Bind { channel, .. } if channel.peer().is_ok())
    }

    /// Send exception to the user-owned endpoint.
    pub(super) fn send_exception(
        &self,
        exception: &Arc<Exception>,
    ) -> ZxResult<oneshot::Receiver<()>> {
        debug!(
            "Exception: {:?} ,try send to {:?}",
            exception.type_, self.type_
        );
        let mut inner = self.inner.lock();
        let (channel, rights) = match &*inner {
            ExceptionateInner::Bind { channel, rights } => (channel, *rights),
            _ => return Err(ZxError::NEXT),
        };
        let info = ExceptionInfo {
            pid: exception.thread.proc().id(),
            tid: exception.thread.id(),
            type_: exception.type_,
            padding: Default::default(),
        };
        let (object, closed) = ExceptionObject::create(exception.clone(), rights);
        let msg = MessagePacket {
            data: info.pack(),
            handles: vec![Handle::new(object, Rights::DEFAULT_EXCEPTION)],
        };
        channel.write(msg).map_err(|err| {
            if err == ZxError::PEER_CLOSED {
                *inner = ExceptionateInner::Init;
                return ZxError::NEXT;
            }
            err
        })?;
        Ok(closed)
    }
}

#[repr(C)]
#[derive(Debug)]
struct ExceptionInfo {
    pid: KoID,
    tid: KoID,
    type_: ExceptionType,
    padding: u32,
}

impl ExceptionInfo {
    #[allow(unsafe_code)]
    fn pack(&self) -> Vec<u8> {
        let buf: [u8; size_of::<ExceptionInfo>()] = unsafe { core::mem::transmute_copy(self) };
        Vec::from(buf)
    }
}

/// The common header of all exception reports.
#[repr(C)]
#[derive(Debug, Clone)]
struct ExceptionHeader {
    /// The actual size, in bytes, of the report (including this field).
    size: u32,
    /// The type of the exception.
    type_: ExceptionType,
}

/// Data associated with an exception (siginfo in linux parlance)
/// Things available from regsets (e.g., pc) are not included here.
/// For an example list of things one might add, see linux siginfo.
#[cfg(target_arch = "x86_64")]
#[repr(C)]
#[derive(Debug, Default, Clone)]
struct ExceptionContext {
    vector: u64,
    err_code: u64,
    cr2: u64,
}

/// Data associated with an exception (siginfo in linux parlance)
/// Things available from regsets (e.g., pc) are not included here.
/// For an example list of things one might add, see linux siginfo.
#[cfg(target_arch = "aarch64")]
#[repr(C)]
#[derive(Debug, Default, Clone)]
struct ExceptionContext {
    esr: u32,
    padding1: u32,
    far: u64,
    padding2: u64,
}

impl ExceptionContext {
    #[cfg(target_arch = "x86_64")]
    fn from_user_context(cx: &UserContext) -> Self {
        ExceptionContext {
            vector: cx.trap_num as u64,
            err_code: cx.error_code as u64,
            cr2: kernel_hal::fetch_fault_vaddr() as u64,
        }
    }
    #[cfg(target_arch = "aarch64")]
    fn from_user_context(_cx: &UserContext) -> Self {
        unimplemented!()
    }
}

/// Data reported to an exception handler for most exceptions.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct ExceptionReport {
    /// The common header of all exception reports.
    header: ExceptionHeader,
    /// Exception-specific data.
    context: ExceptionContext,
}

impl ExceptionReport {
    fn new(type_: ExceptionType, cx: Option<&UserContext>) -> Self {
        ExceptionReport {
            header: ExceptionHeader {
                type_,
                size: core::mem::size_of::<ExceptionReport>() as u32,
            },
            context: cx
                .map(ExceptionContext::from_user_context)
                .unwrap_or_default(),
        }
    }
}

/// Type of exception
#[allow(missing_docs)]
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ExceptionType {
    General = 0x008,
    FatalPageFault = 0x108,
    UndefinedInstruction = 0x208,
    SoftwareBreakpoint = 0x308,
    HardwareBreakpoint = 0x408,
    UnalignedAccess = 0x508,
    // exceptions generated by kernel instead of the hardware
    Synth = 0x8000,
    ThreadStarting = 0x8008,
    ThreadExiting = 0x8108,
    PolicyError = 0x8208,
    ProcessStarting = 0x8308,
}

impl ExceptionType {
    /// Is the exception type generated by kernel instead of the hardware.
    pub fn is_synth(self) -> bool {
        (self as u32) & (ExceptionType::Synth as u32) != 0
    }
}

/// Type of the exception channel
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(super) enum ExceptionChannelType {
    None = 0,
    Debugger = 1,
    Thread = 2,
    Process = 3,
    Job = 4,
    JobDebugger = 5,
}

/// The exception object received from the exception channel.
///
/// This will be transmitted to registered exception handlers in userspace
/// and provides them with exception state and control functionality.
/// We do not send exception directly since it's hard to figure out
/// when will the handle close.
pub struct ExceptionObject {
    base: KObjectBase,
    exception: Arc<Exception>,
    /// Task rights copied from `Exceptionate`.
    rights: Rights,
    close_signal: Option<oneshot::Sender<()>>,
}

impl_kobject!(ExceptionObject);

impl ExceptionObject {
    /// Create an kernel object of `Exception`.
    ///
    /// Return the object and a `Receiver` of the object dropped event.
    fn create(exception: Arc<Exception>, rights: Rights) -> (Arc<Self>, oneshot::Receiver<()>) {
        let (sender, receiver) = oneshot::channel();
        let object = Arc::new(ExceptionObject {
            base: KObjectBase::new(),
            exception,
            rights,
            close_signal: Some(sender),
        });
        (object, receiver)
    }

    /// Create a handle for the exception's thread.
    pub fn get_thread_handle(&self) -> Handle {
        Handle {
            object: self.exception.thread.clone(),
            rights: self.rights & Rights::DEFAULT_THREAD,
        }
    }

    /// Create a handle for the exception's process.
    pub fn get_process_handle(&self) -> ZxResult<Handle> {
        if self.exception.current_channel_type() == ExceptionChannelType::Thread {
            return Err(ZxError::ACCESS_DENIED);
        }
        Ok(Handle {
            object: self.exception.thread.proc().clone(),
            rights: self.rights & Rights::DEFAULT_PROCESS,
        })
    }

    /// Get whether closing the exception handle will
    /// finish exception processing and resume the underlying thread.
    pub fn state(&self) -> u32 {
        self.exception.inner.lock().handled as u32
    }

    /// Set whether closing the exception handle will
    /// finish exception processing and resume the underlying thread.
    pub fn set_state(&self, state: u32) -> ZxResult {
        if state > 1 {
            return Err(ZxError::INVALID_ARGS);
        }
        self.exception.inner.lock().handled = state == 1;
        Ok(())
    }

    /// Get whether the debugger gets a 'second chance' at handling the exception
    /// if the process-level handler fails to do so.
    pub fn strategy(&self) -> u32 {
        self.exception.inner.lock().second_chance as u32
    }

    /// Set whether the debugger gets a 'second chance' at handling the exception
    /// if the process-level handler fails to do so.
    pub fn set_strategy(&self, strategy: u32) -> ZxResult {
        if strategy > 1 {
            return Err(ZxError::INVALID_ARGS);
        }
        let mut inner = self.exception.inner.lock();
        match inner.current_channel_type {
            ExceptionChannelType::Debugger | ExceptionChannelType::JobDebugger => {
                inner.second_chance = strategy == 1;
                Ok(())
            }
            _ => Err(ZxError::BAD_STATE),
        }
    }
}

impl Drop for ExceptionObject {
    fn drop(&mut self) {
        self.close_signal.take().unwrap().send(()).ok();
    }
}

/// An Exception represents a single currently-active exception.
pub(super) struct Exception {
    thread: Arc<Thread>,
    type_: ExceptionType,
    report: ExceptionReport,
    inner: Mutex<ExceptionInner>,
}

struct ExceptionInner {
    current_channel_type: ExceptionChannelType,
    handled: bool,
    second_chance: bool,
}

impl Exception {
    /// Create an `Exception`.
    pub fn new(thread: &Arc<Thread>, type_: ExceptionType, cx: Option<&UserContext>) -> Arc<Self> {
        Arc::new(Exception {
            thread: thread.clone(),
            type_,
            report: ExceptionReport::new(type_, cx),
            inner: Mutex::new(ExceptionInner {
                current_channel_type: ExceptionChannelType::None,
                handled: false,
                second_chance: false,
            }),
        })
    }

    /// Handle the exception.
    ///
    /// Note that it's possible that this may returns before exception was send to any exception channel.
    /// This happens only when the thread is killed before we send the exception.
    pub async fn handle(self: &Arc<Self>) {
        let result = match self.type_ {
            ExceptionType::ProcessStarting => {
                self.handle_with(JobDebuggerIterator::new(self.thread.proc().job()), true)
                    .await
            }
            ExceptionType::ThreadStarting | ExceptionType::ThreadExiting => {
                self.handle_with(Some(self.thread.proc().debug_exceptionate()), false)
                    .await
            }
            _ => {
                self.handle_with(ExceptionateIterator::new(self), false)
                    .await
            }
        };
        if result == Err(ZxError::NEXT) && !self.type_.is_synth() {
            // Nobody handled the exception, kill myself
            self.thread.proc().exit(TASK_RETCODE_SYSCALL_KILL);
        }
    }

    /// Handle the exception with a customized iterator.
    ///
    /// If `first_only` is true, this will only send exception to the first one that received the exception
    /// even when the exception is not handled.
    async fn handle_with(
        self: &Arc<Self>,
        exceptionates: impl IntoIterator<Item = Arc<Exceptionate>>,
        first_only: bool,
    ) -> ZxResult {
        for exceptionate in exceptionates.into_iter() {
            let closed = match exceptionate.send_exception(self) {
                // This channel is not available now!
                Err(ZxError::NEXT) => continue,
                res => res?,
            };
            self.inner.lock().current_channel_type = exceptionate.type_;
            // If this error, the sender is dropped, and the handle should also be closed.
            closed.await.ok();
            let handled = {
                let mut inner = self.inner.lock();
                inner.current_channel_type = ExceptionChannelType::None;
                inner.handled
            };
            if handled | first_only {
                return Ok(());
            }
        }
        Err(ZxError::NEXT)
    }

    /// Get the exception's channel type.
    pub fn current_channel_type(&self) -> ExceptionChannelType {
        self.inner.lock().current_channel_type
    }

    /// Get a report of the exception.
    pub fn report(&self) -> ExceptionReport {
        self.report.clone()
    }
}

/// An iterator used to find Exceptionates used while handling the exception
/// This is only used to handle normal exceptions (Architectural & Policy)
/// We can use rust generator instead here but that is somehow not stable
/// Exception handlers are tried in the following order:
/// - process debugger
/// - thread
/// - process
/// - process debugger (in dealing with a second-chance exception)
/// - job (first owning job, then its parent job, and so on up to root job)
struct ExceptionateIterator<'a> {
    exception: &'a Exception,
    state: ExceptionateIteratorState,
}

/// The state used in ExceptionateIterator.
/// Name of options is what to consider next
enum ExceptionateIteratorState {
    Debug(bool),
    Thread,
    Process,
    Job(Arc<Job>),
    Finished,
}

impl<'a> ExceptionateIterator<'a> {
    fn new(exception: &'a Exception) -> Self {
        ExceptionateIterator {
            exception,
            state: ExceptionateIteratorState::Debug(false),
        }
    }
}

impl<'a> Iterator for ExceptionateIterator<'a> {
    type Item = Arc<Exceptionate>;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match &self.state {
                ExceptionateIteratorState::Debug(second_chance) => {
                    if *second_chance && !self.exception.inner.lock().second_chance {
                        self.state =
                            ExceptionateIteratorState::Job(self.exception.thread.proc().job());
                        continue;
                    }
                    let proc = self.exception.thread.proc();
                    self.state = if *second_chance {
                        ExceptionateIteratorState::Job(self.exception.thread.proc().job())
                    } else {
                        ExceptionateIteratorState::Thread
                    };
                    return Some(proc.debug_exceptionate());
                }
                ExceptionateIteratorState::Thread => {
                    self.state = ExceptionateIteratorState::Process;
                    return Some(self.exception.thread.exceptionate());
                }
                ExceptionateIteratorState::Process => {
                    let proc = self.exception.thread.proc();
                    self.state = ExceptionateIteratorState::Debug(true);
                    return Some(proc.exceptionate());
                }
                ExceptionateIteratorState::Job(job) => {
                    let parent = job.parent();
                    let result = job.exceptionate();
                    self.state = parent.map_or(
                        ExceptionateIteratorState::Finished,
                        ExceptionateIteratorState::Job,
                    );
                    return Some(result);
                }
                ExceptionateIteratorState::Finished => return None,
            }
        }
    }
}

/// This is only used by ProcessStarting exceptions
struct JobDebuggerIterator {
    job: Option<Arc<Job>>,
}

impl JobDebuggerIterator {
    /// Create a new JobDebuggerIterator
    fn new(job: Arc<Job>) -> Self {
        JobDebuggerIterator { job: Some(job) }
    }
}

impl Iterator for JobDebuggerIterator {
    type Item = Arc<Exceptionate>;
    fn next(&mut self) -> Option<Self::Item> {
        let result = self.job.as_ref().map(|job| job.debug_exceptionate());
        self.job = self.job.as_ref().and_then(|job| job.parent());
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn exceptionate_iterator() {
        let parent_job = Job::root();
        let job = parent_job.create_child().unwrap();
        let proc = Process::create(&job, "proc").unwrap();
        let thread = Thread::create(&proc, "thread").unwrap();

        let exception = Exception::new(&thread, ExceptionType::Synth, None);
        let actual: Vec<_> = ExceptionateIterator::new(&exception).collect();
        let expected = [
            proc.debug_exceptionate(),
            thread.exceptionate(),
            proc.exceptionate(),
            job.exceptionate(),
            parent_job.exceptionate(),
        ];
        assert_eq!(actual.len(), expected.len());
        for (actual, expected) in actual.iter().zip(expected.iter()) {
            assert!(Arc::ptr_eq(&actual, expected));
        }
    }

    #[test]
    fn exceptionate_iterator_second_chance() {
        let parent_job = Job::root();
        let job = parent_job.create_child().unwrap();
        let proc = Process::create(&job, "proc").unwrap();
        let thread = Thread::create(&proc, "thread").unwrap();

        let exception = Exception::new(&thread, ExceptionType::Synth, None);
        exception.inner.lock().second_chance = true;
        let actual: Vec<_> = ExceptionateIterator::new(&exception).collect();
        let expected = [
            proc.debug_exceptionate(),
            thread.exceptionate(),
            proc.exceptionate(),
            proc.debug_exceptionate(),
            job.exceptionate(),
            parent_job.exceptionate(),
        ];
        assert_eq!(actual.len(), expected.len());
        for (actual, expected) in actual.iter().zip(expected.iter()) {
            assert!(Arc::ptr_eq(&actual, expected));
        }
    }

    #[test]
    fn job_debugger_iterator() {
        let parent_job = Job::root();
        let job = parent_job.create_child().unwrap();
        let child_job = job.create_child().unwrap();
        let _grandson_job = child_job.create_child().unwrap();

        let actual: Vec<_> = JobDebuggerIterator::new(child_job.clone()).collect();
        let expected = [
            child_job.debug_exceptionate(),
            job.debug_exceptionate(),
            parent_job.debug_exceptionate(),
        ];
        assert_eq!(actual.len(), expected.len());
        for (actual, expected) in actual.iter().zip(expected.iter()) {
            assert!(Arc::ptr_eq(&actual, expected));
        }
    }

    #[async_std::test]
    async fn exception_handling() {
        let parent_job = Job::root();
        let job = parent_job.create_child().unwrap();
        let proc = Process::create(&job, "proc").unwrap();
        let thread = Thread::create(&proc, "thread").unwrap();

        let exception = Exception::new(&thread, ExceptionType::Synth, None);

        // This is used to verify that exceptions are handled in a specific order
        let handled_order = Arc::new(Mutex::new(Vec::<usize>::new()));

        let create_handler = |exceptionate: &Arc<Exceptionate>,
                              should_receive: bool,
                              should_handle: bool,
                              order: usize| {
            let channel = exceptionate
                .create_channel(Rights::DEFAULT_THREAD | Rights::DEFAULT_PROCESS)
                .unwrap();
            let handled_order = handled_order.clone();

            async_std::task::spawn(async move {
                // wait for the channel is ready
                let channel_object: Arc<dyn KernelObject> = channel.clone();
                channel_object
                    .wait_signal(Signal::READABLE | Signal::PEER_CLOSED)
                    .await;

                if !should_receive {
                    // channel should be closed without message
                    assert_eq!(channel.read().err(), Some(ZxError::PEER_CLOSED));
                    return;
                }

                // we should get the exception here
                let data = channel.read().unwrap();
                assert_eq!(data.handles.len(), 1);
                let exception = data.handles[0]
                    .object
                    .clone()
                    .downcast_arc::<ExceptionObject>()
                    .unwrap();
                if should_handle {
                    exception.set_state(1).unwrap();
                }
                // record the order of the handler used
                handled_order.lock().push(order);
            })
        };

        // proc debug should get the exception first
        create_handler(&proc.debug_exceptionate(), true, false, 0);
        // thread should get the exception next
        create_handler(&thread.exceptionate(), true, false, 1);
        // here we omit proc to test that we can handle the case that there is none handler
        // job should get the exception and handle it next
        create_handler(&job.exceptionate(), true, true, 3);
        // since exception is handled we should not get it from parent job
        create_handler(&parent_job.exceptionate(), false, false, 4);

        exception.handle().await;

        // terminate handlers by shutdown the related exceptionates
        thread.exceptionate().shutdown();
        proc.debug_exceptionate().shutdown();
        job.exceptionate().shutdown();
        parent_job.exceptionate().shutdown();

        // test for the order: proc debug -> thread -> job
        assert_eq!(handled_order.lock().clone(), vec![0, 1, 3]);
    }
}