1# Exception Debugging
2
3
4## Basic Concepts
5
6The OpenHarmony LiteOS-M provides exception handling and debugging measures to help locate and analyze problems. Exception handling involves a series of actions taken by the OS to respond to exceptions occurred during the OS running, for example, printing the exception type, system status, call stack information of the current function, CPU information, and call stack information of tasks.
7
8
9## Working Principles
10
11A stack frame contains information such as function parameters, variables, and return value in a function call process. When a function is called, a stack frame of the subfunction is created, and the input parameters, local variables, and registers of the function are stored into the stack. Stack frames grow towards lower addresses. The ARM32 CPU architecture is used as an example. Each stack frame stores the historical values of the program counter (PC), link register (LR), stack pointer (SP), and frame pointer (FP) registers. The LR points to the return address of a function, and the FP points to the start address of the stack frame of the function's parent function. The FP helps locate the parent function's stack frame, which further helps locate the parent function's FP. The parent function's FP helps locate the grandparent function's stack frame and FP... In this way, the call stack of the program can be traced to obtain the relationship between the functions called.
12
13When an exception occurs in the system, the system prints the register information in the stack frame of the abnormal function as well as the LRs and FPs in the stack frames of its parent function and grandfather function. The relationships between the functions help you locate the cause of the exception.
14
15The following figure illustrates the stack analysis mechanism for your reference. The actual stack information varies depending on the CPU architecture.
16
17**Figure 1** Stack analysis mechanism
18
19![](figures/stack-analysis-mechanism.png "stack-analysis-mechanism")
20
21In the figure, the registers in different colors indicate different functions. The registers save related data when functions are called. The FP register helps track the stack to the parent function of the abnormal function and further presents the relationships between the functions called.
22
23
24## Available APIs
25
26The following table describes APIs available for the OpenHarmony LiteOS-M stack trace module. For more details about the APIs, see the API reference.
27
28**Table 1** APIs of the stack trace module
29
30| API| Description|
31| -------- | -------- |
32| LOS_BackTrace | Prints the call stack relationship at the calling point.|
33| LOS_RecordLR  | Obtains the call stack relationship at the calling point when print is unavailable.|
34
35
36## Development Guidelines
37
38
39### How to Develop
40
41The typical process for enabling exception debugging is as follows:
42
431. Configure the macros related to exception handling in the **target_config.h** file.
44
45   | Configuration Item| Description| Value|
46   | -------- | -------- | -------- |
47   | LOSCFG_BACKTRACE_DEPTH | Depth of the function call stack. The default value is **15**.| 15 |
48   | LOSCFG_BACKTRACE_TYPE | Type of the stack tracing.<br>**0**: The stack tracing is disabled.<br>**1**: supports call stack analysis of the Cortex-M series hardware.<br>**2**: supports call stack analysis of the RISC-V series hardware.| Set this parameter to **1** or **2** based on the toolchain type.|
49
502. Use the error code in the example to build and run a project, and check the error information displayed on the serial port terminal. The sample code simulates error code. During actual product development, use the exception debugging mechanism to locate exceptions.
51
52   The following example demonstrates the exception output through a task. The task entry function simulates calling of multiple functions and finally calls a function that simulates an exception. The sample code is as follows:
53
54   The sample code is built and verified in **./kernel/liteos_m/testsuites/src/osTest.c**. Call **ExampleExcEntry** in **TestTaskEntry**.
55
56   ```
57   #include <stdio.h>
58   #include "los_config.h"
59   #include "los_interrupt.h"
60   #include "los_task.h"
61
62   UINT32 g_taskExcId;
63   #define TSK_PRIOR 4
64
65   /* Simulate an exception. */
66   UINT32 GetResultException0(UINT16 dividend){
67       UINT32 result = *(UINT32 *)(0xffffffff);
68       printf("Enter GetResultException0. %u\r\n", result);
69       return result;
70   }
71
72   UINT32 GetResultException1(UINT16 dividend){
73       printf("Enter GetResultException1.\r\n");
74       return GetResultException0(dividend);
75   }
76
77   UINT32 GetResultException2(UINT16 dividend){
78       printf("Enter GetResultException2.\r\n");
79       return GetResultException1(dividend);
80   }
81
82   UINT32 ExampleExc(VOID)
83   {
84       UINT32 ret;
85
86       printf("Enter Example_Exc Handler.\r\n");
87
88       /* Simulate the triggering of the exception. */
89       ret = GetResultException2(TSK_PRIOR);
90       printf("Divided result =%u.\r\n", ret);
91
92       printf("Exit Example_Exc Handler.\r\n");
93       return ret;
94   }
95
96
97   /* Create a task with an exception in the task entry function. */
98   UINT32 ExampleExcEntry(VOID)
99   {
100       UINT32 ret;
101       TSK_INIT_PARAM_S initParam = { 0 };
102
103       /* Lock task scheduling to prevent newly created tasks from being scheduled prior to this task due to higher priority. */
104       LOS_TaskLock();
105
106       printf("LOS_TaskLock() Success!\r\n");
107
108       initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleExc;
109       initParam.usTaskPrio = TSK_PRIOR;
110       initParam.pcName = "Example_Exc";
111       initParam.uwStackSize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE;
112       /* Create a task with a higher priority. The task will not be executed because task scheduling is locked. */
113       ret = LOS_TaskCreate(&g_taskExcId, &initParam);
114       if (ret != LOS_OK) {
115           LOS_TaskUnlock();
116
117           printf("Example_Exc create Failed!\r\n");
118           return LOS_NOK;
119       }
120
121       printf("Example_Exc create Success!\r\n");
122
123         /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */
124         LOS_TaskUnlock();
125
126         return LOS_OK;
127     }
128   ```
129
130   The error information output by the serial port terminal is as follows:
131
132   ```
133   LOS_TaskLock() Success!
134   Example_Exc create Success!
135   Enter Example_Exc Handler.
136   Enter GetResultException2.
137   Enter GetResultException1.
138   *************Exception Information**************
139   Type      = 4
140   ThrdPid   = 5
141   Phase     = exc in task
142   FaultAddr = 0xfffffffc
143   Current task info:
144   Task name = Example_Exc
145   Task ID   = 5
146   Task SP   = 0x210549bc
147   Task ST   = 0x21053a00
148   Task SS   = 0x1000
149   Exception reg dump:
150   PC        = 0x2101c61a
151   LR        = 0x2101c64d
152   SP        = 0x210549a8
153   R0        = 0x4
154   R1        = 0xa
155   R2        = 0x0
156   R3        = 0xffffffff
157   R4        = 0x2103fb20
158   R5        = 0x5050505
159   R6        = 0x6060606
160   R7        = 0x210549a8
161   R8        = 0x8080808
162   R9        = 0x9090909
163   R10       = 0x10101010
164   R11       = 0x11111111
165   R12       = 0x0
166   PriMask   = 0x0
167   xPSR      = 0x41000000
168   ----- backtrace start -----
169   backtrace 0 -- lr = 0x2101c64c
170   backtrace 1 -- lr = 0x2101c674
171   backtrace 2 -- lr = 0x2101c696
172   backtrace 3 -- lr = 0x2101b1ec
173   ----- backtrace end -----
174
175    TID  Priority   Status StackSize WaterLine StackPoint TopOfStack EventMask  SemID  CPUUSE CPUUSE10s CPUUSE1s   TaskEntry name
176    ---  -------- -------- --------- --------- ---------- ---------- --------- ------ ------- --------- --------  ---------- ----
177      0        0      Pend    0x1000      0xdc 0x2104730c 0x210463e8         0 0xffff     0.0       0.0      0.0  0x2101a199 Swt_Task
178      1       31     Ready     0x500      0x44 0x210478e4 0x21047428         0 0xffff     0.0       0.0      0.0  0x2101a9c9 IdleCore000
179      2        5  PendTime    0x6000      0xd4 0x2104e8f4 0x210489c8         0 0xffff     5.7       5.7      0.0  0x21016149 tcpip_thread
180      3        3      Pend    0x1000     0x488 0x2104f90c 0x2104e9e8       0x1 0xffff     8.6       8.6      0.0  0x21016db5 ShellTaskEntry
181      4       25     Ready    0x4000     0x460 0x21053964 0x2104f9f0         0 0xffff     9.0       8.9      0.0  0x2101c765 IT_TST_INI
182      5        4   Running    0x1000     0x458 0x210549bc 0x21053a00         0 0xffff    76.5      76.6      0.0  0x2101c685 Example_Exc
183
184   OS exception NVIC dump:
185   interrupt enable register, base address: 0xe000e100, size: 0x20
186   0x2001 0x0 0x0 0x0 0x0 0x0 0x0 0x0
187   interrupt pending register, base address: 0xe000e200, size: 0x20
188   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
189   interrupt active register, base address: 0xe000e300, size: 0x20
190   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
191   interrupt priority register, base address: 0xe000e400, size: 0xf0
192   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
193   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
194   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
195   0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
196   interrupt exception register, base address: 0xe000ed18, size: 0xc
197   0x0 0x0 0xf0f00000
198   interrupt shcsr register, base address: 0xe000ed24, size: 0x4
199   0x70002
200   interrupt control register, base address: 0xe000ed04, size: 0x4
201   0x1000e805
202
203   memory pools check:
204   system heap memcheck over, all passed!
205   memory pool check end!
206
207   The preceding data may vary depending on the running environment.
208   ```
209
210
211### How to Locate Exceptions
212
213The procedure for locating the exception is as follows:
214
2151. Check that the compiler optimization is disabled. Otherwise, the following problems may be optimized during the compilation process.
216
2172. Open the image disassembly file (.asm) generated. If the file is not generated, use the objdump tool to generate it. The command is as follows:
218
219   ```
220   arm-none-eabi-objdump -S -l XXX.elf
221   ```
222
2233. Search for the PC (pointing to the instruction being executed) in the .asm file to locate the abnormal function.
224
225   The PC address directs to the instruction being executed when the exception occurs. In the .asm file corresponding to the currently executed binary file, search for the PC value **0x2101c61a** and locate the instruction being executed by the CPU. Disassemble the code as follows:
226
227   ```
228   2101c60c <GetResultException0>:
229   2101c60c:	b580      	push	{r7, lr}
230   2101c60e:	b084      	sub	sp, #16
231   2101c610:	af00      	add	r7, sp, #0
232   2101c612:	4603      	mov	r3, r0
233   2101c614:	80fb      	strh	r3, [r7, #6]
234   2101c616:	f04f 33ff 	mov.w	r3, #4294967295	; 0xffffffff
235   2101c61a:	681b      	ldr	r3, [r3, #0]
236   2101c61c:	60fb      	str	r3, [r7, #12]
237   2101c61e:	68f9      	ldr	r1, [r7, #12]
238   2101c620:	4803      	ldr	r0, [pc, #12]	; (2101c630 <GetResultException0+0x24>)
239   2101c622:	f001 f92b 	bl	2101d87c <printf>
240   2101c626:	68fb      	ldr	r3, [r7, #12]
241   2101c628:	4618      	mov	r0, r3
242   2101c62a:	3710      	adds	r7, #16
243   2101c62c:	46bd      	mov	sp, r7
244   2101c62e:	bd80      	pop	{r7, pc}
245   2101c630:	21025f90 	.word	0x21025f90
246   ```
247
248   As indicated by the information displayed:
249   - When the exception occurs, the CPU is executing the **ldr r3, [r3, #0]** instruction. The value of **r3** is **0xffffffff**, which causes an invalid address.
250   - The exception occurs in the **GetResultException0** function.
251
2525. Search for the parent function of the abnormal function based on the LR value.
253
254   The code disassembly of the LR value **0x2101c64d** is as follows:
255
256   ```
257   2101c634 <GetResultException1>:
258   2101c634:	b580      	push	{r7, lr}
259   2101c636:	b082      	sub	sp, #8
260   2101c638:	af00      	add	r7, sp, #0
261   2101c63a:	4603      	mov	r3, r0
262   2101c63c:	80fb      	strh	r3, [r7, #6]
263   2101c63e:	4806      	ldr	r0, [pc, #24]	; (2101c658 <GetResultException1+0x24>)
264   2101c640:	f001 f91c 	bl	2101d87c <printf>
265   2101c644:	88fb      	ldrh	r3, [r7, #6]
266   2101c646:	4618      	mov	r0, r3
267   2101c648:	f7ff ffe0 	bl	2101c60c <GetResultException0>
268   2101c64c:	4603      	mov	r3, r0
269   2101c64e:	4618      	mov	r0, r3
270   2101c650:	3708      	adds	r7, #8
271   2101c652:	46bd      	mov	sp, r7
272   2101c654:	bd80      	pop	{r7, pc}
273   2101c656:	bf00      	nop
274   2101c658:	21025fb0 	.word	0x21025fb0
275   ```
276
277   The previous line of LR **2101c648** is **bl 2101c60c \<GetResultException0\>**, which calls the abnormal function. The parent function is **GetResultException1**.
278
2797. Repeat step 3 to parse the LR value between **backtrace start** and **backtrace end** in the exception information to obtain the call stack relationship where the exception occurs and find the cause of the exception.
280