1 /*
2 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 #include "hardware/exception.h"
8 #include "hardware/platform_defs.h"
9 #include "hardware/structs/scb.h"
10 #include "hardware/sync.h"
11 #include "pico/assert.h"
12
13 #ifndef exception_is_compile_time_default
exception_is_compile_time_default(exception_handler_t handler)14 static bool exception_is_compile_time_default(exception_handler_t handler) {
15 extern char __default_isrs_start;
16 extern char __default_isrs_end;
17 return ((uintptr_t)handler) >= (uintptr_t)&__default_isrs_start &&
18 ((uintptr_t)handler) < (uintptr_t)&__default_isrs_end;
19 }
20 #endif
21
get_vtable(void)22 static inline exception_handler_t *get_vtable(void) {
23 return (exception_handler_t *) scb_hw->vtor;
24 }
25
set_raw_exception_handler_and_restore_interrupts(enum exception_number num,exception_handler_t handler,uint32_t save)26 static void set_raw_exception_handler_and_restore_interrupts(enum exception_number num, exception_handler_t handler, uint32_t save) {
27 // update vtable (vtable_handler may be same or updated depending on cases, but we do it anyway for compactness)
28 get_vtable()[16 + num] = handler;
29 __dmb();
30 restore_interrupts(save);
31 }
32
check_exception_param(__unused enum exception_number num)33 static inline void check_exception_param(__unused enum exception_number num) {
34 invalid_params_if(EXCEPTION, num < NMI_EXCEPTION || num >=0);
35 }
36
exception_get_vtable_handler(enum exception_number num)37 exception_handler_t exception_get_vtable_handler(enum exception_number num) {
38 check_exception_param(num);
39 return get_vtable()[16 + num];
40 }
41
exception_set_exclusive_handler(enum exception_number num,exception_handler_t handler)42 exception_handler_t exception_set_exclusive_handler(enum exception_number num, exception_handler_t handler) {
43 check_exception_param(num);
44 #if !PICO_NO_RAM_VECTOR_TABLE
45 uint32_t save = save_and_disable_interrupts();
46 exception_handler_t current = exception_get_vtable_handler(num);
47 hard_assert(handler == current || exception_is_compile_time_default(current));
48 set_raw_exception_handler_and_restore_interrupts(num, handler, save);
49 #else
50 panic_unsupported();
51 #endif
52 return current;
53 }
54
exception_restore_handler(enum exception_number num,exception_handler_t original_handler)55 void exception_restore_handler(enum exception_number num, exception_handler_t original_handler) {
56 hard_assert(exception_is_compile_time_default(original_handler));
57 #if !PICO_NO_RAM_VECTOR_TABLE
58 uint32_t save = save_and_disable_interrupts();
59 set_raw_exception_handler_and_restore_interrupts(num, original_handler, save);
60 #else
61 panic_unsupported();
62 #endif
63 }