xref: /aosp_15_r20/external/elfutils/backends/loongarch_unwind.c (revision 7304104da70ce23c86437a01be71edd1a2d7f37e)
1 /* Get previous frame state for an existing frame state.
2    Copyright (C) 2023 OpenAnolis community LoongArch SIG.
3    Copyright (C) 2023 Loongson Technology Corporation Limited.
4    This file is part of elfutils.
5 
6    This file is free software; you can redistribute it and/or modify
7    it under the terms of either
8 
9      * the GNU Lesser General Public License as published by the Free
10        Software Foundation; either version 3 of the License, or (at
11        your option) any later version
12 
13    or
14 
15      * the GNU General Public License as published by the Free
16        Software Foundation; either version 2 of the License, or (at
17        your option) any later version
18 
19    or both in parallel, as here.
20 
21    elfutils is distributed in the hope that it will be useful, but
22    WITHOUT ANY WARRANTY; without even the implied warranty of
23    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24    General Public License for more details.
25 
26    You should have received copies of the GNU General Public License and
27    the GNU Lesser General Public License along with this program.  If
28    not, see <http://www.gnu.org/licenses/>.  */
29 
30 #ifdef HAVE_CONFIG_H
31 # include <config.h>
32 #endif
33 
34 #define BACKEND loongarch_
35 #define RA_REG 1
36 #define SP_REG 3
37 #define FP_REG 22
38 
39 #define RA_OFFSET 8
40 #define FP_OFFSET 16
41 
42 #include "libebl_CPU.h"
43 
44 /* There was no CFI. Maybe we happen to have a frame pointer and can unwind from that?  */
45 
46 bool
EBLHOOK(unwind)47 EBLHOOK(unwind) (Ebl *ebl __attribute__ ((unused)), Dwarf_Addr pc __attribute__ ((unused)),
48                  ebl_tid_registers_t *setfunc, ebl_tid_registers_get_t *getfunc,
49                  ebl_pid_memory_read_t *readfunc, void *arg,
50                  bool *signal_framep __attribute__ ((unused)))
51 {
52   Dwarf_Word fp, ra, sp;
53 
54   if (!getfunc(RA_REG, 1, &ra, arg))
55     return false;
56 
57   if (ra == 0 || !setfunc(-1, 1, &ra, arg))
58     return false;
59 
60   if (!getfunc(FP_REG, 1, &fp, arg))
61     fp = 0;
62 
63   if (!getfunc(SP_REG, 1, &sp, arg))
64     sp = 0;
65 
66   Dwarf_Word newRa, newFp, newSp;
67 
68   if (!readfunc(fp - RA_OFFSET, &newRa, arg))
69     newRa = 0;
70 
71   if (!readfunc(fp - FP_OFFSET, &newFp, arg))
72     newFp = 0;
73 
74   newSp = fp;
75 
76   // These are not fatal if they don't work. They will just prevent unwinding at the next frame.
77   setfunc(RA_REG, 1, &newRa, arg);
78   setfunc(FP_REG, 1, &newFp, arg);
79   setfunc(SP_REG, 1, &newSp, arg);
80 
81   // If the fp is invalid, we might still have a valid ra.
82   // But if the fp is valid, then the stack should be moving in the right direction.
83   return fp == 0 || newSp > sp;
84 }
85