1 /*
2  * Copyright (c) Copyright (c) 2020 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/printk.h>
9 #include <ksched.h>
10 
11 static volatile int expected_reason = -1;
12 
13 void z_thread_essential_clear(struct k_thread *thread);
14 
k_sys_fatal_error_handler(unsigned int reason,const struct arch_esf * pEsf)15 void k_sys_fatal_error_handler(unsigned int reason, const struct arch_esf *pEsf)
16 {
17 	printk("Caught system error -- reason %d\n", reason);
18 
19 	if (expected_reason == -1) {
20 		printk("Was not expecting a crash\n");
21 		printk("PROJECT EXECUTION FAILED\n");
22 		k_fatal_halt(reason);
23 	}
24 
25 	if (reason != expected_reason) {
26 		printk("Wrong crash type got %d expected %d\n", reason,
27 		       expected_reason);
28 		printk("PROJECT EXECUTION FAILED\n");
29 		k_fatal_halt(reason);
30 	}
31 
32 	printk("Fatal error expected as part of test case.\n");
33 
34 	expected_reason = -1;
35 }
36 
37 /**
38  * @brief This test case verifies when fatal error
39  *        log message can be captured.
40  * @details
41  * Test Objective:
42  * - When the fatal error is triggered, if the debugging message function
43  *   is turned on, the system can capture the log information.
44  *
45  * Prerequisite Conditions:
46  * - N/A
47  *
48  * Input Specifications:
49  * - N/A
50  *
51  * Test Procedure:
52  * -# Writing a function deliberately triggers a koops exception.
53  * -# When the log module is enabled, it will log some information
54  *    in the process of exception.
55  * -# The regex in testcase.yaml verify the kernel will dump thread id
56  *    information and error type when exception occurs.
57  *
58  * Expected Test Result:
59  * - The expected log message is caught.
60  *
61  * Pass/Fail Criteria:
62  * - Success if the log matching regex in step 3.
63  * - Failure if the log is not matching regex in step 3.
64  *
65  * Assumptions and Constraints:
66  * - N/A
67  * @ingroup kernel_fatal_tests
68  */
test_message_capture(void)69 void test_message_capture(void)
70 {
71 	unsigned int key;
72 
73 	expected_reason = K_ERR_KERNEL_OOPS;
74 
75 	key = irq_lock();
76 	k_oops();
77 	printk("SHOULD NEVER SEE THIS\n");
78 	irq_unlock(key);
79 }
80 
main(void)81 int main(void)
82 {
83 	/* main() is an essential thread, and we try to OOPS it.  When
84 	 * this test was written, that worked (even though it wasn't
85 	 * supposed to per docs).  Now we trap a different error (a
86 	 * panic and not an oops).  Set the thread non-essential as a
87 	 * workaround.
88 	 */
89 	z_thread_essential_clear(_current);
90 
91 	test_message_capture();
92 	return 0;
93 }
94