1 /* Target-dependent code for the RISC-V architecture, for GDB.
2 
3    Copyright (C) 2018-2024 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "extract-store-integer.h"
21 #include "frame.h"
22 #include "inferior.h"
23 #include "symtab.h"
24 #include "value.h"
25 #include "cli/cli-cmds.h"
26 #include "language.h"
27 #include "gdbcore.h"
28 #include "symfile.h"
29 #include "objfiles.h"
30 #include "gdbtypes.h"
31 #include "target.h"
32 #include "arch-utils.h"
33 #include "regcache.h"
34 #include "osabi.h"
35 #include "riscv-tdep.h"
36 #include "reggroups.h"
37 #include "opcode/riscv.h"
38 #include "elf/riscv.h"
39 #include "elf-bfd.h"
40 #include "symcat.h"
41 #include "dis-asm.h"
42 #include "frame-unwind.h"
43 #include "frame-base.h"
44 #include "trad-frame.h"
45 #include "infcall.h"
46 #include "floatformat.h"
47 #include "remote.h"
48 #include "target-descriptions.h"
49 #include "dwarf2/frame.h"
50 #include "user-regs.h"
51 #include "valprint.h"
52 #include "opcode/riscv-opc.h"
53 #include "cli/cli-decode.h"
54 #include "observable.h"
55 #include "prologue-value.h"
56 #include "arch/riscv.h"
57 #include "riscv-ravenscar-thread.h"
58 #include "gdbsupport/gdb-safe-ctype.h"
59 
60 /* The stack must be 16-byte aligned.  */
61 #define SP_ALIGNMENT 16
62 
63 /* The biggest alignment that the target supports.  */
64 #define BIGGEST_ALIGNMENT 16
65 
66 /* Define a series of is_XXX_insn functions to check if the value INSN
67    is an instance of instruction XXX.  */
68 #define DECLARE_INSN(INSN_NAME, INSN_MATCH, INSN_MASK) \
69 static inline bool is_ ## INSN_NAME ## _insn (long insn) \
70 { \
71   return (insn & INSN_MASK) == INSN_MATCH; \
72 }
73 #include "opcode/riscv-opc.h"
74 #undef DECLARE_INSN
75 
76 /* When this is true debugging information about breakpoint kinds will be
77    printed.  */
78 
79 static bool riscv_debug_breakpoints = false;
80 
81 /* Print a "riscv-breakpoints" debug statement.  */
82 
83 #define riscv_breakpoints_debug_printf(fmt, ...)  \
84   debug_prefixed_printf_cond (riscv_debug_breakpoints,      \
85                                     "riscv-breakpoints",    \
86                                     fmt, ##__VA_ARGS__)
87 
88 /* When this is true debugging information about inferior calls will be
89    printed.  */
90 
91 static bool riscv_debug_infcall = false;
92 
93 /* Print a "riscv-infcall" debug statement.  */
94 
95 #define riscv_infcall_debug_printf(fmt, ...)                                    \
96   debug_prefixed_printf_cond (riscv_debug_infcall, "riscv-infcall",   \
97                                     fmt, ##__VA_ARGS__)
98 
99 /* Print "riscv-infcall" start/end debug statements.  */
100 
101 #define RISCV_INFCALL_SCOPED_DEBUG_START_END(fmt, ...)                \
102   scoped_debug_start_end (riscv_debug_infcall, "riscv-infcall", \
103                                 fmt, ##__VA_ARGS__)
104 
105 /* When this is true debugging information about stack unwinding will be
106    printed.  */
107 
108 static bool riscv_debug_unwinder = false;
109 
110 /* Print a "riscv-unwinder" debug statement.  */
111 
112 #define riscv_unwinder_debug_printf(fmt, ...)                                   \
113   debug_prefixed_printf_cond (riscv_debug_unwinder, "riscv-unwinder", \
114                                     fmt, ##__VA_ARGS__)
115 
116 /* When this is true debugging information about gdbarch initialisation
117    will be printed.  */
118 
119 static bool riscv_debug_gdbarch = false;
120 
121 /* Print a "riscv-gdbarch" debug statement.  */
122 
123 #define riscv_gdbarch_debug_printf(fmt, ...)                                    \
124   debug_prefixed_printf_cond (riscv_debug_gdbarch, "riscv-gdbarch",   \
125                                     fmt, ##__VA_ARGS__)
126 
127 /* The names of the RISC-V target description features.  */
128 const char *riscv_feature_name_csr = "org.gnu.gdb.riscv.csr";
129 static const char *riscv_feature_name_cpu = "org.gnu.gdb.riscv.cpu";
130 static const char *riscv_feature_name_fpu = "org.gnu.gdb.riscv.fpu";
131 static const char *riscv_feature_name_virtual = "org.gnu.gdb.riscv.virtual";
132 static const char *riscv_feature_name_vector = "org.gnu.gdb.riscv.vector";
133 
134 /* The current set of options to be passed to the disassembler.  */
135 static std::string riscv_disassembler_options;
136 
137 /* Cached information about a frame.  */
138 
139 struct riscv_unwind_cache
140 {
141   /* The register from which we can calculate the frame base.  This is
142      usually $sp or $fp.  */
143   int frame_base_reg;
144 
145   /* The offset from the current value in register FRAME_BASE_REG to the
146      actual frame base address.  */
147   int frame_base_offset;
148 
149   /* Information about previous register values.  */
150   trad_frame_saved_reg *regs;
151 
152   /* The id for this frame.  */
153   struct frame_id this_id;
154 
155   /* The base (stack) address for this frame.  This is the stack pointer
156      value on entry to this frame before any adjustments are made.  */
157   CORE_ADDR frame_base;
158 };
159 
160 /* RISC-V specific register group for CSRs.  */
161 
162 static const reggroup *csr_reggroup = nullptr;
163 
164 /* Callback function for user_reg_add.  */
165 
166 static struct value *
value_of_riscv_user_reg(const frame_info_ptr & frame,const void * baton)167 value_of_riscv_user_reg (const frame_info_ptr &frame, const void *baton)
168 {
169   const int *reg_p = (const int *) baton;
170   return value_of_register (*reg_p, get_next_frame_sentinel_okay (frame));
171 }
172 
173 /* Information about a register alias that needs to be set up for this
174    target.  These are collected when the target's XML description is
175    analysed, and then processed later, once the gdbarch has been created.  */
176 
177 class riscv_pending_register_alias
178 {
179 public:
180   /* Constructor.  */
181 
riscv_pending_register_alias(const char * name,const void * baton)182   riscv_pending_register_alias (const char *name, const void *baton)
183     : m_name (name),
184       m_baton (baton)
185   { /* Nothing.  */ }
186 
187   /* Convert this into a user register for GDBARCH.  */
188 
create(struct gdbarch * gdbarch)189   void create (struct gdbarch *gdbarch) const
190   {
191     user_reg_add (gdbarch, m_name, value_of_riscv_user_reg, m_baton);
192   }
193 
194 private:
195   /* The name for this alias.  */
196   const char *m_name;
197 
198   /* The baton value for passing to user_reg_add.  This must point to some
199      data that will live for at least as long as the gdbarch object to
200      which the user register is attached.  */
201   const void *m_baton;
202 };
203 
204 /* A set of registers that we expect to find in a tdesc_feature.  These
205    are use in RISCV_GDBARCH_INIT when processing the target description.  */
206 
207 struct riscv_register_feature
208 {
riscv_register_featureriscv_register_feature209   explicit riscv_register_feature (const char *feature_name)
210     : m_feature_name (feature_name)
211   { /* Delete.  */ }
212 
213   riscv_register_feature () = delete;
214   DISABLE_COPY_AND_ASSIGN (riscv_register_feature);
215 
216   /* Information for a single register.  */
217   struct register_info
218   {
219     /* The GDB register number for this register.  */
220     int regnum;
221 
222     /* List of names for this register.  The first name in this list is the
223        preferred name, the name GDB should use when describing this
224        register.  */
225     std::vector<const char *> names;
226 
227     /* Look in FEATURE for a register with a name from this classes names
228        list.  If the register is found then register its number with
229        TDESC_DATA and add all its aliases to the ALIASES list.
230        PREFER_FIRST_NAME_P is used when deciding which aliases to create.  */
231     bool check (struct tdesc_arch_data *tdesc_data,
232                     const struct tdesc_feature *feature,
233                     bool prefer_first_name_p,
234                     std::vector<riscv_pending_register_alias> *aliases) const;
235   };
236 
237   /* Return the name of this feature.  */
nameriscv_register_feature238   const char *name () const
239   { return m_feature_name; }
240 
241 protected:
242 
243   /* Return a target description feature extracted from TDESC for this
244      register feature.  Will return nullptr if there is no feature in TDESC
245      with the name M_FEATURE_NAME.  */
tdesc_featureriscv_register_feature246   const struct tdesc_feature *tdesc_feature (const struct target_desc *tdesc) const
247   {
248     return tdesc_find_feature (tdesc, name ());
249   }
250 
251   /* List of all the registers that we expect that we might find in this
252      register set.  */
253   std::vector<struct register_info> m_registers;
254 
255 private:
256 
257   /* The name for this feature.  This is the name used to find this feature
258      within the target description.  */
259   const char *m_feature_name;
260 };
261 
262 /* See description in the class declaration above.  */
263 
264 bool
check(struct tdesc_arch_data * tdesc_data,const struct tdesc_feature * feature,bool prefer_first_name_p,std::vector<riscv_pending_register_alias> * aliases)265 riscv_register_feature::register_info::check
266           (struct tdesc_arch_data *tdesc_data,
267            const struct tdesc_feature *feature,
268            bool prefer_first_name_p,
269            std::vector<riscv_pending_register_alias> *aliases) const
270 {
271   for (const char *name : this->names)
272     {
273       bool found = tdesc_numbered_register (feature, tdesc_data,
274                                                       this->regnum, name);
275       if (found)
276           {
277             /* We know that the target description mentions this
278                register.  In RISCV_REGISTER_NAME we ensure that GDB
279                always uses the first name for each register, so here we
280                add aliases for all of the remaining names.  */
281             int start_index = prefer_first_name_p ? 1 : 0;
282             for (int i = start_index; i < this->names.size (); ++i)
283               {
284                 const char *alias = this->names[i];
285                 if (alias == name && !prefer_first_name_p)
286                     continue;
287                 aliases->emplace_back (alias, (void *) &this->regnum);
288               }
289             return true;
290           }
291     }
292   return false;
293 }
294 
295 /* Class representing the x-registers feature set.  */
296 
297 struct riscv_xreg_feature : public riscv_register_feature
298 {
riscv_xreg_featureriscv_xreg_feature299   riscv_xreg_feature ()
300     : riscv_register_feature (riscv_feature_name_cpu)
301   {
302     m_registers =  {
303       { RISCV_ZERO_REGNUM + 0, { "zero", "x0" } },
304       { RISCV_ZERO_REGNUM + 1, { "ra", "x1" } },
305       { RISCV_ZERO_REGNUM + 2, { "sp", "x2" } },
306       { RISCV_ZERO_REGNUM + 3, { "gp", "x3" } },
307       { RISCV_ZERO_REGNUM + 4, { "tp", "x4" } },
308       { RISCV_ZERO_REGNUM + 5, { "t0", "x5" } },
309       { RISCV_ZERO_REGNUM + 6, { "t1", "x6" } },
310       { RISCV_ZERO_REGNUM + 7, { "t2", "x7" } },
311       { RISCV_ZERO_REGNUM + 8, { "fp", "x8", "s0" } },
312       { RISCV_ZERO_REGNUM + 9, { "s1", "x9" } },
313       { RISCV_ZERO_REGNUM + 10, { "a0", "x10" } },
314       { RISCV_ZERO_REGNUM + 11, { "a1", "x11" } },
315       { RISCV_ZERO_REGNUM + 12, { "a2", "x12" } },
316       { RISCV_ZERO_REGNUM + 13, { "a3", "x13" } },
317       { RISCV_ZERO_REGNUM + 14, { "a4", "x14" } },
318       { RISCV_ZERO_REGNUM + 15, { "a5", "x15" } },
319       { RISCV_ZERO_REGNUM + 16, { "a6", "x16" } },
320       { RISCV_ZERO_REGNUM + 17, { "a7", "x17" } },
321       { RISCV_ZERO_REGNUM + 18, { "s2", "x18" } },
322       { RISCV_ZERO_REGNUM + 19, { "s3", "x19" } },
323       { RISCV_ZERO_REGNUM + 20, { "s4", "x20" } },
324       { RISCV_ZERO_REGNUM + 21, { "s5", "x21" } },
325       { RISCV_ZERO_REGNUM + 22, { "s6", "x22" } },
326       { RISCV_ZERO_REGNUM + 23, { "s7", "x23" } },
327       { RISCV_ZERO_REGNUM + 24, { "s8", "x24" } },
328       { RISCV_ZERO_REGNUM + 25, { "s9", "x25" } },
329       { RISCV_ZERO_REGNUM + 26, { "s10", "x26" } },
330       { RISCV_ZERO_REGNUM + 27, { "s11", "x27" } },
331       { RISCV_ZERO_REGNUM + 28, { "t3", "x28" } },
332       { RISCV_ZERO_REGNUM + 29, { "t4", "x29" } },
333       { RISCV_ZERO_REGNUM + 30, { "t5", "x30" } },
334       { RISCV_ZERO_REGNUM + 31, { "t6", "x31" } },
335       { RISCV_ZERO_REGNUM + 32, { "pc" } }
336     };
337   }
338 
339   /* Return the preferred name for the register with gdb register number
340      REGNUM, which must be in the inclusive range RISCV_ZERO_REGNUM to
341      RISCV_PC_REGNUM.  */
register_nameriscv_xreg_feature342   const char *register_name (int regnum) const
343   {
344     gdb_assert (regnum >= RISCV_ZERO_REGNUM && regnum <= m_registers.size ());
345     return m_registers[regnum].names[0];
346   }
347 
348   /* Check this feature within TDESC, record the registers from this
349      feature into TDESC_DATA and update ALIASES and FEATURES.  */
checkriscv_xreg_feature350   bool check (const struct target_desc *tdesc,
351                 struct tdesc_arch_data *tdesc_data,
352                 std::vector<riscv_pending_register_alias> *aliases,
353                 struct riscv_gdbarch_features *features) const
354   {
355     const struct tdesc_feature *feature_cpu = tdesc_feature (tdesc);
356 
357     if (feature_cpu == nullptr)
358       return false;
359 
360     bool seen_an_optional_reg_p = false;
361     for (const auto &reg : m_registers)
362       {
363           bool found = reg.check (tdesc_data, feature_cpu, true, aliases);
364 
365           bool is_optional_reg_p = (reg.regnum >= RISCV_ZERO_REGNUM + 16
366                                           && reg.regnum < RISCV_ZERO_REGNUM + 32);
367 
368           if (!found && (!is_optional_reg_p || seen_an_optional_reg_p))
369             return false;
370           else if (found && is_optional_reg_p)
371             seen_an_optional_reg_p = true;
372       }
373 
374     /* Check that all of the core cpu registers have the same bitsize.  */
375     int xlen_bitsize = tdesc_register_bitsize (feature_cpu, "pc");
376 
377     bool valid_p = true;
378     for (auto &tdesc_reg : feature_cpu->registers)
379       valid_p &= (tdesc_reg->bitsize == xlen_bitsize);
380 
381     features->xlen = (xlen_bitsize / 8);
382     features->embedded = !seen_an_optional_reg_p;
383 
384     return valid_p;
385   }
386 };
387 
388 /* An instance of the x-register feature set.  */
389 
390 static const struct riscv_xreg_feature riscv_xreg_feature;
391 
392 /* Class representing the f-registers feature set.  */
393 
394 struct riscv_freg_feature : public riscv_register_feature
395 {
riscv_freg_featureriscv_freg_feature396   riscv_freg_feature ()
397     : riscv_register_feature (riscv_feature_name_fpu)
398   {
399     m_registers =  {
400       { RISCV_FIRST_FP_REGNUM + 0, { "ft0", "f0" } },
401       { RISCV_FIRST_FP_REGNUM + 1, { "ft1", "f1" } },
402       { RISCV_FIRST_FP_REGNUM + 2, { "ft2", "f2" } },
403       { RISCV_FIRST_FP_REGNUM + 3, { "ft3", "f3" } },
404       { RISCV_FIRST_FP_REGNUM + 4, { "ft4", "f4" } },
405       { RISCV_FIRST_FP_REGNUM + 5, { "ft5", "f5" } },
406       { RISCV_FIRST_FP_REGNUM + 6, { "ft6", "f6" } },
407       { RISCV_FIRST_FP_REGNUM + 7, { "ft7", "f7" } },
408       { RISCV_FIRST_FP_REGNUM + 8, { "fs0", "f8" } },
409       { RISCV_FIRST_FP_REGNUM + 9, { "fs1", "f9" } },
410       { RISCV_FIRST_FP_REGNUM + 10, { "fa0", "f10" } },
411       { RISCV_FIRST_FP_REGNUM + 11, { "fa1", "f11" } },
412       { RISCV_FIRST_FP_REGNUM + 12, { "fa2", "f12" } },
413       { RISCV_FIRST_FP_REGNUM + 13, { "fa3", "f13" } },
414       { RISCV_FIRST_FP_REGNUM + 14, { "fa4", "f14" } },
415       { RISCV_FIRST_FP_REGNUM + 15, { "fa5", "f15" } },
416       { RISCV_FIRST_FP_REGNUM + 16, { "fa6", "f16" } },
417       { RISCV_FIRST_FP_REGNUM + 17, { "fa7", "f17" } },
418       { RISCV_FIRST_FP_REGNUM + 18, { "fs2", "f18" } },
419       { RISCV_FIRST_FP_REGNUM + 19, { "fs3", "f19" } },
420       { RISCV_FIRST_FP_REGNUM + 20, { "fs4", "f20" } },
421       { RISCV_FIRST_FP_REGNUM + 21, { "fs5", "f21" } },
422       { RISCV_FIRST_FP_REGNUM + 22, { "fs6", "f22" } },
423       { RISCV_FIRST_FP_REGNUM + 23, { "fs7", "f23" } },
424       { RISCV_FIRST_FP_REGNUM + 24, { "fs8", "f24" } },
425       { RISCV_FIRST_FP_REGNUM + 25, { "fs9", "f25" } },
426       { RISCV_FIRST_FP_REGNUM + 26, { "fs10", "f26" } },
427       { RISCV_FIRST_FP_REGNUM + 27, { "fs11", "f27" } },
428       { RISCV_FIRST_FP_REGNUM + 28, { "ft8", "f28" } },
429       { RISCV_FIRST_FP_REGNUM + 29, { "ft9", "f29" } },
430       { RISCV_FIRST_FP_REGNUM + 30, { "ft10", "f30" } },
431       { RISCV_FIRST_FP_REGNUM + 31, { "ft11", "f31" } },
432       { RISCV_CSR_FFLAGS_REGNUM, { "fflags", "csr1" } },
433       { RISCV_CSR_FRM_REGNUM, { "frm", "csr2" } },
434       { RISCV_CSR_FCSR_REGNUM, { "fcsr", "csr3" } },
435     };
436   }
437 
438   /* Return the preferred name for the register with gdb register number
439      REGNUM, which must be in the inclusive range RISCV_FIRST_FP_REGNUM to
440      RISCV_LAST_FP_REGNUM.  */
register_nameriscv_freg_feature441   const char *register_name (int regnum) const
442   {
443     static_assert (RISCV_LAST_FP_REGNUM == RISCV_FIRST_FP_REGNUM + 31);
444     gdb_assert (regnum >= RISCV_FIRST_FP_REGNUM
445                     && regnum <= RISCV_LAST_FP_REGNUM);
446     regnum -= RISCV_FIRST_FP_REGNUM;
447     return m_registers[regnum].names[0];
448   }
449 
450   /* Check this feature within TDESC, record the registers from this
451      feature into TDESC_DATA and update ALIASES and FEATURES.  */
checkriscv_freg_feature452   bool check (const struct target_desc *tdesc,
453                 struct tdesc_arch_data *tdesc_data,
454                 std::vector<riscv_pending_register_alias> *aliases,
455                 struct riscv_gdbarch_features *features) const
456   {
457     const struct tdesc_feature *feature_fpu = tdesc_feature (tdesc);
458 
459     /* It's fine if this feature is missing.  Update the architecture
460        feature set and return.  */
461     if (feature_fpu == nullptr)
462       {
463           features->flen = 0;
464           return true;
465       }
466 
467     /* Check all of the floating pointer registers are present.  We also
468        check that the floating point CSRs are present too, though if these
469        are missing this is not fatal.  */
470     for (const auto &reg : m_registers)
471       {
472           bool found = reg.check (tdesc_data, feature_fpu, true, aliases);
473 
474           bool is_ctrl_reg_p = reg.regnum > RISCV_LAST_FP_REGNUM;
475 
476           if (!found && !is_ctrl_reg_p)
477             return false;
478       }
479 
480     /* Look through all of the floating point registers (not the FP CSRs
481        though), and check they all have the same bitsize.  Use this bitsize
482        to update the feature set for this gdbarch.  */
483     int fp_bitsize = -1;
484     for (const auto &reg : m_registers)
485       {
486           /* Stop once we get to the CSRs which are at the end of the
487              M_REGISTERS list.  */
488           if (reg.regnum > RISCV_LAST_FP_REGNUM)
489             break;
490 
491           int reg_bitsize = -1;
492           for (const char *name : reg.names)
493             {
494               if (tdesc_unnumbered_register (feature_fpu, name))
495                 {
496                     reg_bitsize = tdesc_register_bitsize (feature_fpu, name);
497                     break;
498                 }
499             }
500           gdb_assert (reg_bitsize != -1);
501           if (fp_bitsize == -1)
502             fp_bitsize = reg_bitsize;
503           else if (fp_bitsize != reg_bitsize)
504             return false;
505       }
506 
507     features->flen = (fp_bitsize / 8);
508     return true;
509   }
510 };
511 
512 /* An instance of the f-register feature set.  */
513 
514 static const struct riscv_freg_feature riscv_freg_feature;
515 
516 /* Class representing the virtual registers.  These are not physical
517    registers on the hardware, but might be available from the target.
518    These are not pseudo registers, reading these really does result in a
519    register read from the target, it is just that there might not be a
520    physical register backing the result.  */
521 
522 struct riscv_virtual_feature : public riscv_register_feature
523 {
riscv_virtual_featureriscv_virtual_feature524   riscv_virtual_feature ()
525     : riscv_register_feature (riscv_feature_name_virtual)
526   {
527     m_registers =  {
528       { RISCV_PRIV_REGNUM, { "priv" } }
529     };
530   }
531 
checkriscv_virtual_feature532   bool check (const struct target_desc *tdesc,
533                 struct tdesc_arch_data *tdesc_data,
534                 std::vector<riscv_pending_register_alias> *aliases,
535                 struct riscv_gdbarch_features *features) const
536   {
537     const struct tdesc_feature *feature_virtual = tdesc_feature (tdesc);
538 
539     /* It's fine if this feature is missing.  */
540     if (feature_virtual == nullptr)
541       return true;
542 
543     /* We don't check the return value from the call to check here, all the
544        registers in this feature are optional.  */
545     for (const auto &reg : m_registers)
546       reg.check (tdesc_data, feature_virtual, true, aliases);
547 
548     return true;
549   }
550 };
551 
552 /* An instance of the virtual register feature.  */
553 
554 static const struct riscv_virtual_feature riscv_virtual_feature;
555 
556 /* Class representing the CSR feature.  */
557 
558 struct riscv_csr_feature : public riscv_register_feature
559 {
riscv_csr_featureriscv_csr_feature560   riscv_csr_feature ()
561     : riscv_register_feature (riscv_feature_name_csr)
562   {
563     m_registers = {
564 #define DECLARE_CSR(NAME,VALUE,CLASS,DEFINE_VER,ABORT_VER)            \
565       { RISCV_ ## VALUE ## _REGNUM, { # NAME } },
566 #include "opcode/riscv-opc.h"
567 #undef DECLARE_CSR
568     };
569     riscv_create_csr_aliases ();
570   }
571 
checkriscv_csr_feature572   bool check (const struct target_desc *tdesc,
573                 struct tdesc_arch_data *tdesc_data,
574                 std::vector<riscv_pending_register_alias> *aliases,
575                 struct riscv_gdbarch_features *features) const
576   {
577     const struct tdesc_feature *feature_csr = tdesc_feature (tdesc);
578 
579     /* It's fine if this feature is missing.  */
580     if (feature_csr == nullptr)
581       return true;
582 
583     /* We don't check the return value from the call to check here, all the
584        registers in this feature are optional.  */
585     for (const auto &reg : m_registers)
586       reg.check (tdesc_data, feature_csr, true, aliases);
587 
588     return true;
589   }
590 
591 private:
592 
593   /* Complete RISCV_CSR_FEATURE, building the CSR alias names and adding them
594      to the name list for each register.  */
595 
596   void
riscv_create_csr_aliasesriscv_csr_feature597   riscv_create_csr_aliases ()
598   {
599     for (auto &reg : m_registers)
600       {
601           int csr_num = reg.regnum - RISCV_FIRST_CSR_REGNUM;
602           gdb::unique_xmalloc_ptr<char> alias = xstrprintf ("csr%d", csr_num);
603           reg.names.push_back (alias.release ());
604       }
605   }
606 };
607 
608 /* An instance of the csr register feature.  */
609 
610 static const struct riscv_csr_feature riscv_csr_feature;
611 
612 /* Class representing the v-registers feature set.  */
613 
614 struct riscv_vector_feature : public riscv_register_feature
615 {
riscv_vector_featureriscv_vector_feature616   riscv_vector_feature ()
617     : riscv_register_feature (riscv_feature_name_vector)
618   {
619     m_registers =  {
620       { RISCV_V0_REGNUM + 0, { "v0" } },
621       { RISCV_V0_REGNUM + 1, { "v1" } },
622       { RISCV_V0_REGNUM + 2, { "v2" } },
623       { RISCV_V0_REGNUM + 3, { "v3" } },
624       { RISCV_V0_REGNUM + 4, { "v4" } },
625       { RISCV_V0_REGNUM + 5, { "v5" } },
626       { RISCV_V0_REGNUM + 6, { "v6" } },
627       { RISCV_V0_REGNUM + 7, { "v7" } },
628       { RISCV_V0_REGNUM + 8, { "v8" } },
629       { RISCV_V0_REGNUM + 9, { "v9" } },
630       { RISCV_V0_REGNUM + 10, { "v10" } },
631       { RISCV_V0_REGNUM + 11, { "v11" } },
632       { RISCV_V0_REGNUM + 12, { "v12" } },
633       { RISCV_V0_REGNUM + 13, { "v13" } },
634       { RISCV_V0_REGNUM + 14, { "v14" } },
635       { RISCV_V0_REGNUM + 15, { "v15" } },
636       { RISCV_V0_REGNUM + 16, { "v16" } },
637       { RISCV_V0_REGNUM + 17, { "v17" } },
638       { RISCV_V0_REGNUM + 18, { "v18" } },
639       { RISCV_V0_REGNUM + 19, { "v19" } },
640       { RISCV_V0_REGNUM + 20, { "v20" } },
641       { RISCV_V0_REGNUM + 21, { "v21" } },
642       { RISCV_V0_REGNUM + 22, { "v22" } },
643       { RISCV_V0_REGNUM + 23, { "v23" } },
644       { RISCV_V0_REGNUM + 24, { "v24" } },
645       { RISCV_V0_REGNUM + 25, { "v25" } },
646       { RISCV_V0_REGNUM + 26, { "v26" } },
647       { RISCV_V0_REGNUM + 27, { "v27" } },
648       { RISCV_V0_REGNUM + 28, { "v28" } },
649       { RISCV_V0_REGNUM + 29, { "v29" } },
650       { RISCV_V0_REGNUM + 30, { "v30" } },
651       { RISCV_V0_REGNUM + 31, { "v31" } },
652     };
653   }
654 
655   /* Return the preferred name for the register with gdb register number
656      REGNUM, which must be in the inclusive range RISCV_V0_REGNUM to
657      RISCV_V0_REGNUM + 31.  */
register_nameriscv_vector_feature658   const char *register_name (int regnum) const
659   {
660     gdb_assert (regnum >= RISCV_V0_REGNUM
661                     && regnum <= RISCV_V0_REGNUM + 31);
662     regnum -= RISCV_V0_REGNUM;
663     return m_registers[regnum].names[0];
664   }
665 
666   /* Check this feature within TDESC, record the registers from this
667      feature into TDESC_DATA and update ALIASES and FEATURES.  */
checkriscv_vector_feature668   bool check (const struct target_desc *tdesc,
669                 struct tdesc_arch_data *tdesc_data,
670                 std::vector<riscv_pending_register_alias> *aliases,
671                 struct riscv_gdbarch_features *features) const
672   {
673     const struct tdesc_feature *feature_vector = tdesc_feature (tdesc);
674 
675     /* It's fine if this feature is missing.  Update the architecture
676        feature set and return.  */
677     if (feature_vector == nullptr)
678       {
679           features->vlen = 0;
680           return true;
681       }
682 
683     /* Check all of the vector registers are present.  */
684     for (const auto &reg : m_registers)
685       {
686           if (!reg.check (tdesc_data, feature_vector, true, aliases))
687             return false;
688       }
689 
690     /* Look through all of the vector registers and check they all have the
691        same bitsize.  Use this bitsize to update the feature set for this
692        gdbarch.  */
693     int vector_bitsize = -1;
694     for (const auto &reg : m_registers)
695       {
696           int reg_bitsize = -1;
697           for (const char *name : reg.names)
698             {
699               if (tdesc_unnumbered_register (feature_vector, name))
700                 {
701                     reg_bitsize = tdesc_register_bitsize (feature_vector, name);
702                     break;
703                 }
704             }
705           gdb_assert (reg_bitsize != -1);
706           if (vector_bitsize == -1)
707             vector_bitsize = reg_bitsize;
708           else if (vector_bitsize != reg_bitsize)
709             return false;
710       }
711 
712     features->vlen = (vector_bitsize / 8);
713     return true;
714   }
715 };
716 
717 /* An instance of the v-register feature set.  */
718 
719 static const struct riscv_vector_feature riscv_vector_feature;
720 
721 /* Controls whether we place compressed breakpoints or not.  When in auto
722    mode GDB tries to determine if the target supports compressed
723    breakpoints, and uses them if it does.  */
724 
725 static enum auto_boolean use_compressed_breakpoints;
726 
727 /* The show callback for 'show riscv use-compressed-breakpoints'.  */
728 
729 static void
show_use_compressed_breakpoints(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)730 show_use_compressed_breakpoints (struct ui_file *file, int from_tty,
731                                          struct cmd_list_element *c,
732                                          const char *value)
733 {
734   gdb_printf (file,
735                 _("Debugger's use of compressed breakpoints is set "
736                     "to %s.\n"), value);
737 }
738 
739 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
740 
741 static struct cmd_list_element *setriscvcmdlist = NULL;
742 static struct cmd_list_element *showriscvcmdlist = NULL;
743 
744 /* The set and show lists for 'set riscv' and 'show riscv' prefixes.  */
745 
746 static struct cmd_list_element *setdebugriscvcmdlist = NULL;
747 static struct cmd_list_element *showdebugriscvcmdlist = NULL;
748 
749 /* The show callback for all 'show debug riscv VARNAME' variables.  */
750 
751 static void
show_riscv_debug_variable(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)752 show_riscv_debug_variable (struct ui_file *file, int from_tty,
753                                  struct cmd_list_element *c,
754                                  const char *value)
755 {
756   gdb_printf (file,
757                 _("RiscV debug variable `%s' is set to: %s\n"),
758                 c->name, value);
759 }
760 
761 /* See riscv-tdep.h.  */
762 
763 int
riscv_isa_xlen(struct gdbarch * gdbarch)764 riscv_isa_xlen (struct gdbarch *gdbarch)
765 {
766   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
767   return tdep->isa_features.xlen;
768 }
769 
770 /* See riscv-tdep.h.  */
771 
772 int
riscv_abi_xlen(struct gdbarch * gdbarch)773 riscv_abi_xlen (struct gdbarch *gdbarch)
774 {
775   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
776   return tdep->abi_features.xlen;
777 }
778 
779 /* See riscv-tdep.h.  */
780 
781 int
riscv_isa_flen(struct gdbarch * gdbarch)782 riscv_isa_flen (struct gdbarch *gdbarch)
783 {
784   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
785   return tdep->isa_features.flen;
786 }
787 
788 /* See riscv-tdep.h.  */
789 
790 int
riscv_abi_flen(struct gdbarch * gdbarch)791 riscv_abi_flen (struct gdbarch *gdbarch)
792 {
793   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
794   return tdep->abi_features.flen;
795 }
796 
797 /* See riscv-tdep.h.  */
798 
799 bool
riscv_abi_embedded(struct gdbarch * gdbarch)800 riscv_abi_embedded (struct gdbarch *gdbarch)
801 {
802   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
803   return tdep->abi_features.embedded;
804 }
805 
806 /* Return true if the target for GDBARCH has floating point hardware.  */
807 
808 static bool
riscv_has_fp_regs(struct gdbarch * gdbarch)809 riscv_has_fp_regs (struct gdbarch *gdbarch)
810 {
811   return (riscv_isa_flen (gdbarch) > 0);
812 }
813 
814 /* Return true if GDBARCH is using any of the floating point hardware ABIs.  */
815 
816 static bool
riscv_has_fp_abi(struct gdbarch * gdbarch)817 riscv_has_fp_abi (struct gdbarch *gdbarch)
818 {
819   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
820   return tdep->abi_features.flen > 0;
821 }
822 
823 /* Return true if REGNO is a floating pointer register.  */
824 
825 static bool
riscv_is_fp_regno_p(int regno)826 riscv_is_fp_regno_p (int regno)
827 {
828   return (regno >= RISCV_FIRST_FP_REGNUM
829             && regno <= RISCV_LAST_FP_REGNUM);
830 }
831 
832 /* Implement the breakpoint_kind_from_pc gdbarch method.  */
833 
834 static int
riscv_breakpoint_kind_from_pc(struct gdbarch * gdbarch,CORE_ADDR * pcptr)835 riscv_breakpoint_kind_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pcptr)
836 {
837   if (use_compressed_breakpoints == AUTO_BOOLEAN_AUTO)
838     {
839       bool unaligned_p = false;
840       gdb_byte buf[1];
841 
842       /* Some targets don't support unaligned reads.  The address can only
843            be unaligned if the C extension is supported.  So it is safe to
844            use a compressed breakpoint in this case.  */
845       if (*pcptr & 0x2)
846           unaligned_p = true;
847       else
848           {
849             /* Read the opcode byte to determine the instruction length.  If
850                the read fails this may be because we tried to set the
851                breakpoint at an invalid address, in this case we provide a
852                fake result which will give a breakpoint length of 4.
853                Hopefully when we try to actually insert the breakpoint we
854                will see a failure then too which will be reported to the
855                user.  */
856             if (target_read_code (*pcptr, buf, 1) == -1)
857               buf[0] = 0;
858           }
859 
860       if (riscv_debug_breakpoints)
861           {
862             const char *bp = (unaligned_p || riscv_insn_length (buf[0]) == 2
863                                   ? "C.EBREAK" : "EBREAK");
864 
865             std::string suffix;
866             if (unaligned_p)
867               suffix = "(unaligned address)";
868             else
869               suffix = string_printf ("(instruction length %d)",
870                                             riscv_insn_length (buf[0]));
871             riscv_breakpoints_debug_printf ("Using %s for breakpoint at %s %s",
872                                                     bp, paddress (gdbarch, *pcptr),
873                                                     suffix.c_str ());
874           }
875       if (unaligned_p || riscv_insn_length (buf[0]) == 2)
876           return 2;
877       else
878           return 4;
879     }
880   else if (use_compressed_breakpoints == AUTO_BOOLEAN_TRUE)
881     return 2;
882   else
883     return 4;
884 }
885 
886 /* Implement the sw_breakpoint_from_kind gdbarch method.  */
887 
888 static const gdb_byte *
riscv_sw_breakpoint_from_kind(struct gdbarch * gdbarch,int kind,int * size)889 riscv_sw_breakpoint_from_kind (struct gdbarch *gdbarch, int kind, int *size)
890 {
891   static const gdb_byte ebreak[] = { 0x73, 0x00, 0x10, 0x00, };
892   static const gdb_byte c_ebreak[] = { 0x02, 0x90 };
893 
894   *size = kind;
895   switch (kind)
896     {
897     case 2:
898       return c_ebreak;
899     case 4:
900       return ebreak;
901     default:
902       gdb_assert_not_reached ("unhandled breakpoint kind");
903     }
904 }
905 
906 /* Implement the register_name gdbarch method.  This is used instead of
907    the function supplied by calling TDESC_USE_REGISTERS so that we can
908    ensure the preferred names are offered for x-regs and f-regs.  */
909 
910 static const char *
riscv_register_name(struct gdbarch * gdbarch,int regnum)911 riscv_register_name (struct gdbarch *gdbarch, int regnum)
912 {
913   /* Lookup the name through the target description.  If we get back NULL
914      then this is an unknown register.  If we do get a name back then we
915      look up the registers preferred name below.  */
916   const char *name = tdesc_register_name (gdbarch, regnum);
917   gdb_assert (name != nullptr);
918   if (name[0] == '\0')
919     return name;
920 
921   /* We want GDB to use the ABI names for registers even if the target
922      gives us a target description with the architectural name.  For
923      example we want to see 'ra' instead of 'x1' whatever the target
924      description called it.  */
925   if (regnum >= RISCV_ZERO_REGNUM && regnum < RISCV_FIRST_FP_REGNUM)
926     return riscv_xreg_feature.register_name (regnum);
927 
928   /* Like with the x-regs we prefer the abi names for the floating point
929      registers.  If the target doesn't have floating point registers then
930      the tdesc_register_name call above should have returned an empty
931      string.  */
932   if (regnum >= RISCV_FIRST_FP_REGNUM && regnum <= RISCV_LAST_FP_REGNUM)
933     {
934       gdb_assert (riscv_has_fp_regs (gdbarch));
935       return riscv_freg_feature.register_name (regnum);
936     }
937 
938   /* Some targets (QEMU) are reporting these three registers twice, once
939      in the FPU feature, and once in the CSR feature.  Both of these read
940      the same underlying state inside the target, but naming the register
941      twice in the target description results in GDB having two registers
942      with the same name, only one of which can ever be accessed, but both
943      will show up in 'info register all'.  Unless, we identify the
944      duplicate copies of these registers (in riscv_tdesc_unknown_reg) and
945      then hide the registers here by giving them no name.  */
946   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
947   if (tdep->duplicate_fflags_regnum == regnum
948       || tdep->duplicate_frm_regnum == regnum
949       || tdep->duplicate_fcsr_regnum == regnum)
950     return "";
951 
952   /* The remaining registers are different.  For all other registers on the
953      machine we prefer to see the names that the target description
954      provides.  This is particularly important for CSRs which might be
955      renamed over time.  If GDB keeps track of the "latest" name, but a
956      particular target provides an older name then we don't want to force
957      users to see the newer name in register output.
958 
959      The other case that reaches here are any registers that the target
960      provided that GDB is completely unaware of.  For these we have no
961      choice but to accept the target description name.
962 
963      Just accept whatever name TDESC_REGISTER_NAME returned.  */
964   return name;
965 }
966 
967 /* Implement gdbarch_pseudo_register_read.  Read pseudo-register REGNUM
968    from REGCACHE and place the register value into BUF.  BUF is sized
969    based on the type of register REGNUM, all of BUF should be written too,
970    the result should be sign or zero extended as appropriate.  */
971 
972 static enum register_status
riscv_pseudo_register_read(struct gdbarch * gdbarch,readable_regcache * regcache,int regnum,gdb_byte * buf)973 riscv_pseudo_register_read (struct gdbarch *gdbarch,
974                                   readable_regcache *regcache,
975                                   int regnum, gdb_byte *buf)
976 {
977   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
978 
979   if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
980     {
981       /* Clear BUF.  */
982       memset (buf, 0, register_size (gdbarch, regnum));
983 
984       /* Read the first byte of the fcsr register, this contains both frm
985            and fflags.  */
986       enum register_status status
987           = regcache->raw_read_part (RISCV_CSR_FCSR_REGNUM, 0, 1, buf);
988 
989       if (status != REG_VALID)
990           return status;
991 
992       /* Extract the appropriate parts.  */
993       if (regnum == tdep->fflags_regnum)
994           buf[0] &= 0x1f;
995       else if (regnum == tdep->frm_regnum)
996           buf[0] = (buf[0] >> 5) & 0x7;
997 
998       return REG_VALID;
999     }
1000 
1001   return REG_UNKNOWN;
1002 }
1003 
1004 /* Implement gdbarch_deprecated_pseudo_register_write.  Write the contents of
1005    BUF into pseudo-register REGNUM in REGCACHE.  BUF is sized based on the type
1006    of register REGNUM.  */
1007 
1008 static void
riscv_pseudo_register_write(struct gdbarch * gdbarch,struct regcache * regcache,int regnum,const gdb_byte * buf)1009 riscv_pseudo_register_write (struct gdbarch *gdbarch,
1010                                    struct regcache *regcache, int regnum,
1011                                    const gdb_byte *buf)
1012 {
1013   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1014 
1015   if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1016     {
1017       int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
1018       gdb_byte raw_buf[register_size (gdbarch, fcsr_regnum)];
1019 
1020       regcache->raw_read (fcsr_regnum, raw_buf);
1021 
1022       if (regnum == tdep->fflags_regnum)
1023           raw_buf[0] = (raw_buf[0] & ~0x1f) | (buf[0] & 0x1f);
1024       else if (regnum == tdep->frm_regnum)
1025           raw_buf[0] = (raw_buf[0] & ~(0x7 << 5)) | ((buf[0] & 0x7) << 5);
1026 
1027       regcache->raw_write (fcsr_regnum, raw_buf);
1028     }
1029   else
1030     gdb_assert_not_reached ("unknown pseudo register %d", regnum);
1031 }
1032 
1033 /* Implement the cannot_store_register gdbarch method.  The zero register
1034    (x0) is read-only on RISC-V.  */
1035 
1036 static int
riscv_cannot_store_register(struct gdbarch * gdbarch,int regnum)1037 riscv_cannot_store_register (struct gdbarch *gdbarch, int regnum)
1038 {
1039   return regnum == RISCV_ZERO_REGNUM;
1040 }
1041 
1042 /* Construct a type for 64-bit FP registers.  */
1043 
1044 static struct type *
riscv_fpreg_d_type(struct gdbarch * gdbarch)1045 riscv_fpreg_d_type (struct gdbarch *gdbarch)
1046 {
1047   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1048 
1049   if (tdep->riscv_fpreg_d_type == nullptr)
1050     {
1051       const struct builtin_type *bt = builtin_type (gdbarch);
1052 
1053       /* The type we're building is this: */
1054 #if 0
1055       union __gdb_builtin_type_fpreg_d
1056       {
1057           float f;
1058           double d;
1059       };
1060 #endif
1061 
1062       struct type *t;
1063 
1064       t = arch_composite_type (gdbarch,
1065                                      "__gdb_builtin_type_fpreg_d", TYPE_CODE_UNION);
1066       append_composite_type_field (t, "float", bt->builtin_float);
1067       append_composite_type_field (t, "double", bt->builtin_double);
1068       t->set_is_vector (true);
1069       t->set_name ("builtin_type_fpreg_d");
1070       tdep->riscv_fpreg_d_type = t;
1071     }
1072 
1073   return tdep->riscv_fpreg_d_type;
1074 }
1075 
1076 /* Implement the register_type gdbarch method.  This is installed as an
1077    for the override setup by TDESC_USE_REGISTERS, for most registers we
1078    delegate the type choice to the target description, but for a few
1079    registers we try to improve the types if the target description has
1080    taken a simplistic approach.  */
1081 
1082 static struct type *
riscv_register_type(struct gdbarch * gdbarch,int regnum)1083 riscv_register_type (struct gdbarch *gdbarch, int regnum)
1084 {
1085   struct type *type = tdesc_register_type (gdbarch, regnum);
1086   int xlen = riscv_isa_xlen (gdbarch);
1087 
1088   /* We want to perform some specific type "fixes" in cases where we feel
1089      that we really can do better than the target description.  For all
1090      other cases we just return what the target description says.  */
1091   if (riscv_is_fp_regno_p (regnum))
1092     {
1093       /* This spots the case for RV64 where the double is defined as
1094            either 'ieee_double' or 'float' (which is the generic name that
1095            converts to 'double' on 64-bit).  In these cases its better to
1096            present the registers using a union type.  */
1097       int flen = riscv_isa_flen (gdbarch);
1098       if (flen == 8
1099             && type->code () == TYPE_CODE_FLT
1100             && type->length () == flen
1101             && (strcmp (type->name (), "builtin_type_ieee_double") == 0
1102                 || strcmp (type->name (), "double") == 0))
1103           type = riscv_fpreg_d_type (gdbarch);
1104     }
1105 
1106   if ((regnum == gdbarch_pc_regnum (gdbarch)
1107        || regnum == RISCV_RA_REGNUM
1108        || regnum == RISCV_FP_REGNUM
1109        || regnum == RISCV_SP_REGNUM
1110        || regnum == RISCV_GP_REGNUM
1111        || regnum == RISCV_TP_REGNUM)
1112       && type->code () == TYPE_CODE_INT
1113       && type->length () == xlen)
1114     {
1115       /* This spots the case where some interesting registers are defined
1116            as simple integers of the expected size, we force these registers
1117            to be pointers as we believe that is more useful.  */
1118       if (regnum == gdbarch_pc_regnum (gdbarch)
1119             || regnum == RISCV_RA_REGNUM)
1120           type = builtin_type (gdbarch)->builtin_func_ptr;
1121       else if (regnum == RISCV_FP_REGNUM
1122                  || regnum == RISCV_SP_REGNUM
1123                  || regnum == RISCV_GP_REGNUM
1124                  || regnum == RISCV_TP_REGNUM)
1125           type = builtin_type (gdbarch)->builtin_data_ptr;
1126     }
1127 
1128   return type;
1129 }
1130 
1131 /* Helper for riscv_print_registers_info, prints info for a single register
1132    REGNUM.  */
1133 
1134 static void
riscv_print_one_register_info(struct gdbarch * gdbarch,struct ui_file * file,const frame_info_ptr & frame,int regnum)1135 riscv_print_one_register_info (struct gdbarch *gdbarch,
1136                                      struct ui_file *file,
1137                                      const frame_info_ptr &frame,
1138                                      int regnum)
1139 {
1140   const char *name = gdbarch_register_name (gdbarch, regnum);
1141   struct value *val;
1142   struct type *regtype;
1143   int print_raw_format;
1144   enum tab_stops { value_column_1 = 15 };
1145 
1146   gdb_puts (name, file);
1147   print_spaces (std::max<int> (1, value_column_1 - strlen (name)), file);
1148 
1149   try
1150     {
1151       val = value_of_register (regnum, get_next_frame_sentinel_okay (frame));
1152       regtype = val->type ();
1153     }
1154   catch (const gdb_exception_error &ex)
1155     {
1156       /* Handle failure to read a register without interrupting the entire
1157            'info registers' flow.  */
1158       gdb_printf (file, "%s\n", ex.what ());
1159       return;
1160     }
1161 
1162   print_raw_format = (val->entirely_available ()
1163                           && !val->optimized_out ());
1164 
1165   if (regtype->code () == TYPE_CODE_FLT
1166       || (regtype->code () == TYPE_CODE_UNION
1167             && regtype->num_fields () == 2
1168             && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1169             && regtype->field (1).type ()->code () == TYPE_CODE_FLT)
1170       || (regtype->code () == TYPE_CODE_UNION
1171             && regtype->num_fields () == 3
1172             && regtype->field (0).type ()->code () == TYPE_CODE_FLT
1173             && regtype->field (1).type ()->code () == TYPE_CODE_FLT
1174             && regtype->field (2).type ()->code () == TYPE_CODE_FLT))
1175     {
1176       struct value_print_options opts;
1177       const gdb_byte *valaddr = val->contents_for_printing ().data ();
1178       enum bfd_endian byte_order = type_byte_order (regtype);
1179 
1180       get_user_print_options (&opts);
1181       opts.deref_ref = true;
1182 
1183       common_val_print (val, file, 0, &opts, current_language);
1184 
1185       if (print_raw_format)
1186           {
1187             gdb_printf (file, "\t(raw ");
1188             print_hex_chars (file, valaddr, regtype->length (), byte_order,
1189                                  true);
1190             gdb_printf (file, ")");
1191           }
1192     }
1193   else
1194     {
1195       struct value_print_options opts;
1196       riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1197 
1198       /* Print the register in hex.  */
1199       get_formatted_print_options (&opts, 'x');
1200       opts.deref_ref = true;
1201       common_val_print (val, file, 0, &opts, current_language);
1202 
1203       if (print_raw_format)
1204           {
1205             if (regnum == RISCV_CSR_MSTATUS_REGNUM)
1206               {
1207                 LONGEST d;
1208                 int size = register_size (gdbarch, regnum);
1209                 unsigned xlen;
1210 
1211                 /* The SD field is always in the upper bit of MSTATUS, regardless
1212                      of the number of bits in MSTATUS.  */
1213                 d = value_as_long (val);
1214                 xlen = size * 8;
1215                 gdb_printf (file,
1216                                 "\tSD:%X VM:%02X MXR:%X PUM:%X MPRV:%X XS:%X "
1217                                 "FS:%X MPP:%x HPP:%X SPP:%X MPIE:%X HPIE:%X "
1218                                 "SPIE:%X UPIE:%X MIE:%X HIE:%X SIE:%X UIE:%X",
1219                                 (int) ((d >> (xlen - 1)) & 0x1),
1220                                 (int) ((d >> 24) & 0x1f),
1221                                 (int) ((d >> 19) & 0x1),
1222                                 (int) ((d >> 18) & 0x1),
1223                                 (int) ((d >> 17) & 0x1),
1224                                 (int) ((d >> 15) & 0x3),
1225                                 (int) ((d >> 13) & 0x3),
1226                                 (int) ((d >> 11) & 0x3),
1227                                 (int) ((d >> 9) & 0x3),
1228                                 (int) ((d >> 8) & 0x1),
1229                                 (int) ((d >> 7) & 0x1),
1230                                 (int) ((d >> 6) & 0x1),
1231                                 (int) ((d >> 5) & 0x1),
1232                                 (int) ((d >> 4) & 0x1),
1233                                 (int) ((d >> 3) & 0x1),
1234                                 (int) ((d >> 2) & 0x1),
1235                                 (int) ((d >> 1) & 0x1),
1236                                 (int) ((d >> 0) & 0x1));
1237               }
1238             else if (regnum == RISCV_CSR_MISA_REGNUM)
1239               {
1240                 int base;
1241                 unsigned xlen, i;
1242                 LONGEST d;
1243                 int size = register_size (gdbarch, regnum);
1244 
1245                 /* The MXL field is always in the upper two bits of MISA,
1246                      regardless of the number of bits in MISA.  Mask out other
1247                      bits to ensure we have a positive value.  */
1248                 d = value_as_long (val);
1249                 base = (d >> ((size * 8) - 2)) & 0x3;
1250                 xlen = 16;
1251 
1252                 for (; base > 0; base--)
1253                     xlen *= 2;
1254                 gdb_printf (file, "\tRV%d", xlen);
1255 
1256                 for (i = 0; i < 26; i++)
1257                     {
1258                       if (d & (1 << i))
1259                         gdb_printf (file, "%c", 'A' + i);
1260                     }
1261               }
1262             else if (regnum == RISCV_CSR_FCSR_REGNUM
1263                        || regnum == tdep->fflags_regnum
1264                        || regnum == tdep->frm_regnum)
1265               {
1266                 LONGEST d = value_as_long (val);
1267 
1268                 gdb_printf (file, "\t");
1269                 if (regnum != tdep->frm_regnum)
1270                     gdb_printf (file,
1271                                   "NV:%d DZ:%d OF:%d UF:%d NX:%d",
1272                                   (int) ((d >> 4) & 0x1),
1273                                   (int) ((d >> 3) & 0x1),
1274                                   (int) ((d >> 2) & 0x1),
1275                                   (int) ((d >> 1) & 0x1),
1276                                   (int) ((d >> 0) & 0x1));
1277 
1278                 if (regnum != tdep->fflags_regnum)
1279                     {
1280                       static const char * const sfrm[] =
1281                         {
1282                           _("RNE (round to nearest; ties to even)"),
1283                           _("RTZ (Round towards zero)"),
1284                           _("RDN (Round down towards -INF)"),
1285                           _("RUP (Round up towards +INF)"),
1286                           _("RMM (Round to nearest; ties to max magnitude)"),
1287                           _("INVALID[5]"),
1288                           _("INVALID[6]"),
1289                           /* A value of 0x7 indicates dynamic rounding mode when
1290                                used within an instructions rounding-mode field, but
1291                                is invalid within the FRM register.  */
1292                           _("INVALID[7] (Dynamic rounding mode)"),
1293                         };
1294                       int frm = ((regnum == RISCV_CSR_FCSR_REGNUM)
1295                                    ? (d >> 5) : d) & 0x7;
1296 
1297                       gdb_printf (file, "%sFRM:%i [%s]",
1298                                     (regnum == RISCV_CSR_FCSR_REGNUM
1299                                      ? " " : ""),
1300                                     frm, sfrm[frm]);
1301                     }
1302               }
1303             else if (regnum == RISCV_PRIV_REGNUM)
1304               {
1305                 LONGEST d;
1306                 uint8_t priv;
1307 
1308                 d = value_as_long (val);
1309                 priv = d & 0xff;
1310 
1311                 if (priv < 4)
1312                     {
1313                       static const char * const sprv[] =
1314                         {
1315                           "User/Application",
1316                           "Supervisor",
1317                           "Hypervisor",
1318                           "Machine"
1319                         };
1320                       gdb_printf (file, "\tprv:%d [%s]",
1321                                     priv, sprv[priv]);
1322                     }
1323                 else
1324                     gdb_printf (file, "\tprv:%d [INVALID]", priv);
1325               }
1326             else
1327               {
1328                 /* If not a vector register, print it also according to its
1329                      natural format.  */
1330                 if (regtype->is_vector () == 0)
1331                     {
1332                       get_user_print_options (&opts);
1333                       opts.deref_ref = true;
1334                       gdb_printf (file, "\t");
1335                       common_val_print (val, file, 0, &opts, current_language);
1336                     }
1337               }
1338           }
1339     }
1340   gdb_printf (file, "\n");
1341 }
1342 
1343 /* Return true if REGNUM is a valid CSR register.  The CSR register space
1344    is sparsely populated, so not every number is a named CSR.  */
1345 
1346 static bool
riscv_is_regnum_a_named_csr(int regnum)1347 riscv_is_regnum_a_named_csr (int regnum)
1348 {
1349   gdb_assert (regnum >= RISCV_FIRST_CSR_REGNUM
1350                 && regnum <= RISCV_LAST_CSR_REGNUM);
1351 
1352   switch (regnum)
1353     {
1354 #define DECLARE_CSR(name, num, class, define_ver, abort_ver) case RISCV_ ## num ## _REGNUM:
1355 #include "opcode/riscv-opc.h"
1356 #undef DECLARE_CSR
1357       return true;
1358 
1359     default:
1360       return false;
1361     }
1362 }
1363 
1364 /* Return true if REGNUM is an unknown CSR identified in
1365    riscv_tdesc_unknown_reg for GDBARCH.  */
1366 
1367 static bool
riscv_is_unknown_csr(struct gdbarch * gdbarch,int regnum)1368 riscv_is_unknown_csr (struct gdbarch *gdbarch, int regnum)
1369 {
1370   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1371   return (regnum >= tdep->unknown_csrs_first_regnum
1372             && regnum < (tdep->unknown_csrs_first_regnum
1373                            + tdep->unknown_csrs_count));
1374 }
1375 
1376 /* Implement the register_reggroup_p gdbarch method.  Is REGNUM a member
1377    of REGGROUP?  */
1378 
1379 static int
riscv_register_reggroup_p(struct gdbarch * gdbarch,int regnum,const struct reggroup * reggroup)1380 riscv_register_reggroup_p (struct gdbarch  *gdbarch, int regnum,
1381                                  const struct reggroup *reggroup)
1382 {
1383   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1384 
1385   /* Used by 'info registers' and 'info registers <groupname>'.  */
1386 
1387   if (gdbarch_register_name (gdbarch, regnum)[0] == '\0')
1388     return 0;
1389 
1390   if (regnum > RISCV_LAST_REGNUM && regnum < gdbarch_num_regs (gdbarch))
1391     {
1392       /* Any extra registers from the CSR tdesc_feature (identified in
1393            riscv_tdesc_unknown_reg) are removed from the save/restore groups
1394            as some targets (QEMU) report CSRs which then can't be read and
1395            having unreadable registers in the save/restore group breaks
1396            things like inferior calls.
1397 
1398            The unknown CSRs are also removed from the general group, and
1399            added into both the csr and system group.  This is inline with the
1400            known CSRs (see below).  */
1401       if (riscv_is_unknown_csr (gdbarch, regnum))
1402           {
1403             if (reggroup == restore_reggroup || reggroup == save_reggroup
1404                  || reggroup == general_reggroup)
1405               return 0;
1406             else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1407               return 1;
1408           }
1409 
1410       /* This is some other unknown register from the target description.
1411            In this case we trust whatever the target description says about
1412            which groups this register should be in.  */
1413       int ret = tdesc_register_in_reggroup_p (gdbarch, regnum, reggroup);
1414       if (ret != -1)
1415           return ret;
1416 
1417       return default_register_reggroup_p (gdbarch, regnum, reggroup);
1418     }
1419 
1420   if (reggroup == all_reggroup)
1421     {
1422       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum >= RISCV_PRIV_REGNUM)
1423           return 1;
1424       if (riscv_is_regnum_a_named_csr (regnum))
1425           return 1;
1426       return 0;
1427     }
1428   else if (reggroup == float_reggroup)
1429     return (riscv_is_fp_regno_p (regnum)
1430               || regnum == RISCV_CSR_FCSR_REGNUM
1431               || regnum == tdep->fflags_regnum
1432               || regnum == tdep->frm_regnum);
1433   else if (reggroup == general_reggroup)
1434     return regnum < RISCV_FIRST_FP_REGNUM;
1435   else if (reggroup == restore_reggroup || reggroup == save_reggroup)
1436     {
1437       if (riscv_has_fp_regs (gdbarch))
1438           return (regnum <= RISCV_LAST_FP_REGNUM
1439                     || regnum == RISCV_CSR_FCSR_REGNUM
1440                     || regnum == tdep->fflags_regnum
1441                     || regnum == tdep->frm_regnum);
1442       else
1443           return regnum < RISCV_FIRST_FP_REGNUM;
1444     }
1445   else if (reggroup == system_reggroup || reggroup == csr_reggroup)
1446     {
1447       if (regnum == RISCV_PRIV_REGNUM)
1448           return 1;
1449       if (regnum < RISCV_FIRST_CSR_REGNUM || regnum > RISCV_LAST_CSR_REGNUM)
1450           return 0;
1451       if (riscv_is_regnum_a_named_csr (regnum))
1452           return 1;
1453       return 0;
1454     }
1455   else if (reggroup == vector_reggroup)
1456     return (regnum >= RISCV_V0_REGNUM && regnum <= RISCV_V31_REGNUM);
1457   else
1458     return 0;
1459 }
1460 
1461 /* Return the name for pseudo-register REGNUM for GDBARCH.  */
1462 
1463 static const char *
riscv_pseudo_register_name(struct gdbarch * gdbarch,int regnum)1464 riscv_pseudo_register_name (struct gdbarch *gdbarch, int regnum)
1465 {
1466   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1467 
1468   if (regnum == tdep->fflags_regnum)
1469     return "fflags";
1470   else if (regnum == tdep->frm_regnum)
1471     return "frm";
1472   else
1473     gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1474 }
1475 
1476 /* Return the type for pseudo-register REGNUM for GDBARCH.  */
1477 
1478 static struct type *
riscv_pseudo_register_type(struct gdbarch * gdbarch,int regnum)1479 riscv_pseudo_register_type (struct gdbarch *gdbarch, int regnum)
1480 {
1481   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
1482 
1483   if (regnum == tdep->fflags_regnum || regnum == tdep->frm_regnum)
1484    return builtin_type (gdbarch)->builtin_int32;
1485   else
1486     gdb_assert_not_reached ("unknown pseudo register number %d", regnum);
1487 }
1488 
1489 /* Return true (non-zero) if pseudo-register REGNUM from GDBARCH is a
1490    member of REGGROUP, otherwise return false (zero).  */
1491 
1492 static int
riscv_pseudo_register_reggroup_p(struct gdbarch * gdbarch,int regnum,const struct reggroup * reggroup)1493 riscv_pseudo_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
1494                                           const struct reggroup *reggroup)
1495 {
1496   /* The standard function will also work for pseudo-registers.  */
1497   return riscv_register_reggroup_p (gdbarch, regnum, reggroup);
1498 }
1499 
1500 /* Implement the print_registers_info gdbarch method.  This is used by
1501    'info registers' and 'info all-registers'.  */
1502 
1503 static void
riscv_print_registers_info(struct gdbarch * gdbarch,struct ui_file * file,const frame_info_ptr & frame,int regnum,int print_all)1504 riscv_print_registers_info (struct gdbarch *gdbarch,
1505                                   struct ui_file *file,
1506                                   const frame_info_ptr &frame,
1507                                   int regnum, int print_all)
1508 {
1509   if (regnum != -1)
1510     {
1511       /* Print one specified register.  */
1512       if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1513           error (_("Not a valid register for the current processor type"));
1514       riscv_print_one_register_info (gdbarch, file, frame, regnum);
1515     }
1516   else
1517     {
1518       const struct reggroup *reggroup;
1519 
1520       if (print_all)
1521           reggroup = all_reggroup;
1522       else
1523           reggroup = general_reggroup;
1524 
1525       for (regnum = 0; regnum < gdbarch_num_cooked_regs (gdbarch); ++regnum)
1526           {
1527             /* Zero never changes, so might as well hide by default.  */
1528             if (regnum == RISCV_ZERO_REGNUM && !print_all)
1529               continue;
1530 
1531             /* Registers with no name are not valid on this ISA.  */
1532             if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1533               continue;
1534 
1535             /* Is the register in the group we're interested in?  */
1536             if (!gdbarch_register_reggroup_p (gdbarch, regnum, reggroup))
1537               continue;
1538 
1539             riscv_print_one_register_info (gdbarch, file, frame, regnum);
1540           }
1541     }
1542 }
1543 
1544 /* Class that handles one decoded RiscV instruction.  */
1545 
1546 class riscv_insn
1547 {
1548 public:
1549 
1550   /* Enum of all the opcodes that GDB cares about during the prologue scan.  */
1551   enum opcode
1552     {
1553       /* Unknown value is used at initialisation time.  */
1554       UNKNOWN = 0,
1555 
1556       /* These instructions are all the ones we are interested in during the
1557            prologue scan.  */
1558       ADD,
1559       ADDI,
1560       ADDIW,
1561       ADDW,
1562       AUIPC,
1563       LUI,
1564       LI,
1565       SD,
1566       SW,
1567       LD,
1568       LW,
1569       MV,
1570       /* These are needed for software breakpoint support.  */
1571       JAL,
1572       JALR,
1573       BEQ,
1574       BNE,
1575       BLT,
1576       BGE,
1577       BLTU,
1578       BGEU,
1579       /* These are needed for stepping over atomic sequences.  */
1580       SLTI,
1581       SLTIU,
1582       XORI,
1583       ORI,
1584       ANDI,
1585       SLLI,
1586       SLLIW,
1587       SRLI,
1588       SRLIW,
1589       SRAI,
1590       SRAIW,
1591       SUB,
1592       SUBW,
1593       SLL,
1594       SLLW,
1595       SLT,
1596       SLTU,
1597       XOR,
1598       SRL,
1599       SRLW,
1600       SRA,
1601       SRAW,
1602       OR,
1603       AND,
1604       LR_W,
1605       LR_D,
1606       SC_W,
1607       SC_D,
1608       /* This instruction is used to do a syscall.  */
1609       ECALL,
1610 
1611       /* Other instructions are not interesting during the prologue scan, and
1612            are ignored.  */
1613       OTHER
1614     };
1615 
riscv_insn()1616   riscv_insn ()
1617     : m_length (0),
1618       m_opcode (OTHER),
1619       m_rd (0),
1620       m_rs1 (0),
1621       m_rs2 (0)
1622   {
1623     /* Nothing.  */
1624   }
1625 
1626   void decode (struct gdbarch *gdbarch, CORE_ADDR pc);
1627 
1628   /* Get the length of the instruction in bytes.  */
length()1629   int length () const
1630   { return m_length; }
1631 
1632   /* Get the opcode for this instruction.  */
opcode()1633   enum opcode opcode () const
1634   { return m_opcode; }
1635 
1636   /* Get destination register field for this instruction.  This is only
1637      valid if the OPCODE implies there is such a field for this
1638      instruction.  */
rd()1639   int rd () const
1640   { return m_rd; }
1641 
1642   /* Get the RS1 register field for this instruction.  This is only valid
1643      if the OPCODE implies there is such a field for this instruction.  */
rs1()1644   int rs1 () const
1645   { return m_rs1; }
1646 
1647   /* Get the RS2 register field for this instruction.  This is only valid
1648      if the OPCODE implies there is such a field for this instruction.  */
rs2()1649   int rs2 () const
1650   { return m_rs2; }
1651 
1652   /* Get the immediate for this instruction in signed form.  This is only
1653      valid if the OPCODE implies there is such a field for this
1654      instruction.  */
imm_signed()1655   int imm_signed () const
1656   { return m_imm.s; }
1657 
1658 private:
1659 
1660   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
decode_register_index(unsigned long opcode,int offset)1661   int decode_register_index (unsigned long opcode, int offset)
1662   {
1663     return (opcode >> offset) & 0x1F;
1664   }
1665 
1666   /* Extract 5 bit register field at OFFSET from instruction OPCODE.  */
decode_register_index_short(unsigned long opcode,int offset)1667   int decode_register_index_short (unsigned long opcode, int offset)
1668   {
1669     return ((opcode >> offset) & 0x7) + 8;
1670   }
1671 
1672   /* Helper for DECODE, decode 32-bit R-type instruction.  */
decode_r_type_insn(enum opcode opcode,ULONGEST ival)1673   void decode_r_type_insn (enum opcode opcode, ULONGEST ival)
1674   {
1675     m_opcode = opcode;
1676     m_rd = decode_register_index (ival, OP_SH_RD);
1677     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1678     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1679   }
1680 
1681   /* Helper for DECODE, decode 16-bit compressed R-type instruction.  */
decode_cr_type_insn(enum opcode opcode,ULONGEST ival)1682   void decode_cr_type_insn (enum opcode opcode, ULONGEST ival)
1683   {
1684     m_opcode = opcode;
1685     m_rd = m_rs1 = decode_register_index (ival, OP_SH_CRS1S);
1686     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1687   }
1688 
1689   /* Helper for DECODE, decode 32-bit I-type instruction.  */
decode_i_type_insn(enum opcode opcode,ULONGEST ival)1690   void decode_i_type_insn (enum opcode opcode, ULONGEST ival)
1691   {
1692     m_opcode = opcode;
1693     m_rd = decode_register_index (ival, OP_SH_RD);
1694     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1695     m_imm.s = EXTRACT_ITYPE_IMM (ival);
1696   }
1697 
1698   /* Helper for DECODE, decode 16-bit compressed I-type instruction.  Some
1699      of the CI instruction have a hard-coded rs1 register, while others
1700      just use rd for both the source and destination.  RS1_REGNUM, if
1701      passed, is the value to place in rs1, otherwise rd is duplicated into
1702      rs1.  */
1703   void decode_ci_type_insn (enum opcode opcode, ULONGEST ival,
1704                                   std::optional<int> rs1_regnum = {})
1705   {
1706     m_opcode = opcode;
1707     m_rd = decode_register_index (ival, OP_SH_CRS1S);
1708     if (rs1_regnum.has_value ())
1709       m_rs1 = *rs1_regnum;
1710     else
1711       m_rs1 = m_rd;
1712     m_imm.s = EXTRACT_CITYPE_IMM (ival);
1713   }
1714 
1715   /* Helper for DECODE, decode 16-bit compressed CL-type instruction.  */
decode_cl_type_insn(enum opcode opcode,ULONGEST ival)1716   void decode_cl_type_insn (enum opcode opcode, ULONGEST ival)
1717   {
1718     m_opcode = opcode;
1719     m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
1720     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1721     m_imm.s = EXTRACT_CLTYPE_IMM (ival);
1722   }
1723 
1724   /* Helper for DECODE, decode 32-bit S-type instruction.  */
decode_s_type_insn(enum opcode opcode,ULONGEST ival)1725   void decode_s_type_insn (enum opcode opcode, ULONGEST ival)
1726   {
1727     m_opcode = opcode;
1728     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1729     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1730     m_imm.s = EXTRACT_STYPE_IMM (ival);
1731   }
1732 
1733   /* Helper for DECODE, decode 16-bit CS-type instruction.  The immediate
1734      encoding is different for each CS format instruction, so extracting
1735      the immediate is left up to the caller, who should pass the extracted
1736      immediate value through in IMM.  */
decode_cs_type_insn(enum opcode opcode,ULONGEST ival,int imm)1737   void decode_cs_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1738   {
1739     m_opcode = opcode;
1740     m_imm.s = imm;
1741     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1742     m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1743   }
1744 
1745   /* Helper for DECODE, decode 16-bit CSS-type instruction.  The immediate
1746      encoding is different for each CSS format instruction, so extracting
1747      the immediate is left up to the caller, who should pass the extracted
1748      immediate value through in IMM.  */
decode_css_type_insn(enum opcode opcode,ULONGEST ival,int imm)1749   void decode_css_type_insn (enum opcode opcode, ULONGEST ival, int imm)
1750   {
1751     m_opcode = opcode;
1752     m_imm.s = imm;
1753     m_rs1 = RISCV_SP_REGNUM;
1754     /* Not a compressed register number in this case.  */
1755     m_rs2 = decode_register_index (ival, OP_SH_CRS2);
1756   }
1757 
1758   /* Helper for DECODE, decode 32-bit U-type instruction.  */
decode_u_type_insn(enum opcode opcode,ULONGEST ival)1759   void decode_u_type_insn (enum opcode opcode, ULONGEST ival)
1760   {
1761     m_opcode = opcode;
1762     m_rd = decode_register_index (ival, OP_SH_RD);
1763     m_imm.s = EXTRACT_UTYPE_IMM (ival);
1764   }
1765 
1766   /* Helper for DECODE, decode 32-bit J-type instruction.  */
decode_j_type_insn(enum opcode opcode,ULONGEST ival)1767   void decode_j_type_insn (enum opcode opcode, ULONGEST ival)
1768   {
1769     m_opcode = opcode;
1770     m_rd = decode_register_index (ival, OP_SH_RD);
1771     m_imm.s = EXTRACT_JTYPE_IMM (ival);
1772   }
1773 
1774   /* Helper for DECODE, decode 32-bit J-type instruction.  */
decode_cj_type_insn(enum opcode opcode,ULONGEST ival)1775   void decode_cj_type_insn (enum opcode opcode, ULONGEST ival)
1776   {
1777     m_opcode = opcode;
1778     m_imm.s = EXTRACT_CJTYPE_IMM (ival);
1779   }
1780 
decode_b_type_insn(enum opcode opcode,ULONGEST ival)1781   void decode_b_type_insn (enum opcode opcode, ULONGEST ival)
1782   {
1783     m_opcode = opcode;
1784     m_rs1 = decode_register_index (ival, OP_SH_RS1);
1785     m_rs2 = decode_register_index (ival, OP_SH_RS2);
1786     m_imm.s = EXTRACT_BTYPE_IMM (ival);
1787   }
1788 
decode_cb_type_insn(enum opcode opcode,ULONGEST ival)1789   void decode_cb_type_insn (enum opcode opcode, ULONGEST ival)
1790   {
1791     m_opcode = opcode;
1792     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1793     m_imm.s = EXTRACT_CBTYPE_IMM (ival);
1794   }
1795 
decode_ca_type_insn(enum opcode opcode,ULONGEST ival)1796   void decode_ca_type_insn (enum opcode opcode, ULONGEST ival)
1797   {
1798     m_opcode = opcode;
1799     m_rs1 = decode_register_index_short (ival, OP_SH_CRS1S);
1800     m_rs2 = decode_register_index_short (ival, OP_SH_CRS2S);
1801   }
1802 
1803   /* Fetch instruction from target memory at ADDR, return the content of
1804      the instruction, and update LEN with the instruction length.  */
1805   static ULONGEST fetch_instruction (struct gdbarch *gdbarch,
1806                                              CORE_ADDR addr, int *len);
1807 
1808   /* The length of the instruction in bytes.  Should be 2 or 4.  */
1809   int m_length;
1810 
1811   /* The instruction opcode.  */
1812   enum opcode m_opcode;
1813 
1814   /* The three possible registers an instruction might reference.  Not
1815      every instruction fills in all of these registers.  Which fields are
1816      valid depends on the opcode.  The naming of these fields matches the
1817      naming in the riscv isa manual.  */
1818   int m_rd;
1819   int m_rs1;
1820   int m_rs2;
1821 
1822   /* Possible instruction immediate.  This is only valid if the instruction
1823      format contains an immediate, not all instruction, whether this is
1824      valid depends on the opcode.  Despite only having one format for now
1825      the immediate is packed into a union, later instructions might require
1826      an unsigned formatted immediate, having the union in place now will
1827      reduce the need for code churn later.  */
1828   union riscv_insn_immediate
1829   {
riscv_insn_immediate()1830     riscv_insn_immediate ()
1831       : s (0)
1832     {
1833       /* Nothing.  */
1834     }
1835 
1836     int s;
1837   } m_imm;
1838 };
1839 
1840 /* Fetch instruction from target memory at ADDR, return the content of the
1841    instruction, and update LEN with the instruction length.  */
1842 
1843 ULONGEST
fetch_instruction(struct gdbarch * gdbarch,CORE_ADDR addr,int * len)1844 riscv_insn::fetch_instruction (struct gdbarch *gdbarch,
1845                                      CORE_ADDR addr, int *len)
1846 {
1847   gdb_byte buf[RISCV_MAX_INSN_LEN];
1848   int instlen, status;
1849 
1850   /* All insns are at least 16 bits.  */
1851   status = target_read_memory (addr, buf, 2);
1852   if (status)
1853     memory_error (TARGET_XFER_E_IO, addr);
1854 
1855   /* If we need more, grab it now.  */
1856   instlen = riscv_insn_length (buf[0]);
1857   gdb_assert (instlen <= sizeof (buf));
1858   *len = instlen;
1859 
1860   if (instlen > 2)
1861     {
1862       status = target_read_memory (addr + 2, buf + 2, instlen - 2);
1863       if (status)
1864           memory_error (TARGET_XFER_E_IO, addr + 2);
1865     }
1866 
1867   /* RISC-V Specification states instructions are always little endian */
1868   return extract_unsigned_integer (buf, instlen, BFD_ENDIAN_LITTLE);
1869 }
1870 
1871 /* Fetch from target memory an instruction at PC and decode it.  This can
1872    throw an error if the memory access fails, callers are responsible for
1873    handling this error if that is appropriate.  */
1874 
1875 void
decode(struct gdbarch * gdbarch,CORE_ADDR pc)1876 riscv_insn::decode (struct gdbarch *gdbarch, CORE_ADDR pc)
1877 {
1878   ULONGEST ival;
1879 
1880   /* Fetch the instruction, and the instructions length.  */
1881   ival = fetch_instruction (gdbarch, pc, &m_length);
1882 
1883   if (m_length == 4)
1884     {
1885       if (is_add_insn (ival))
1886           decode_r_type_insn (ADD, ival);
1887       else if (is_addw_insn (ival))
1888           decode_r_type_insn (ADDW, ival);
1889       else if (is_addi_insn (ival))
1890           decode_i_type_insn (ADDI, ival);
1891       else if (is_addiw_insn (ival))
1892           decode_i_type_insn (ADDIW, ival);
1893       else if (is_auipc_insn (ival))
1894           decode_u_type_insn (AUIPC, ival);
1895       else if (is_lui_insn (ival))
1896           decode_u_type_insn (LUI, ival);
1897       else if (is_sd_insn (ival))
1898           decode_s_type_insn (SD, ival);
1899       else if (is_sw_insn (ival))
1900           decode_s_type_insn (SW, ival);
1901       else if (is_jal_insn (ival))
1902           decode_j_type_insn (JAL, ival);
1903       else if (is_jalr_insn (ival))
1904           decode_i_type_insn (JALR, ival);
1905       else if (is_beq_insn (ival))
1906           decode_b_type_insn (BEQ, ival);
1907       else if (is_bne_insn (ival))
1908           decode_b_type_insn (BNE, ival);
1909       else if (is_blt_insn (ival))
1910           decode_b_type_insn (BLT, ival);
1911       else if (is_bge_insn (ival))
1912           decode_b_type_insn (BGE, ival);
1913       else if (is_bltu_insn (ival))
1914           decode_b_type_insn (BLTU, ival);
1915       else if (is_bgeu_insn (ival))
1916           decode_b_type_insn (BGEU, ival);
1917       else if (is_slti_insn(ival))
1918           decode_i_type_insn (SLTI, ival);
1919       else if (is_sltiu_insn(ival))
1920           decode_i_type_insn (SLTIU, ival);
1921       else if (is_xori_insn(ival))
1922           decode_i_type_insn (XORI, ival);
1923       else if (is_ori_insn(ival))
1924           decode_i_type_insn (ORI, ival);
1925       else if (is_andi_insn(ival))
1926           decode_i_type_insn (ANDI, ival);
1927       else if (is_slli_insn(ival))
1928           decode_i_type_insn (SLLI, ival);
1929       else if (is_slliw_insn(ival))
1930           decode_i_type_insn (SLLIW, ival);
1931       else if (is_srli_insn(ival))
1932           decode_i_type_insn (SRLI, ival);
1933       else if (is_srliw_insn(ival))
1934           decode_i_type_insn (SRLIW, ival);
1935       else if (is_srai_insn(ival))
1936           decode_i_type_insn (SRAI, ival);
1937       else if (is_sraiw_insn(ival))
1938           decode_i_type_insn (SRAIW, ival);
1939       else if (is_sub_insn(ival))
1940           decode_r_type_insn (SUB, ival);
1941       else if (is_subw_insn(ival))
1942           decode_r_type_insn (SUBW, ival);
1943       else if (is_sll_insn(ival))
1944           decode_r_type_insn (SLL, ival);
1945       else if (is_sllw_insn(ival))
1946           decode_r_type_insn (SLLW, ival);
1947       else if (is_slt_insn(ival))
1948           decode_r_type_insn (SLT, ival);
1949       else if (is_sltu_insn(ival))
1950           decode_r_type_insn (SLTU, ival);
1951       else if (is_xor_insn(ival))
1952           decode_r_type_insn (XOR, ival);
1953       else if (is_srl_insn(ival))
1954           decode_r_type_insn (SRL, ival);
1955       else if (is_srlw_insn(ival))
1956           decode_r_type_insn (SRLW, ival);
1957       else if (is_sra_insn(ival))
1958           decode_r_type_insn (SRA, ival);
1959       else if (is_sraw_insn(ival))
1960           decode_r_type_insn (SRAW, ival);
1961       else if (is_or_insn(ival))
1962           decode_r_type_insn (OR, ival);
1963       else if (is_and_insn(ival))
1964           decode_r_type_insn (AND, ival);
1965       else if (is_lr_w_insn (ival))
1966           decode_r_type_insn (LR_W, ival);
1967       else if (is_lr_d_insn (ival))
1968           decode_r_type_insn (LR_D, ival);
1969       else if (is_sc_w_insn (ival))
1970           decode_r_type_insn (SC_W, ival);
1971       else if (is_sc_d_insn (ival))
1972           decode_r_type_insn (SC_D, ival);
1973       else if (is_ecall_insn (ival))
1974           decode_i_type_insn (ECALL, ival);
1975       else if (is_ld_insn (ival))
1976           decode_i_type_insn (LD, ival);
1977       else if (is_lw_insn (ival))
1978           decode_i_type_insn (LW, ival);
1979       else
1980           /* None of the other fields are valid in this case.  */
1981           m_opcode = OTHER;
1982     }
1983   else if (m_length == 2)
1984     {
1985       int xlen = riscv_isa_xlen (gdbarch);
1986 
1987       /* C_ADD and C_JALR have the same opcode.  If RS2 is 0, then this is a
1988            C_JALR.  So must try to match C_JALR first as it has more bits in
1989            mask.  */
1990       if (is_c_jalr_insn (ival))
1991           decode_cr_type_insn (JALR, ival);
1992       else if (is_c_add_insn (ival))
1993           decode_cr_type_insn (ADD, ival);
1994       /* C_ADDW is RV64 and RV128 only.  */
1995       else if (xlen != 4 && is_c_addw_insn (ival))
1996           decode_cr_type_insn (ADDW, ival);
1997       else if (is_c_addi_insn (ival))
1998           decode_ci_type_insn (ADDI, ival);
1999       /* C_ADDIW and C_JAL have the same opcode.  C_ADDIW is RV64 and RV128
2000            only and C_JAL is RV32 only.  */
2001       else if (xlen != 4 && is_c_addiw_insn (ival))
2002           decode_ci_type_insn (ADDIW, ival);
2003       else if (xlen == 4 && is_c_jal_insn (ival))
2004           decode_cj_type_insn (JAL, ival);
2005       /* C_ADDI16SP and C_LUI have the same opcode.  If RD is 2, then this is a
2006            C_ADDI16SP.  So must try to match C_ADDI16SP first as it has more bits
2007            in mask.  */
2008       else if (is_c_addi16sp_insn (ival))
2009           {
2010             m_opcode = ADDI;
2011             m_rd = m_rs1 = decode_register_index (ival, OP_SH_RD);
2012             m_imm.s = EXTRACT_CITYPE_ADDI16SP_IMM (ival);
2013           }
2014       else if (is_c_addi4spn_insn (ival))
2015           {
2016             m_opcode = ADDI;
2017             m_rd = decode_register_index_short (ival, OP_SH_CRS2S);
2018             m_rs1 = RISCV_SP_REGNUM;
2019             m_imm.s = EXTRACT_CIWTYPE_ADDI4SPN_IMM (ival);
2020           }
2021       else if (is_c_lui_insn (ival))
2022           {
2023             m_opcode = LUI;
2024             m_rd = decode_register_index (ival, OP_SH_CRS1S);
2025             m_imm.s = EXTRACT_CITYPE_LUI_IMM (ival);
2026           }
2027       else if (is_c_srli_insn (ival))
2028           decode_cb_type_insn (SRLI, ival);
2029       else if (is_c_srai_insn (ival))
2030           decode_cb_type_insn (SRAI, ival);
2031       else if (is_c_andi_insn (ival))
2032           decode_cb_type_insn (ANDI, ival);
2033       else if (is_c_sub_insn (ival))
2034           decode_ca_type_insn (SUB, ival);
2035       else if (is_c_xor_insn (ival))
2036           decode_ca_type_insn (XOR, ival);
2037       else if (is_c_or_insn (ival))
2038           decode_ca_type_insn (OR, ival);
2039       else if (is_c_and_insn (ival))
2040           decode_ca_type_insn (AND, ival);
2041       else if (is_c_subw_insn (ival))
2042           decode_ca_type_insn (SUBW, ival);
2043       else if (is_c_addw_insn (ival))
2044           decode_ca_type_insn (ADDW, ival);
2045       else if (is_c_li_insn (ival))
2046           decode_ci_type_insn (LI, ival);
2047       /* C_SD and C_FSW have the same opcode.  C_SD is RV64 and RV128 only,
2048            and C_FSW is RV32 only.  */
2049       else if (xlen != 4 && is_c_sd_insn (ival))
2050           decode_cs_type_insn (SD, ival, EXTRACT_CLTYPE_LD_IMM (ival));
2051       else if (is_c_sw_insn (ival))
2052           decode_cs_type_insn (SW, ival, EXTRACT_CLTYPE_LW_IMM (ival));
2053       else if (is_c_swsp_insn (ival))
2054           decode_css_type_insn (SW, ival, EXTRACT_CSSTYPE_SWSP_IMM (ival));
2055       else if (xlen != 4 && is_c_sdsp_insn (ival))
2056           decode_css_type_insn (SD, ival, EXTRACT_CSSTYPE_SDSP_IMM (ival));
2057       /* C_JR and C_MV have the same opcode.  If RS2 is 0, then this is a C_JR.
2058            So must try to match C_JR first as it has more bits in mask.  */
2059       else if (is_c_jr_insn (ival))
2060           decode_cr_type_insn (JALR, ival);
2061       else if (is_c_mv_insn (ival))
2062           decode_cr_type_insn (MV, ival);
2063       else if (is_c_j_insn (ival))
2064           decode_cj_type_insn (JAL, ival);
2065       else if (is_c_beqz_insn (ival))
2066           decode_cb_type_insn (BEQ, ival);
2067       else if (is_c_bnez_insn (ival))
2068           decode_cb_type_insn (BNE, ival);
2069       else if (is_c_ld_insn (ival))
2070           decode_cl_type_insn (LD, ival);
2071       else if (is_c_lw_insn (ival))
2072           decode_cl_type_insn (LW, ival);
2073       else if (is_c_ldsp_insn (ival))
2074           decode_ci_type_insn (LD, ival, RISCV_SP_REGNUM);
2075       else if (is_c_lwsp_insn (ival))
2076           decode_ci_type_insn (LW, ival, RISCV_SP_REGNUM);
2077       else
2078           /* None of the other fields of INSN are valid in this case.  */
2079           m_opcode = OTHER;
2080     }
2081   else
2082     {
2083       /* 6 bytes or more.  If the instruction is longer than 8 bytes, we don't
2084            have full instruction bits in ival.  At least, such long instructions
2085            are not defined yet, so just ignore it.  */
2086       gdb_assert (m_length > 0 && m_length % 2 == 0);
2087       m_opcode = OTHER;
2088     }
2089 }
2090 
2091 /* Return true if INSN represents an instruction something like:
2092 
2093    ld fp,IMMEDIATE(sp)
2094 
2095    That is, a load from stack-pointer plus some immediate offset, with the
2096    result stored into the frame pointer.  We also accept 'lw' as well as
2097    'ld'.  */
2098 
2099 static bool
is_insn_load_of_fp_from_sp(const struct riscv_insn & insn)2100 is_insn_load_of_fp_from_sp (const struct riscv_insn &insn)
2101 {
2102   return ((insn.opcode () == riscv_insn::LD
2103              || insn.opcode () == riscv_insn::LW)
2104             && insn.rd () == RISCV_FP_REGNUM
2105             && insn.rs1 () == RISCV_SP_REGNUM);
2106 }
2107 
2108 /* Return true if INSN represents an instruction something like:
2109 
2110    add sp,sp,IMMEDIATE
2111 
2112    That is, an add of an immediate to the value in the stack pointer
2113    register, with the result stored back to the stack pointer register.  */
2114 
2115 static bool
is_insn_addi_of_sp_to_sp(const struct riscv_insn & insn)2116 is_insn_addi_of_sp_to_sp (const struct riscv_insn &insn)
2117 {
2118   return ((insn.opcode () == riscv_insn::ADDI
2119              || insn.opcode () == riscv_insn::ADDIW)
2120             && insn.rd () == RISCV_SP_REGNUM
2121             && insn.rs1 () == RISCV_SP_REGNUM);
2122 }
2123 
2124 /* Is the instruction in code memory prior to address PC a load from stack
2125    instruction?  Return true if it is, otherwise, return false.
2126 
2127    This is a best effort that is used as part of the function prologue
2128    scanning logic.  With compressed instructions and arbitrary control
2129    flow in the inferior, we can never be certain what the instruction
2130    prior to PC is.
2131 
2132    This function first looks for a compressed instruction, then looks for
2133    a 32-bit non-compressed instruction.  */
2134 
2135 static bool
previous_insn_is_load_fp_from_stack(struct gdbarch * gdbarch,CORE_ADDR pc)2136 previous_insn_is_load_fp_from_stack (struct gdbarch *gdbarch, CORE_ADDR pc)
2137 {
2138   struct riscv_insn insn;
2139   insn.decode (gdbarch, pc - 2);
2140   gdb_assert (insn.length () > 0);
2141 
2142   if (insn.length () != 2 || !is_insn_load_of_fp_from_sp (insn))
2143     {
2144       insn.decode (gdbarch, pc - 4);
2145       gdb_assert (insn.length () > 0);
2146 
2147       if (insn.length () != 4 || !is_insn_load_of_fp_from_sp (insn))
2148           return false;
2149     }
2150 
2151   riscv_unwinder_debug_printf
2152     ("previous instruction at %s (length %d) was 'ld'",
2153      core_addr_to_string (pc - insn.length ()), insn.length ());
2154   return true;
2155 }
2156 
2157 /* Is the instruction in code memory prior to address PC an add of an
2158    immediate to the stack pointer, with the result being written back into
2159    the stack pointer?  Return true and set *PREV_PC to the address of the
2160    previous instruction if we believe the previous instruction is such an
2161    add, otherwise return false and *PREV_PC is undefined.
2162 
2163    This is a best effort that is used as part of the function prologue
2164    scanning logic.  With compressed instructions and arbitrary control
2165    flow in the inferior, we can never be certain what the instruction
2166    prior to PC is.
2167 
2168    This function first looks for a compressed instruction, then looks for
2169    a 32-bit non-compressed instruction.  */
2170 
2171 static bool
previous_insn_is_add_imm_to_sp(struct gdbarch * gdbarch,CORE_ADDR pc,CORE_ADDR * prev_pc)2172 previous_insn_is_add_imm_to_sp (struct gdbarch *gdbarch, CORE_ADDR pc,
2173                                         CORE_ADDR *prev_pc)
2174 {
2175   struct riscv_insn insn;
2176   insn.decode (gdbarch, pc - 2);
2177   gdb_assert (insn.length () > 0);
2178 
2179   if (insn.length () != 2 || !is_insn_addi_of_sp_to_sp (insn))
2180     {
2181       insn.decode (gdbarch, pc - 4);
2182       gdb_assert (insn.length () > 0);
2183 
2184       if (insn.length () != 4 || !is_insn_addi_of_sp_to_sp (insn))
2185           return false;
2186     }
2187 
2188   riscv_unwinder_debug_printf
2189     ("previous instruction at %s (length %d) was 'add'",
2190      core_addr_to_string (pc - insn.length ()), insn.length ());
2191   *prev_pc = pc - insn.length ();
2192   return true;
2193 }
2194 
2195 /* Try to spot when PC is located in an exit sequence for a particular
2196    function.  Detecting an exit sequence involves a limited amount of
2197    scanning backwards through the disassembly, and so, when considering
2198    compressed instructions, we can never be certain that we have
2199    disassembled the preceding instructions correctly.  On top of that, we
2200    can't be certain that the inferior arrived at PC by passing through the
2201    preceding instructions.
2202 
2203    With all that said, we know that using prologue scanning to figure a
2204    functions unwind information starts to fail when we consider returns
2205    from an instruction -- we must pass through some instructions that
2206    restore the previous state prior to the final return instruction, and
2207    with state partially restored, our prologue derived unwind information
2208    is no longer valid.
2209 
2210    This function then, aims to spot instruction sequences like this:
2211 
2212      ld     fp, IMM_1(sp)
2213      add    sp, sp, IMM_2
2214      ret
2215 
2216    The first instruction restores the previous frame-pointer value, the
2217    second restores the previous stack pointer value, and the final
2218    instruction is the actual return.
2219 
2220    We need to consider that some or all of these instructions might be
2221    compressed.
2222 
2223    This function makes the assumption that, when the inferior reaches the
2224    'ret' instruction the stack pointer will have been restored to its value
2225    on entry to this function.  This assumption will be true in most well
2226    formed programs.
2227 
2228    Return true if we detect that we are in such an instruction sequence,
2229    that is PC points at one of the three instructions given above.  In this
2230    case, set *OFFSET to IMM_2 if PC points to either of the first
2231    two instructions (the 'ld' or 'add'), otherwise set *OFFSET to 0.
2232 
2233    Otherwise, this function returns false, and the contents of *OFFSET are
2234    undefined.  */
2235 
2236 static bool
riscv_detect_end_of_function(struct gdbarch * gdbarch,CORE_ADDR pc,int * offset)2237 riscv_detect_end_of_function (struct gdbarch *gdbarch, CORE_ADDR pc,
2238                                     int *offset)
2239 {
2240   *offset = 0;
2241 
2242   /* We only want to scan a maximum of 3 instructions.  */
2243   for (int i = 0; i < 3; ++i)
2244     {
2245       struct riscv_insn insn;
2246       insn.decode (gdbarch, pc);
2247       gdb_assert (insn.length () > 0);
2248 
2249       if (is_insn_load_of_fp_from_sp (insn))
2250           {
2251             riscv_unwinder_debug_printf ("found 'ld' instruction at %s",
2252                                                core_addr_to_string (pc));
2253             if (i > 0)
2254               return false;
2255             pc += insn.length ();
2256           }
2257       else if (is_insn_addi_of_sp_to_sp (insn))
2258           {
2259             riscv_unwinder_debug_printf ("found 'add' instruction at %s",
2260                                                core_addr_to_string (pc));
2261             if (i > 1)
2262               return false;
2263             if (i == 0)
2264               {
2265                 if (!previous_insn_is_load_fp_from_stack (gdbarch, pc))
2266                     return false;
2267 
2268                 i = 1;
2269               }
2270             *offset = insn.imm_signed ();
2271             pc += insn.length ();
2272           }
2273       else if (insn.opcode () == riscv_insn::JALR
2274                  && insn.rs1 () == RISCV_RA_REGNUM
2275                  && insn.rs2 () == RISCV_ZERO_REGNUM)
2276           {
2277             riscv_unwinder_debug_printf ("found 'ret' instruction at %s",
2278                                                core_addr_to_string (pc));
2279             gdb_assert (i != 1);
2280             if (i == 0)
2281               {
2282                 CORE_ADDR prev_pc;
2283                 if (!previous_insn_is_add_imm_to_sp (gdbarch, pc, &prev_pc))
2284                     return false;
2285                 if (!previous_insn_is_load_fp_from_stack (gdbarch, prev_pc))
2286                     return false;
2287                 i = 2;
2288               }
2289 
2290             pc += insn.length ();
2291           }
2292       else
2293           return false;
2294     }
2295 
2296   return true;
2297 }
2298 
2299 /* The prologue scanner.  This is currently only used for skipping the
2300    prologue of a function when the DWARF information is not sufficient.
2301    However, it is written with filling of the frame cache in mind, which
2302    is why different groups of stack setup instructions are split apart
2303    during the core of the inner loop.  In the future, the intention is to
2304    extend this function to fully support building up a frame cache that
2305    can unwind register values when there is no DWARF information.  */
2306 
2307 static CORE_ADDR
riscv_scan_prologue(struct gdbarch * gdbarch,CORE_ADDR start_pc,CORE_ADDR end_pc,struct riscv_unwind_cache * cache)2308 riscv_scan_prologue (struct gdbarch *gdbarch,
2309                          CORE_ADDR start_pc, CORE_ADDR end_pc,
2310                          struct riscv_unwind_cache *cache)
2311 {
2312   CORE_ADDR cur_pc, next_pc, after_prologue_pc;
2313   CORE_ADDR original_end_pc = end_pc;
2314   CORE_ADDR end_prologue_addr = 0;
2315 
2316   /* Find an upper limit on the function prologue using the debug
2317      information.  If the debug information could not be used to provide
2318      that bound, then use an arbitrary large number as the upper bound.  */
2319   after_prologue_pc = skip_prologue_using_sal (gdbarch, start_pc);
2320   if (after_prologue_pc == 0)
2321     after_prologue_pc = start_pc + 100;   /* Arbitrary large number.  */
2322   if (after_prologue_pc < end_pc)
2323     end_pc = after_prologue_pc;
2324 
2325   pv_t regs[RISCV_NUM_INTEGER_REGS]; /* Number of GPR.  */
2326   for (int regno = 0; regno < RISCV_NUM_INTEGER_REGS; regno++)
2327     regs[regno] = pv_register (regno, 0);
2328   pv_area stack (RISCV_SP_REGNUM, gdbarch_addr_bit (gdbarch));
2329 
2330   riscv_unwinder_debug_printf ("function starting at %s (limit %s)",
2331                                      core_addr_to_string (start_pc),
2332                                      core_addr_to_string (end_pc));
2333 
2334   for (next_pc = cur_pc = start_pc; cur_pc < end_pc; cur_pc = next_pc)
2335     {
2336       struct riscv_insn insn;
2337 
2338       /* Decode the current instruction, and decide where the next
2339            instruction lives based on the size of this instruction.  */
2340       insn.decode (gdbarch, cur_pc);
2341       gdb_assert (insn.length () > 0);
2342       next_pc = cur_pc + insn.length ();
2343 
2344       /* Look for common stack adjustment insns.  */
2345       if (is_insn_addi_of_sp_to_sp (insn))
2346           {
2347             /* Handle: addi sp, sp, -i
2348                or:     addiw sp, sp, -i  */
2349             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2350             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2351             regs[insn.rd ()]
2352               = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2353           }
2354       else if ((insn.opcode () == riscv_insn::SW
2355                     || insn.opcode () == riscv_insn::SD)
2356                  && (insn.rs1 () == RISCV_SP_REGNUM
2357                        || insn.rs1 () == RISCV_FP_REGNUM))
2358           {
2359             /* Handle: sw reg, offset(sp)
2360                or:     sd reg, offset(sp)
2361                or:     sw reg, offset(s0)
2362                or:     sd reg, offset(s0)  */
2363             /* Instruction storing a register onto the stack.  */
2364             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2365             gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2366             stack.store (pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ()),
2367                               (insn.opcode () == riscv_insn::SW ? 4 : 8),
2368                               regs[insn.rs2 ()]);
2369           }
2370       else if (insn.opcode () == riscv_insn::ADDI
2371                  && insn.rd () == RISCV_FP_REGNUM
2372                  && insn.rs1 () == RISCV_SP_REGNUM)
2373           {
2374             /* Handle: addi s0, sp, size  */
2375             /* Instructions setting up the frame pointer.  */
2376             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2377             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2378             regs[insn.rd ()]
2379               = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2380           }
2381       else if ((insn.opcode () == riscv_insn::ADD
2382                     || insn.opcode () == riscv_insn::ADDW)
2383                  && insn.rd () == RISCV_FP_REGNUM
2384                  && insn.rs1 () == RISCV_SP_REGNUM
2385                  && insn.rs2 () == RISCV_ZERO_REGNUM)
2386           {
2387             /* Handle: add s0, sp, 0
2388                or:     addw s0, sp, 0  */
2389             /* Instructions setting up the frame pointer.  */
2390             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2391             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2392             regs[insn.rd ()] = pv_add_constant (regs[insn.rs1 ()], 0);
2393           }
2394       else if ((insn.opcode () == riscv_insn::ADDI
2395                     && insn.rd () == RISCV_ZERO_REGNUM
2396                     && insn.rs1 () == RISCV_ZERO_REGNUM
2397                     && insn.imm_signed () == 0))
2398           {
2399             /* Handle: add x0, x0, 0   (NOP)  */
2400           }
2401       else if (insn.opcode () == riscv_insn::AUIPC)
2402           {
2403             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2404             regs[insn.rd ()] = pv_constant (cur_pc + insn.imm_signed ());
2405           }
2406       else if (insn.opcode () == riscv_insn::LUI
2407                  || insn.opcode () == riscv_insn::LI)
2408           {
2409             /* Handle: lui REG, n
2410                or:     li  REG, n  */
2411             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2412             regs[insn.rd ()] = pv_constant (insn.imm_signed ());
2413           }
2414       else if (insn.opcode () == riscv_insn::ADDI)
2415           {
2416             /* Handle: addi REG1, REG2, IMM  */
2417             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2418             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2419             regs[insn.rd ()]
2420               = pv_add_constant (regs[insn.rs1 ()], insn.imm_signed ());
2421           }
2422       else if (insn.opcode () == riscv_insn::ADD)
2423           {
2424             /* Handle: add REG1, REG2, REG3  */
2425             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2426             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2427             gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2428             regs[insn.rd ()] = pv_add (regs[insn.rs1 ()], regs[insn.rs2 ()]);
2429           }
2430       else if (insn.opcode () == riscv_insn::LD
2431                  || insn.opcode () == riscv_insn::LW)
2432           {
2433             /* Handle: ld reg, offset(rs1)
2434                or:     c.ld reg, offset(rs1)
2435                or:     lw reg, offset(rs1)
2436                or:     c.lw reg, offset(rs1)  */
2437             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2438             gdb_assert (insn.rs1 () < RISCV_NUM_INTEGER_REGS);
2439             regs[insn.rd ()]
2440               = stack.fetch (pv_add_constant (regs[insn.rs1 ()],
2441                                                       insn.imm_signed ()),
2442                                  (insn.opcode () == riscv_insn::LW ? 4 : 8));
2443           }
2444       else if (insn.opcode () == riscv_insn::MV)
2445           {
2446             /* Handle: c.mv RD, RS2  */
2447             gdb_assert (insn.rd () < RISCV_NUM_INTEGER_REGS);
2448             gdb_assert (insn.rs2 () < RISCV_NUM_INTEGER_REGS);
2449             gdb_assert (insn.rs2 () > 0);
2450             regs[insn.rd ()] = regs[insn.rs2 ()];
2451           }
2452       else
2453           {
2454             end_prologue_addr = cur_pc;
2455             break;
2456           }
2457     }
2458 
2459   if (end_prologue_addr == 0)
2460     end_prologue_addr = cur_pc;
2461 
2462   riscv_unwinder_debug_printf ("end of prologue at %s",
2463                                      core_addr_to_string (end_prologue_addr));
2464 
2465   if (cache != NULL)
2466     {
2467       /* Figure out if it is a frame pointer or just a stack pointer.  Also
2468            the offset held in the pv_t is from the original register value to
2469            the current value, which for a grows down stack means a negative
2470            value.  The FRAME_BASE_OFFSET is the negation of this, how to get
2471            from the current value to the original value.  */
2472       if (pv_is_register (regs[RISCV_FP_REGNUM], RISCV_SP_REGNUM))
2473           {
2474             cache->frame_base_reg = RISCV_FP_REGNUM;
2475             cache->frame_base_offset = -regs[RISCV_FP_REGNUM].k;
2476           }
2477       else
2478           {
2479             cache->frame_base_reg = RISCV_SP_REGNUM;
2480             cache->frame_base_offset = -regs[RISCV_SP_REGNUM].k;
2481           }
2482 
2483       /* Check to see if we are located near to a return instruction in
2484            this function.  If we are then the one or both of the stack
2485            pointer and frame pointer may have been restored to their previous
2486            value.  If we can spot this situation then we can adjust which
2487            register and offset we use for the frame base.  */
2488       if (cache->frame_base_reg != RISCV_SP_REGNUM
2489             || cache->frame_base_offset != 0)
2490           {
2491             int sp_offset;
2492 
2493             if (riscv_detect_end_of_function (gdbarch, original_end_pc,
2494                                                       &sp_offset))
2495               {
2496                 riscv_unwinder_debug_printf
2497                     ("in function epilogue at %s, stack offset is %d",
2498                      core_addr_to_string (original_end_pc), sp_offset);
2499                 cache->frame_base_reg= RISCV_SP_REGNUM;
2500                 cache->frame_base_offset = sp_offset;
2501               }
2502           }
2503 
2504       /* Assign offset from old SP to all saved registers.  As we don't
2505            have the previous value for the frame base register at this
2506            point, we store the offset as the address in the trad_frame, and
2507            then convert this to an actual address later.  */
2508       for (int i = 0; i <= RISCV_NUM_INTEGER_REGS; i++)
2509           {
2510             CORE_ADDR offset;
2511             if (stack.find_reg (gdbarch, i, &offset))
2512               {
2513                 /* Display OFFSET as a signed value, the offsets are from the
2514                      frame base address to the registers location on the stack,
2515                      with a descending stack this means the offsets are always
2516                      negative.  */
2517                 riscv_unwinder_debug_printf ("register $%s at stack offset %s",
2518                                                      gdbarch_register_name (gdbarch, i),
2519                                                      plongest ((LONGEST) offset));
2520                 cache->regs[i].set_addr (offset);
2521               }
2522           }
2523     }
2524 
2525   return end_prologue_addr;
2526 }
2527 
2528 /* Implement the riscv_skip_prologue gdbarch method.  */
2529 
2530 static CORE_ADDR
riscv_skip_prologue(struct gdbarch * gdbarch,CORE_ADDR pc)2531 riscv_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
2532 {
2533   CORE_ADDR func_addr;
2534 
2535   /* See if we can determine the end of the prologue via the symbol
2536      table.  If so, then return either PC, or the PC after the
2537      prologue, whichever is greater.  */
2538   if (find_pc_partial_function (pc, NULL, &func_addr, NULL))
2539     {
2540       CORE_ADDR post_prologue_pc
2541           = skip_prologue_using_sal (gdbarch, func_addr);
2542 
2543       if (post_prologue_pc != 0)
2544           return std::max (pc, post_prologue_pc);
2545     }
2546 
2547   /* Can't determine prologue from the symbol table, need to examine
2548      instructions.  Pass -1 for the end address to indicate the prologue
2549      scanner can scan as far as it needs to find the end of the prologue.  */
2550   return riscv_scan_prologue (gdbarch, pc, ((CORE_ADDR) -1), NULL);
2551 }
2552 
2553 /* Implement the gdbarch push dummy code callback.  */
2554 
2555 static CORE_ADDR
riscv_push_dummy_code(struct gdbarch * gdbarch,CORE_ADDR sp,CORE_ADDR funaddr,struct value ** args,int nargs,struct type * value_type,CORE_ADDR * real_pc,CORE_ADDR * bp_addr,struct regcache * regcache)2556 riscv_push_dummy_code (struct gdbarch *gdbarch, CORE_ADDR sp,
2557                            CORE_ADDR funaddr, struct value **args, int nargs,
2558                            struct type *value_type, CORE_ADDR *real_pc,
2559                            CORE_ADDR *bp_addr, struct regcache *regcache)
2560 {
2561   /* A nop instruction is 'add x0, x0, 0'.  */
2562   static const gdb_byte nop_insn[] = { 0x13, 0x00, 0x00, 0x00 };
2563 
2564   /* Allocate space for a breakpoint, and keep the stack correctly
2565      aligned.  The space allocated here must be at least big enough to
2566      accommodate the NOP_INSN defined above.  */
2567   sp -= 16;
2568   *bp_addr = sp;
2569   *real_pc = funaddr;
2570 
2571   /* When we insert a breakpoint we select whether to use a compressed
2572      breakpoint or not based on the existing contents of the memory.
2573 
2574      If the breakpoint is being placed onto the stack as part of setting up
2575      for an inferior call from GDB, then the existing stack contents may
2576      randomly appear to be a compressed instruction, causing GDB to insert
2577      a compressed breakpoint.  If this happens on a target that does not
2578      support compressed instructions then this could cause problems.
2579 
2580      To prevent this issue we write an uncompressed nop onto the stack at
2581      the location where the breakpoint will be inserted.  In this way we
2582      ensure that we always use an uncompressed breakpoint, which should
2583      work on all targets.
2584 
2585      We call TARGET_WRITE_MEMORY here so that if the write fails we don't
2586      throw an exception.  Instead we ignore the error and move on.  The
2587      assumption is that either GDB will error later when actually trying to
2588      insert a software breakpoint, or GDB will use hardware breakpoints and
2589      there will be no need to write to memory later.  */
2590   int status = target_write_memory (*bp_addr, nop_insn, sizeof (nop_insn));
2591 
2592   riscv_infcall_debug_printf ("writing %s-byte nop instruction to %s: %s",
2593                                     plongest (sizeof (nop_insn)),
2594                                     paddress (gdbarch, *bp_addr),
2595                                     (status == 0 ? "success" : "failed"));
2596 
2597   return sp;
2598 }
2599 
2600 /* Implement the gdbarch type alignment method, overrides the generic
2601    alignment algorithm for anything that is RISC-V specific.  */
2602 
2603 static ULONGEST
riscv_type_align(gdbarch * gdbarch,type * type)2604 riscv_type_align (gdbarch *gdbarch, type *type)
2605 {
2606   type = check_typedef (type);
2607   if (type->code () == TYPE_CODE_ARRAY && type->is_vector ())
2608     return std::min (type->length (), (ULONGEST) BIGGEST_ALIGNMENT);
2609 
2610   /* Anything else will be aligned by the generic code.  */
2611   return 0;
2612 }
2613 
2614 /* Holds information about a single argument either being passed to an
2615    inferior function, or returned from an inferior function.  This includes
2616    information about the size, type, etc of the argument, and also
2617    information about how the argument will be passed (or returned).  */
2618 
2619 struct riscv_arg_info
2620 {
2621   /* Contents of the argument.  */
2622   const gdb_byte *contents;
2623 
2624   /* Length of argument.  */
2625   int length;
2626 
2627   /* Alignment required for an argument of this type.  */
2628   int align;
2629 
2630   /* The type for this argument.  */
2631   struct type *type;
2632 
2633   /* Each argument can have either 1 or 2 locations assigned to it.  Each
2634      location describes where part of the argument will be placed.  The
2635      second location is valid based on the LOC_TYPE and C_LENGTH fields
2636      of the first location (which is always valid).  */
2637   struct location
2638   {
2639     /* What type of location this is.  */
2640     enum location_type
2641       {
2642        /* Argument passed in a register.  */
2643        in_reg,
2644 
2645        /* Argument passed as an on stack argument.  */
2646        on_stack,
2647 
2648        /* Argument passed by reference.  The second location is always
2649             valid for a BY_REF argument, and describes where the address
2650             of the BY_REF argument should be placed.  */
2651        by_ref
2652       } loc_type;
2653 
2654     /* Information that depends on the location type.  */
2655     union
2656     {
2657       /* Which register number to use.  */
2658       int regno;
2659 
2660       /* The offset into the stack region.  */
2661       int offset;
2662     } loc_data;
2663 
2664     /* The length of contents covered by this location.  If this is less
2665        than the total length of the argument, then the second location
2666        will be valid, and will describe where the rest of the argument
2667        will go.  */
2668     int c_length;
2669 
2670     /* The offset within CONTENTS for this part of the argument.  This can
2671        be non-zero even for the first part (the first field of a struct can
2672        have a non-zero offset due to padding).  For the second part of the
2673        argument, this might be the C_LENGTH value of the first part,
2674        however, if we are passing a structure in two registers, and there's
2675        is padding between the first and second field, then this offset
2676        might be greater than the length of the first argument part.  When
2677        the second argument location is not holding part of the argument
2678        value, but is instead holding the address of a reference argument,
2679        then this offset will be set to 0.  */
2680     int c_offset;
2681   } argloc[2];
2682 
2683   /* TRUE if this is an unnamed argument.  */
2684   bool is_unnamed;
2685 };
2686 
2687 /* Information about a set of registers being used for passing arguments as
2688    part of a function call.  The register set must be numerically
2689    sequential from NEXT_REGNUM to LAST_REGNUM.  The register set can be
2690    disabled from use by setting NEXT_REGNUM greater than LAST_REGNUM.  */
2691 
2692 struct riscv_arg_reg
2693 {
riscv_arg_regriscv_arg_reg2694   riscv_arg_reg (int first, int last)
2695     : next_regnum (first),
2696       last_regnum (last)
2697   {
2698     /* Nothing.  */
2699   }
2700 
2701   /* The GDB register number to use in this set.  */
2702   int next_regnum;
2703 
2704   /* The last GDB register number to use in this set.  */
2705   int last_regnum;
2706 };
2707 
2708 /* Arguments can be passed as on stack arguments, or by reference.  The
2709    on stack arguments must be in a continuous region starting from $sp,
2710    while the by reference arguments can be anywhere, but we'll put them
2711    on the stack after (at higher address) the on stack arguments.
2712 
2713    This might not be the right approach to take.  The ABI is clear that
2714    an argument passed by reference can be modified by the callee, which
2715    us placing the argument (temporarily) onto the stack will not achieve
2716    (changes will be lost).  There's also the possibility that very large
2717    arguments could overflow the stack.
2718 
2719    This struct is used to track offset into these two areas for where
2720    arguments are to be placed.  */
2721 struct riscv_memory_offsets
2722 {
riscv_memory_offsetsriscv_memory_offsets2723   riscv_memory_offsets ()
2724     : arg_offset (0),
2725       ref_offset (0)
2726   {
2727     /* Nothing.  */
2728   }
2729 
2730   /* Offset into on stack argument area.  */
2731   int arg_offset;
2732 
2733   /* Offset into the pass by reference area.  */
2734   int ref_offset;
2735 };
2736 
2737 /* Holds information about where arguments to a call will be placed.  This
2738    is updated as arguments are added onto the call, and can be used to
2739    figure out where the next argument should be placed.  */
2740 
2741 struct riscv_call_info
2742 {
riscv_call_inforiscv_call_info2743   riscv_call_info (struct gdbarch *gdbarch)
2744     : int_regs (RISCV_A0_REGNUM, RISCV_A0_REGNUM + 7),
2745       float_regs (RISCV_FA0_REGNUM, RISCV_FA0_REGNUM + 7)
2746   {
2747     xlen = riscv_abi_xlen (gdbarch);
2748     flen = riscv_abi_flen (gdbarch);
2749 
2750     /* Reduce the number of integer argument registers when using the
2751        embedded abi (i.e. rv32e).  */
2752     if (riscv_abi_embedded (gdbarch))
2753       int_regs.last_regnum = RISCV_A0_REGNUM + 5;
2754 
2755     /* Disable use of floating point registers if needed.  */
2756     if (!riscv_has_fp_abi (gdbarch))
2757       float_regs.next_regnum = float_regs.last_regnum + 1;
2758   }
2759 
2760   /* Track the memory areas used for holding in-memory arguments to a
2761      call.  */
2762   struct riscv_memory_offsets memory;
2763 
2764   /* Holds information about the next integer register to use for passing
2765      an argument.  */
2766   struct riscv_arg_reg int_regs;
2767 
2768   /* Holds information about the next floating point register to use for
2769      passing an argument.  */
2770   struct riscv_arg_reg float_regs;
2771 
2772   /* The XLEN and FLEN are copied in to this structure for convenience, and
2773      are just the results of calling RISCV_ABI_XLEN and RISCV_ABI_FLEN.  */
2774   int xlen;
2775   int flen;
2776 };
2777 
2778 /* Return the number of registers available for use as parameters in the
2779    register set REG.  Returned value can be 0 or more.  */
2780 
2781 static int
riscv_arg_regs_available(struct riscv_arg_reg * reg)2782 riscv_arg_regs_available (struct riscv_arg_reg *reg)
2783 {
2784   if (reg->next_regnum > reg->last_regnum)
2785     return 0;
2786 
2787   return (reg->last_regnum - reg->next_regnum + 1);
2788 }
2789 
2790 /* If there is at least one register available in the register set REG then
2791    the next register from REG is assigned to LOC and the length field of
2792    LOC is updated to LENGTH.  The register set REG is updated to indicate
2793    that the assigned register is no longer available and the function
2794    returns true.
2795 
2796    If there are no registers available in REG then the function returns
2797    false, and LOC and REG are unchanged.  */
2798 
2799 static bool
riscv_assign_reg_location(struct riscv_arg_info::location * loc,struct riscv_arg_reg * reg,int length,int offset)2800 riscv_assign_reg_location (struct riscv_arg_info::location *loc,
2801                                  struct riscv_arg_reg *reg,
2802                                  int length, int offset)
2803 {
2804   if (reg->next_regnum <= reg->last_regnum)
2805     {
2806       loc->loc_type = riscv_arg_info::location::in_reg;
2807       loc->loc_data.regno = reg->next_regnum;
2808       reg->next_regnum++;
2809       loc->c_length = length;
2810       loc->c_offset = offset;
2811       return true;
2812     }
2813 
2814   return false;
2815 }
2816 
2817 /* Assign LOC a location as the next stack parameter, and update MEMORY to
2818    record that an area of stack has been used to hold the parameter
2819    described by LOC.
2820 
2821    The length field of LOC is updated to LENGTH, the length of the
2822    parameter being stored, and ALIGN is the alignment required by the
2823    parameter, which will affect how memory is allocated out of MEMORY.  */
2824 
2825 static void
riscv_assign_stack_location(struct riscv_arg_info::location * loc,struct riscv_memory_offsets * memory,int length,int align)2826 riscv_assign_stack_location (struct riscv_arg_info::location *loc,
2827                                    struct riscv_memory_offsets *memory,
2828                                    int length, int align)
2829 {
2830   loc->loc_type = riscv_arg_info::location::on_stack;
2831   memory->arg_offset
2832     = align_up (memory->arg_offset, align);
2833   loc->loc_data.offset = memory->arg_offset;
2834   memory->arg_offset += length;
2835   loc->c_length = length;
2836 
2837   /* Offset is always 0, either we're the first location part, in which
2838      case we're reading content from the start of the argument, or we're
2839      passing the address of a reference argument, so 0.  */
2840   loc->c_offset = 0;
2841 }
2842 
2843 /* Update AINFO, which describes an argument that should be passed or
2844    returned using the integer ABI.  The argloc fields within AINFO are
2845    updated to describe the location in which the argument will be passed to
2846    a function, or returned from a function.
2847 
2848    The CINFO structure contains the ongoing call information, the holds
2849    information such as which argument registers are remaining to be
2850    assigned to parameter, and how much memory has been used by parameters
2851    so far.
2852 
2853    By examining the state of CINFO a suitable location can be selected,
2854    and assigned to AINFO.  */
2855 
2856 static void
riscv_call_arg_scalar_int(struct riscv_arg_info * ainfo,struct riscv_call_info * cinfo)2857 riscv_call_arg_scalar_int (struct riscv_arg_info *ainfo,
2858                                  struct riscv_call_info *cinfo)
2859 {
2860   if (TYPE_HAS_DYNAMIC_LENGTH (ainfo->type)
2861       || ainfo->length > (2 * cinfo->xlen))
2862     {
2863       /* Argument is going to be passed by reference.  */
2864       ainfo->argloc[0].loc_type
2865           = riscv_arg_info::location::by_ref;
2866       cinfo->memory.ref_offset
2867           = align_up (cinfo->memory.ref_offset, ainfo->align);
2868       ainfo->argloc[0].loc_data.offset = cinfo->memory.ref_offset;
2869       cinfo->memory.ref_offset += ainfo->length;
2870       ainfo->argloc[0].c_length = ainfo->length;
2871 
2872       /* The second location for this argument is given over to holding the
2873            address of the by-reference data.  Pass 0 for the offset as this
2874            is not part of the actual argument value.  */
2875       if (!riscv_assign_reg_location (&ainfo->argloc[1],
2876                                               &cinfo->int_regs,
2877                                               cinfo->xlen, 0))
2878           riscv_assign_stack_location (&ainfo->argloc[1],
2879                                              &cinfo->memory, cinfo->xlen,
2880                                              cinfo->xlen);
2881     }
2882   else
2883     {
2884       int len = std::min (ainfo->length, cinfo->xlen);
2885       int align = std::max (ainfo->align, cinfo->xlen);
2886 
2887       /* Unnamed arguments in registers that require 2*XLEN alignment are
2888            passed in an aligned register pair.  */
2889       if (ainfo->is_unnamed && (align == cinfo->xlen * 2)
2890             && cinfo->int_regs.next_regnum & 1)
2891           cinfo->int_regs.next_regnum++;
2892 
2893       if (!riscv_assign_reg_location (&ainfo->argloc[0],
2894                                               &cinfo->int_regs, len, 0))
2895           riscv_assign_stack_location (&ainfo->argloc[0],
2896                                              &cinfo->memory, len, align);
2897 
2898       if (len < ainfo->length)
2899           {
2900             len = ainfo->length - len;
2901             if (!riscv_assign_reg_location (&ainfo->argloc[1],
2902                                                     &cinfo->int_regs, len,
2903                                                     cinfo->xlen))
2904               riscv_assign_stack_location (&ainfo->argloc[1],
2905                                                    &cinfo->memory, len, cinfo->xlen);
2906           }
2907     }
2908 }
2909 
2910 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2911    is being passed with the floating point ABI.  */
2912 
2913 static void
riscv_call_arg_scalar_float(struct riscv_arg_info * ainfo,struct riscv_call_info * cinfo)2914 riscv_call_arg_scalar_float (struct riscv_arg_info *ainfo,
2915                                    struct riscv_call_info *cinfo)
2916 {
2917   if (ainfo->length > cinfo->flen || ainfo->is_unnamed)
2918     return riscv_call_arg_scalar_int (ainfo, cinfo);
2919   else
2920     {
2921       if (!riscv_assign_reg_location (&ainfo->argloc[0],
2922                                               &cinfo->float_regs,
2923                                               ainfo->length, 0))
2924           return riscv_call_arg_scalar_int (ainfo, cinfo);
2925     }
2926 }
2927 
2928 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
2929    is a complex floating point argument, and is therefore handled
2930    differently to other argument types.  */
2931 
2932 static void
riscv_call_arg_complex_float(struct riscv_arg_info * ainfo,struct riscv_call_info * cinfo)2933 riscv_call_arg_complex_float (struct riscv_arg_info *ainfo,
2934                                     struct riscv_call_info *cinfo)
2935 {
2936   if (ainfo->length <= (2 * cinfo->flen)
2937       && riscv_arg_regs_available (&cinfo->float_regs) >= 2
2938       && !ainfo->is_unnamed)
2939     {
2940       bool result;
2941       int len = ainfo->length / 2;
2942 
2943       result = riscv_assign_reg_location (&ainfo->argloc[0],
2944                                                     &cinfo->float_regs, len, 0);
2945       gdb_assert (result);
2946 
2947       result = riscv_assign_reg_location (&ainfo->argloc[1],
2948                                                     &cinfo->float_regs, len, len);
2949       gdb_assert (result);
2950     }
2951   else
2952     return riscv_call_arg_scalar_int (ainfo, cinfo);
2953 }
2954 
2955 /* A structure used for holding information about a structure type within
2956    the inferior program.  The RiscV ABI has special rules for handling some
2957    structures with a single field or with two fields.  The counting of
2958    fields here is done after flattening out all nested structures.  */
2959 
2960 class riscv_struct_info
2961 {
2962 public:
riscv_struct_info()2963   riscv_struct_info ()
2964     : m_number_of_fields (0),
2965       m_types { nullptr, nullptr },
2966       m_offsets { 0, 0 }
2967   {
2968     /* Nothing.  */
2969   }
2970 
2971   /* Analyse TYPE descending into nested structures, count the number of
2972      scalar fields and record the types of the first two fields found.  */
analyse(struct type * type)2973   void analyse (struct type *type)
2974   {
2975     analyse_inner (type, 0);
2976   }
2977 
2978   /* The number of scalar fields found in the analysed type.  This is
2979      currently only accurate if the value returned is 0, 1, or 2 as the
2980      analysis stops counting when the number of fields is 3.  This is
2981      because the RiscV ABI only has special cases for 1 or 2 fields,
2982      anything else we just don't care about.  */
number_of_fields()2983   int number_of_fields () const
2984   { return m_number_of_fields; }
2985 
2986   /* Return the type for scalar field INDEX within the analysed type.  Will
2987      return nullptr if there is no field at that index.  Only INDEX values
2988      0 and 1 can be requested as the RiscV ABI only has special cases for
2989      structures with 1 or 2 fields.  */
field_type(int index)2990   struct type *field_type (int index) const
2991   {
2992     gdb_assert (index < (sizeof (m_types) / sizeof (m_types[0])));
2993     return m_types[index];
2994   }
2995 
2996   /* Return the offset of scalar field INDEX within the analysed type. Will
2997      return 0 if there is no field at that index.  Only INDEX values 0 and
2998      1 can be requested as the RiscV ABI only has special cases for
2999      structures with 1 or 2 fields.  */
field_offset(int index)3000   int field_offset (int index) const
3001   {
3002     gdb_assert (index < (sizeof (m_offsets) / sizeof (m_offsets[0])));
3003     return m_offsets[index];
3004   }
3005 
3006 private:
3007   /* The number of scalar fields found within the structure after recursing
3008      into nested structures.  */
3009   int m_number_of_fields;
3010 
3011   /* The types of the first two scalar fields found within the structure
3012      after recursing into nested structures.  */
3013   struct type *m_types[2];
3014 
3015   /* The offsets of the first two scalar fields found within the structure
3016      after recursing into nested structures.  */
3017   int m_offsets[2];
3018 
3019   /* Recursive core for ANALYSE, the OFFSET parameter tracks the byte
3020      offset from the start of the top level structure being analysed.  */
3021   void analyse_inner (struct type *type, int offset);
3022 };
3023 
3024 /* See description in class declaration.  */
3025 
3026 void
analyse_inner(struct type * type,int offset)3027 riscv_struct_info::analyse_inner (struct type *type, int offset)
3028 {
3029   unsigned int count = type->num_fields ();
3030   unsigned int i;
3031 
3032   for (i = 0; i < count; ++i)
3033     {
3034       if (type->field (i).loc_kind () != FIELD_LOC_KIND_BITPOS)
3035           continue;
3036 
3037       struct type *field_type = type->field (i).type ();
3038       field_type = check_typedef (field_type);
3039       int field_offset
3040           = offset + type->field (i).loc_bitpos () / TARGET_CHAR_BIT;
3041 
3042       switch (field_type->code ())
3043           {
3044           case TYPE_CODE_STRUCT:
3045             analyse_inner (field_type, field_offset);
3046             break;
3047 
3048           default:
3049             /* RiscV only flattens out structures.  Anything else does not
3050                need to be flattened, we just record the type, and when we
3051                look at the analysis results we'll realise this is not a
3052                structure we can special case, and pass the structure in
3053                memory.  */
3054             if (m_number_of_fields < 2)
3055               {
3056                 m_types[m_number_of_fields] = field_type;
3057                 m_offsets[m_number_of_fields] = field_offset;
3058               }
3059             m_number_of_fields++;
3060             break;
3061           }
3062 
3063       /* RiscV only has special handling for structures with 1 or 2 scalar
3064            fields, any more than that and the structure is just passed in
3065            memory.  We can safely drop out early when we find 3 or more
3066            fields then.  */
3067 
3068       if (m_number_of_fields > 2)
3069           return;
3070     }
3071 }
3072 
3073 /* Like RISCV_CALL_ARG_SCALAR_INT, except the argument described by AINFO
3074    is a structure.  Small structures on RiscV have some special case
3075    handling in order that the structure might be passed in register.
3076    Larger structures are passed in memory.  After assigning location
3077    information to AINFO, CINFO will have been updated.  */
3078 
3079 static void
riscv_call_arg_struct(struct riscv_arg_info * ainfo,struct riscv_call_info * cinfo)3080 riscv_call_arg_struct (struct riscv_arg_info *ainfo,
3081                            struct riscv_call_info *cinfo)
3082 {
3083   if (riscv_arg_regs_available (&cinfo->float_regs) >= 1)
3084     {
3085       struct riscv_struct_info sinfo;
3086 
3087       sinfo.analyse (ainfo->type);
3088       if (sinfo.number_of_fields () == 1
3089             && sinfo.field_type(0)->code () == TYPE_CODE_COMPLEX)
3090           {
3091             /* The following is similar to RISCV_CALL_ARG_COMPLEX_FLOAT,
3092                except we use the type of the complex field instead of the
3093                type from AINFO, and the first location might be at a non-zero
3094                offset.  */
3095             if (sinfo.field_type (0)->length () <= (2 * cinfo->flen)
3096                 && riscv_arg_regs_available (&cinfo->float_regs) >= 2
3097                 && !ainfo->is_unnamed)
3098               {
3099                 bool result;
3100                 int len = sinfo.field_type (0)->length () / 2;
3101                 int offset = sinfo.field_offset (0);
3102 
3103                 result = riscv_assign_reg_location (&ainfo->argloc[0],
3104                                                               &cinfo->float_regs, len,
3105                                                               offset);
3106                 gdb_assert (result);
3107 
3108                 result = riscv_assign_reg_location (&ainfo->argloc[1],
3109                                                               &cinfo->float_regs, len,
3110                                                               (offset + len));
3111                 gdb_assert (result);
3112               }
3113             else
3114               riscv_call_arg_scalar_int (ainfo, cinfo);
3115             return;
3116           }
3117 
3118       if (sinfo.number_of_fields () == 1
3119             && sinfo.field_type(0)->code () == TYPE_CODE_FLT)
3120           {
3121             /* The following is similar to RISCV_CALL_ARG_SCALAR_FLOAT,
3122                except we use the type of the first scalar field instead of
3123                the type from AINFO.  Also the location might be at a non-zero
3124                offset.  */
3125             if (sinfo.field_type (0)->length () > cinfo->flen
3126                 || ainfo->is_unnamed)
3127               riscv_call_arg_scalar_int (ainfo, cinfo);
3128             else
3129               {
3130                 int offset = sinfo.field_offset (0);
3131                 int len = sinfo.field_type (0)->length ();
3132 
3133                 if (!riscv_assign_reg_location (&ainfo->argloc[0],
3134                                                         &cinfo->float_regs,
3135                                                         len, offset))
3136                     riscv_call_arg_scalar_int (ainfo, cinfo);
3137               }
3138             return;
3139           }
3140 
3141       if (sinfo.number_of_fields () == 2
3142             && sinfo.field_type(0)->code () == TYPE_CODE_FLT
3143             && sinfo.field_type (0)->length () <= cinfo->flen
3144             && sinfo.field_type(1)->code () == TYPE_CODE_FLT
3145             && sinfo.field_type (1)->length () <= cinfo->flen
3146             && riscv_arg_regs_available (&cinfo->float_regs) >= 2)
3147           {
3148             int len0 = sinfo.field_type (0)->length ();
3149             int offset = sinfo.field_offset (0);
3150             if (!riscv_assign_reg_location (&ainfo->argloc[0],
3151                                                     &cinfo->float_regs, len0, offset))
3152               error (_("failed during argument setup"));
3153 
3154             int len1 = sinfo.field_type (1)->length ();
3155             offset = sinfo.field_offset (1);
3156             gdb_assert (len1 <= (ainfo->type->length ()
3157                                      - sinfo.field_type (0)->length ()));
3158 
3159             if (!riscv_assign_reg_location (&ainfo->argloc[1],
3160                                                     &cinfo->float_regs,
3161                                                     len1, offset))
3162               error (_("failed during argument setup"));
3163             return;
3164           }
3165 
3166       if (sinfo.number_of_fields () == 2
3167             && riscv_arg_regs_available (&cinfo->int_regs) >= 1
3168             && (sinfo.field_type(0)->code () == TYPE_CODE_FLT
3169                 && sinfo.field_type (0)->length () <= cinfo->flen
3170                 && is_integral_type (sinfo.field_type (1))
3171                 && sinfo.field_type (1)->length () <= cinfo->xlen))
3172           {
3173             int  len0 = sinfo.field_type (0)->length ();
3174             int offset = sinfo.field_offset (0);
3175             if (!riscv_assign_reg_location (&ainfo->argloc[0],
3176                                                     &cinfo->float_regs, len0, offset))
3177               error (_("failed during argument setup"));
3178 
3179             int len1 = sinfo.field_type (1)->length ();
3180             offset = sinfo.field_offset (1);
3181             gdb_assert (len1 <= cinfo->xlen);
3182             if (!riscv_assign_reg_location (&ainfo->argloc[1],
3183                                                     &cinfo->int_regs, len1, offset))
3184               error (_("failed during argument setup"));
3185             return;
3186           }
3187 
3188       if (sinfo.number_of_fields () == 2
3189             && riscv_arg_regs_available (&cinfo->int_regs) >= 1
3190             && (is_integral_type (sinfo.field_type (0))
3191                 && sinfo.field_type (0)->length () <= cinfo->xlen
3192                 && sinfo.field_type(1)->code () == TYPE_CODE_FLT
3193                 && sinfo.field_type (1)->length () <= cinfo->flen))
3194           {
3195             int len0 = sinfo.field_type (0)->length ();
3196             int len1 = sinfo.field_type (1)->length ();
3197 
3198             gdb_assert (len0 <= cinfo->xlen);
3199             gdb_assert (len1 <= cinfo->flen);
3200 
3201             int offset = sinfo.field_offset (0);
3202             if (!riscv_assign_reg_location (&ainfo->argloc[0],
3203                                                     &cinfo->int_regs, len0, offset))
3204               error (_("failed during argument setup"));
3205 
3206             offset = sinfo.field_offset (1);
3207             if (!riscv_assign_reg_location (&ainfo->argloc[1],
3208                                                     &cinfo->float_regs,
3209                                                     len1, offset))
3210               error (_("failed during argument setup"));
3211 
3212             return;
3213           }
3214     }
3215 
3216   /* Non of the structure flattening cases apply, so we just pass using
3217      the integer ABI.  */
3218   riscv_call_arg_scalar_int (ainfo, cinfo);
3219 }
3220 
3221 /* Assign a location to call (or return) argument AINFO, the location is
3222    selected from CINFO which holds information about what call argument
3223    locations are available for use next.  The TYPE is the type of the
3224    argument being passed, this information is recorded into AINFO (along
3225    with some additional information derived from the type).  IS_UNNAMED
3226    is true if this is an unnamed (stdarg) argument, this info is also
3227    recorded into AINFO.
3228 
3229    After assigning a location to AINFO, CINFO will have been updated.  */
3230 
3231 static void
riscv_arg_location(struct gdbarch * gdbarch,struct riscv_arg_info * ainfo,struct riscv_call_info * cinfo,struct type * type,bool is_unnamed)3232 riscv_arg_location (struct gdbarch *gdbarch,
3233                         struct riscv_arg_info *ainfo,
3234                         struct riscv_call_info *cinfo,
3235                         struct type *type, bool is_unnamed)
3236 {
3237   ainfo->type = type;
3238   ainfo->length = ainfo->type->length ();
3239   ainfo->align = type_align (ainfo->type);
3240   ainfo->is_unnamed = is_unnamed;
3241   ainfo->contents = nullptr;
3242   ainfo->argloc[0].c_length = 0;
3243   ainfo->argloc[1].c_length = 0;
3244 
3245   switch (ainfo->type->code ())
3246     {
3247     case TYPE_CODE_INT:
3248     case TYPE_CODE_BOOL:
3249     case TYPE_CODE_CHAR:
3250     case TYPE_CODE_RANGE:
3251     case TYPE_CODE_ENUM:
3252     case TYPE_CODE_PTR:
3253     case TYPE_CODE_FIXED_POINT:
3254       if (ainfo->length <= cinfo->xlen)
3255           {
3256             ainfo->type = builtin_type (gdbarch)->builtin_long;
3257             ainfo->length = cinfo->xlen;
3258           }
3259       else if (ainfo->length <= (2 * cinfo->xlen))
3260           {
3261             ainfo->type = builtin_type (gdbarch)->builtin_long_long;
3262             ainfo->length = 2 * cinfo->xlen;
3263           }
3264 
3265       /* Recalculate the alignment requirement.  */
3266       ainfo->align = type_align (ainfo->type);
3267       riscv_call_arg_scalar_int (ainfo, cinfo);
3268       break;
3269 
3270     case TYPE_CODE_FLT:
3271       riscv_call_arg_scalar_float (ainfo, cinfo);
3272       break;
3273 
3274     case TYPE_CODE_COMPLEX:
3275       riscv_call_arg_complex_float (ainfo, cinfo);
3276       break;
3277 
3278     case TYPE_CODE_STRUCT:
3279       if (!TYPE_HAS_DYNAMIC_LENGTH (ainfo->type))
3280           {
3281             riscv_call_arg_struct (ainfo, cinfo);
3282             break;
3283           }
3284       [[fallthrough]];
3285 
3286     default:
3287       riscv_call_arg_scalar_int (ainfo, cinfo);
3288       break;
3289     }
3290 }
3291 
3292 /* Used for printing debug information about the call argument location in
3293    INFO to STREAM.  The addresses in SP_REFS and SP_ARGS are the base
3294    addresses for the location of pass-by-reference and
3295    arguments-on-the-stack memory areas.  */
3296 
3297 static void
riscv_print_arg_location(ui_file * stream,struct gdbarch * gdbarch,struct riscv_arg_info * info,CORE_ADDR sp_refs,CORE_ADDR sp_args)3298 riscv_print_arg_location (ui_file *stream, struct gdbarch *gdbarch,
3299                                 struct riscv_arg_info *info,
3300                                 CORE_ADDR sp_refs, CORE_ADDR sp_args)
3301 {
3302   gdb_printf (stream, "type: '%s', length: 0x%x, alignment: 0x%x",
3303                 TYPE_SAFE_NAME (info->type), info->length, info->align);
3304   switch (info->argloc[0].loc_type)
3305     {
3306     case riscv_arg_info::location::in_reg:
3307       gdb_printf
3308           (stream, ", register %s",
3309            gdbarch_register_name (gdbarch, info->argloc[0].loc_data.regno));
3310       if (info->argloc[0].c_length < info->length)
3311           {
3312             switch (info->argloc[1].loc_type)
3313               {
3314               case riscv_arg_info::location::in_reg:
3315                 gdb_printf
3316                     (stream, ", register %s",
3317                      gdbarch_register_name (gdbarch,
3318                                                   info->argloc[1].loc_data.regno));
3319                 break;
3320 
3321               case riscv_arg_info::location::on_stack:
3322                 gdb_printf (stream, ", on stack at offset 0x%x",
3323                                 info->argloc[1].loc_data.offset);
3324                 break;
3325 
3326               case riscv_arg_info::location::by_ref:
3327               default:
3328                 /* The second location should never be a reference, any
3329                      argument being passed by reference just places its address
3330                      in the first location and is done.  */
3331                 error (_("invalid argument location"));
3332                 break;
3333               }
3334 
3335             if (info->argloc[1].c_offset > info->argloc[0].c_length)
3336               gdb_printf (stream, " (offset 0x%x)",
3337                               info->argloc[1].c_offset);
3338           }
3339       break;
3340 
3341     case riscv_arg_info::location::on_stack:
3342       gdb_printf (stream, ", on stack at offset 0x%x",
3343                       info->argloc[0].loc_data.offset);
3344       break;
3345 
3346     case riscv_arg_info::location::by_ref:
3347       gdb_printf
3348           (stream, ", by reference, data at offset 0x%x (%s)",
3349            info->argloc[0].loc_data.offset,
3350            core_addr_to_string (sp_refs + info->argloc[0].loc_data.offset));
3351       if (info->argloc[1].loc_type
3352             == riscv_arg_info::location::in_reg)
3353           gdb_printf
3354             (stream, ", address in register %s",
3355              gdbarch_register_name (gdbarch, info->argloc[1].loc_data.regno));
3356       else
3357           {
3358             gdb_assert (info->argloc[1].loc_type
3359                           == riscv_arg_info::location::on_stack);
3360             gdb_printf
3361               (stream, ", address on stack at offset 0x%x (%s)",
3362                info->argloc[1].loc_data.offset,
3363                core_addr_to_string (sp_args + info->argloc[1].loc_data.offset));
3364           }
3365       break;
3366 
3367     default:
3368       gdb_assert_not_reached ("unknown argument location type");
3369     }
3370 }
3371 
3372 /* Wrapper around REGCACHE->cooked_write.  Places the LEN bytes of DATA
3373    into a buffer that is at least as big as the register REGNUM, padding
3374    out the DATA with either 0x00, or 0xff.  For floating point registers
3375    0xff is used, for everyone else 0x00 is used.  */
3376 
3377 static void
riscv_regcache_cooked_write(int regnum,const gdb_byte * data,int len,struct regcache * regcache,int flen)3378 riscv_regcache_cooked_write (int regnum, const gdb_byte *data, int len,
3379                                    struct regcache *regcache, int flen)
3380 {
3381   gdb_byte tmp [sizeof (ULONGEST)];
3382 
3383   /* FP values in FP registers must be NaN-boxed.  */
3384   if (riscv_is_fp_regno_p (regnum) && len < flen)
3385     memset (tmp, -1, sizeof (tmp));
3386   else
3387     memset (tmp, 0, sizeof (tmp));
3388   memcpy (tmp, data, len);
3389   regcache->cooked_write (regnum, tmp);
3390 }
3391 
3392 /* Implement the push dummy call gdbarch callback.  */
3393 
3394 static CORE_ADDR
riscv_push_dummy_call(struct gdbarch * gdbarch,struct value * function,struct regcache * regcache,CORE_ADDR bp_addr,int nargs,struct value ** args,CORE_ADDR sp,function_call_return_method return_method,CORE_ADDR struct_addr)3395 riscv_push_dummy_call (struct gdbarch *gdbarch,
3396                            struct value *function,
3397                            struct regcache *regcache,
3398                            CORE_ADDR bp_addr,
3399                            int nargs,
3400                            struct value **args,
3401                            CORE_ADDR sp,
3402                            function_call_return_method return_method,
3403                            CORE_ADDR struct_addr)
3404 {
3405   int i;
3406   CORE_ADDR sp_args, sp_refs;
3407   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3408 
3409   struct riscv_arg_info *arg_info =
3410     (struct riscv_arg_info *) alloca (nargs * sizeof (struct riscv_arg_info));
3411 
3412   struct riscv_call_info call_info (gdbarch);
3413 
3414   CORE_ADDR osp = sp;
3415 
3416   struct type *ftype = check_typedef (function->type ());
3417 
3418   if (ftype->code () == TYPE_CODE_PTR)
3419     ftype = check_typedef (ftype->target_type ());
3420 
3421   /* We'll use register $a0 if we're returning a struct.  */
3422   if (return_method == return_method_struct)
3423     ++call_info.int_regs.next_regnum;
3424 
3425   for (i = 0; i < nargs; ++i)
3426     {
3427       struct value *arg_value;
3428       struct type *arg_type;
3429       struct riscv_arg_info *info = &arg_info[i];
3430 
3431       arg_value = args[i];
3432       arg_type = check_typedef (arg_value->type ());
3433 
3434       riscv_arg_location (gdbarch, info, &call_info, arg_type,
3435                                 ftype->has_varargs () && i >= ftype->num_fields ());
3436 
3437       if (info->type != arg_type)
3438           arg_value = value_cast (info->type, arg_value);
3439       info->contents = arg_value->contents ().data ();
3440     }
3441 
3442   /* Adjust the stack pointer and align it.  */
3443   sp = sp_refs = align_down (sp - call_info.memory.ref_offset, SP_ALIGNMENT);
3444   sp = sp_args = align_down (sp - call_info.memory.arg_offset, SP_ALIGNMENT);
3445 
3446   if (riscv_debug_infcall)
3447     {
3448       RISCV_INFCALL_SCOPED_DEBUG_START_END ("dummy call args");
3449       riscv_infcall_debug_printf ("floating point ABI %s in use",
3450                                           (riscv_has_fp_abi (gdbarch)
3451                                            ? "is" : "is not"));
3452       riscv_infcall_debug_printf ("xlen: %d", call_info.xlen);
3453       riscv_infcall_debug_printf ("flen: %d", call_info.flen);
3454       if (return_method == return_method_struct)
3455           riscv_infcall_debug_printf
3456             ("[**] struct return pointer in register $A0");
3457       for (i = 0; i < nargs; ++i)
3458           {
3459             struct riscv_arg_info *info = &arg_info [i];
3460             string_file tmp;
3461 
3462             riscv_print_arg_location (&tmp, gdbarch, info, sp_refs, sp_args);
3463             riscv_infcall_debug_printf ("[%2d] %s", i, tmp.string ().c_str ());
3464           }
3465       if (call_info.memory.arg_offset > 0
3466             || call_info.memory.ref_offset > 0)
3467           {
3468             riscv_infcall_debug_printf ("              Original sp: %s",
3469                                               core_addr_to_string (osp));
3470             riscv_infcall_debug_printf ("Stack required (for args): 0x%x",
3471                                               call_info.memory.arg_offset);
3472             riscv_infcall_debug_printf ("Stack required (for refs): 0x%x",
3473                                               call_info.memory.ref_offset);
3474             riscv_infcall_debug_printf ("          Stack allocated: %s",
3475                                               core_addr_to_string_nz (osp - sp));
3476           }
3477     }
3478 
3479   /* Now load the argument into registers, or onto the stack.  */
3480 
3481   if (return_method == return_method_struct)
3482     {
3483       gdb_byte buf[sizeof (LONGEST)];
3484 
3485       store_unsigned_integer (buf, call_info.xlen, byte_order, struct_addr);
3486       regcache->cooked_write (RISCV_A0_REGNUM, buf);
3487     }
3488 
3489   for (i = 0; i < nargs; ++i)
3490     {
3491       CORE_ADDR dst;
3492       int second_arg_length = 0;
3493       const gdb_byte *second_arg_data;
3494       struct riscv_arg_info *info = &arg_info [i];
3495 
3496       gdb_assert (info->length > 0);
3497 
3498       switch (info->argloc[0].loc_type)
3499           {
3500           case riscv_arg_info::location::in_reg:
3501             {
3502               gdb_assert (info->argloc[0].c_length <= info->length);
3503 
3504               riscv_regcache_cooked_write (info->argloc[0].loc_data.regno,
3505                                                    (info->contents
3506                                                     + info->argloc[0].c_offset),
3507                                                    info->argloc[0].c_length,
3508                                                    regcache, call_info.flen);
3509               second_arg_length =
3510                 (((info->argloc[0].c_length + info->argloc[0].c_offset) < info->length)
3511                  ? info->argloc[1].c_length : 0);
3512               second_arg_data = info->contents + info->argloc[1].c_offset;
3513             }
3514             break;
3515 
3516           case riscv_arg_info::location::on_stack:
3517             dst = sp_args + info->argloc[0].loc_data.offset;
3518             write_memory (dst, info->contents, info->length);
3519             second_arg_length = 0;
3520             break;
3521 
3522           case riscv_arg_info::location::by_ref:
3523             dst = sp_refs + info->argloc[0].loc_data.offset;
3524             write_memory (dst, info->contents, info->length);
3525 
3526             second_arg_length = call_info.xlen;
3527             second_arg_data = (gdb_byte *) &dst;
3528             break;
3529 
3530           default:
3531             gdb_assert_not_reached ("unknown argument location type");
3532           }
3533 
3534       if (second_arg_length > 0)
3535           {
3536             switch (info->argloc[1].loc_type)
3537               {
3538               case riscv_arg_info::location::in_reg:
3539                 {
3540                     gdb_assert ((riscv_is_fp_regno_p (info->argloc[1].loc_data.regno)
3541                                    && second_arg_length <= call_info.flen)
3542                                   || second_arg_length <= call_info.xlen);
3543                     riscv_regcache_cooked_write (info->argloc[1].loc_data.regno,
3544                                                        second_arg_data,
3545                                                        second_arg_length,
3546                                                        regcache, call_info.flen);
3547                 }
3548                 break;
3549 
3550               case riscv_arg_info::location::on_stack:
3551                 {
3552                     CORE_ADDR arg_addr;
3553 
3554                     arg_addr = sp_args + info->argloc[1].loc_data.offset;
3555                     write_memory (arg_addr, second_arg_data, second_arg_length);
3556                     break;
3557                 }
3558 
3559               case riscv_arg_info::location::by_ref:
3560               default:
3561                 /* The second location should never be a reference, any
3562                      argument being passed by reference just places its address
3563                      in the first location and is done.  */
3564                 error (_("invalid argument location"));
3565                 break;
3566               }
3567           }
3568     }
3569 
3570   /* Set the dummy return value to bp_addr.
3571      A dummy breakpoint will be setup to execute the call.  */
3572 
3573   riscv_infcall_debug_printf ("writing $ra = %s",
3574                                     core_addr_to_string (bp_addr));
3575   regcache_cooked_write_unsigned (regcache, RISCV_RA_REGNUM, bp_addr);
3576 
3577   /* Finally, update the stack pointer.  */
3578 
3579   riscv_infcall_debug_printf ("writing $sp = %s", core_addr_to_string (sp));
3580   regcache_cooked_write_unsigned (regcache, RISCV_SP_REGNUM, sp);
3581 
3582   return sp;
3583 }
3584 
3585 /* Implement the return_value gdbarch method.  */
3586 
3587 static enum return_value_convention
riscv_return_value(struct gdbarch * gdbarch,struct value * function,struct type * type,struct regcache * regcache,struct value ** read_value,const gdb_byte * writebuf)3588 riscv_return_value (struct gdbarch  *gdbarch,
3589                         struct value *function,
3590                         struct type *type,
3591                         struct regcache *regcache,
3592                         struct value **read_value,
3593                         const gdb_byte *writebuf)
3594 {
3595   struct riscv_call_info call_info (gdbarch);
3596   struct riscv_arg_info info;
3597   struct type *arg_type;
3598 
3599   arg_type = check_typedef (type);
3600   riscv_arg_location (gdbarch, &info, &call_info, arg_type, false);
3601 
3602   if (riscv_debug_infcall)
3603     {
3604       string_file tmp;
3605       riscv_print_arg_location (&tmp, gdbarch, &info, 0, 0);
3606       riscv_infcall_debug_printf ("[R] %s", tmp.string ().c_str ());
3607     }
3608 
3609   if (read_value != nullptr || writebuf != nullptr)
3610     {
3611       unsigned int arg_len;
3612       struct value *abi_val;
3613       gdb_byte *readbuf = nullptr;
3614       int regnum;
3615 
3616       /* We only do one thing at a time.  */
3617       gdb_assert (read_value == nullptr || writebuf == nullptr);
3618 
3619       /* In some cases the argument is not returned as the declared type,
3620            and we need to cast to or from the ABI type in order to
3621            correctly access the argument.  When writing to the machine we
3622            do the cast here, when reading from the machine the cast occurs
3623            later, after extracting the value.  As the ABI type can be
3624            larger than the declared type, then the read or write buffers
3625            passed in might be too small.  Here we ensure that we are using
3626            buffers of sufficient size.  */
3627       if (writebuf != nullptr)
3628           {
3629             struct value *arg_val;
3630 
3631             if (is_fixed_point_type (arg_type))
3632               {
3633                 /* Convert the argument to the type used to pass
3634                      the return value, but being careful to preserve
3635                      the fact that the value needs to be returned
3636                      unscaled.  */
3637                 gdb_mpz unscaled;
3638 
3639                 unscaled.read (gdb::make_array_view (writebuf,
3640                                                                arg_type->length ()),
3641                                    type_byte_order (arg_type),
3642                                    arg_type->is_unsigned ());
3643                 abi_val = value::allocate (info.type);
3644                 unscaled.write (abi_val->contents_raw (),
3645                                     type_byte_order (info.type),
3646                                     info.type->is_unsigned ());
3647               }
3648             else
3649               {
3650                 arg_val = value_from_contents (arg_type, writebuf);
3651                 abi_val = value_cast (info.type, arg_val);
3652               }
3653             writebuf = abi_val->contents_raw ().data ();
3654           }
3655       else
3656           {
3657             abi_val = value::allocate (info.type);
3658             readbuf = abi_val->contents_raw ().data ();
3659           }
3660       arg_len = info.type->length ();
3661 
3662       switch (info.argloc[0].loc_type)
3663           {
3664             /* Return value in register(s).  */
3665           case riscv_arg_info::location::in_reg:
3666             {
3667               regnum = info.argloc[0].loc_data.regno;
3668               gdb_assert (info.argloc[0].c_length <= arg_len);
3669               gdb_assert (info.argloc[0].c_length
3670                               <= register_size (gdbarch, regnum));
3671 
3672               if (readbuf)
3673                 {
3674                     gdb_byte *ptr = readbuf + info.argloc[0].c_offset;
3675                     regcache->cooked_read_part (regnum, 0,
3676                                                       info.argloc[0].c_length,
3677                                                       ptr);
3678                 }
3679 
3680               if (writebuf)
3681                 {
3682                     const gdb_byte *ptr = writebuf + info.argloc[0].c_offset;
3683                     riscv_regcache_cooked_write (regnum, ptr,
3684                                                        info.argloc[0].c_length,
3685                                                        regcache, call_info.flen);
3686                 }
3687 
3688               /* A return value in register can have a second part in a
3689                  second register.  */
3690               if (info.argloc[1].c_length > 0)
3691                 {
3692                     switch (info.argloc[1].loc_type)
3693                       {
3694                       case riscv_arg_info::location::in_reg:
3695                         regnum = info.argloc[1].loc_data.regno;
3696 
3697                         gdb_assert ((info.argloc[0].c_length
3698                                          + info.argloc[1].c_length) <= arg_len);
3699                         gdb_assert (info.argloc[1].c_length
3700                                         <= register_size (gdbarch, regnum));
3701 
3702                         if (readbuf)
3703                           {
3704                               readbuf += info.argloc[1].c_offset;
3705                               regcache->cooked_read_part (regnum, 0,
3706                                                                 info.argloc[1].c_length,
3707                                                                 readbuf);
3708                           }
3709 
3710                         if (writebuf)
3711                           {
3712                               const gdb_byte *ptr
3713                                 = writebuf + info.argloc[1].c_offset;
3714                               riscv_regcache_cooked_write
3715                                 (regnum, ptr, info.argloc[1].c_length,
3716                                  regcache, call_info.flen);
3717                           }
3718                         break;
3719 
3720                       case riscv_arg_info::location::by_ref:
3721                       case riscv_arg_info::location::on_stack:
3722                       default:
3723                         error (_("invalid argument location"));
3724                         break;
3725                       }
3726                 }
3727             }
3728             break;
3729 
3730             /* Return value by reference will have its address in A0.  */
3731           case riscv_arg_info::location::by_ref:
3732             {
3733               ULONGEST addr;
3734 
3735               regcache_cooked_read_unsigned (regcache, RISCV_A0_REGNUM,
3736                                                      &addr);
3737               if (read_value != nullptr)
3738                 {
3739                     abi_val = value_at_non_lval (type, addr);
3740                     /* Also reset the expected type, so that the cast
3741                        later on is a no-op.  If the cast is not a no-op,
3742                        and if the return type is variably-sized, then the
3743                        type of ABI_VAL will differ from ARG_TYPE due to
3744                        dynamic type resolution, and so will most likely
3745                        fail.  */
3746                     arg_type = abi_val->type ();
3747                 }
3748               if (writebuf != nullptr)
3749                 write_memory (addr, writebuf, info.length);
3750             }
3751             break;
3752 
3753           case riscv_arg_info::location::on_stack:
3754           default:
3755             error (_("invalid argument location"));
3756             break;
3757           }
3758 
3759       /* This completes the cast from abi type back to the declared type
3760            in the case that we are reading from the machine.  See the
3761            comment at the head of this block for more details.  */
3762       if (read_value != nullptr)
3763           {
3764             if (is_fixed_point_type (arg_type))
3765               {
3766                 /* Convert abi_val to the actual return type, but
3767                      being careful to preserve the fact that abi_val
3768                      is unscaled.  */
3769                 gdb_mpz unscaled;
3770 
3771                 unscaled.read (abi_val->contents (),
3772                                    type_byte_order (info.type),
3773                                    info.type->is_unsigned ());
3774                 *read_value = value::allocate (arg_type);
3775                 unscaled.write ((*read_value)->contents_raw (),
3776                                     type_byte_order (arg_type),
3777                                     arg_type->is_unsigned ());
3778               }
3779             else
3780               *read_value = value_cast (arg_type, abi_val);
3781           }
3782     }
3783 
3784   switch (info.argloc[0].loc_type)
3785     {
3786     case riscv_arg_info::location::in_reg:
3787       return RETURN_VALUE_REGISTER_CONVENTION;
3788     case riscv_arg_info::location::by_ref:
3789       return RETURN_VALUE_ABI_PRESERVES_ADDRESS;
3790     case riscv_arg_info::location::on_stack:
3791     default:
3792       error (_("invalid argument location"));
3793     }
3794 }
3795 
3796 /* Implement the frame_align gdbarch method.  */
3797 
3798 static CORE_ADDR
riscv_frame_align(struct gdbarch * gdbarch,CORE_ADDR addr)3799 riscv_frame_align (struct gdbarch *gdbarch, CORE_ADDR addr)
3800 {
3801   return align_down (addr, 16);
3802 }
3803 
3804 /* Generate, or return the cached frame cache for the RiscV frame
3805    unwinder.  */
3806 
3807 static struct riscv_unwind_cache *
riscv_frame_cache(const frame_info_ptr & this_frame,void ** this_cache)3808 riscv_frame_cache (const frame_info_ptr &this_frame, void **this_cache)
3809 {
3810   CORE_ADDR pc, start_addr;
3811   struct riscv_unwind_cache *cache;
3812   struct gdbarch *gdbarch = get_frame_arch (this_frame);
3813   int numregs, regno;
3814 
3815   if ((*this_cache) != NULL)
3816     return (struct riscv_unwind_cache *) *this_cache;
3817 
3818   cache = FRAME_OBSTACK_ZALLOC (struct riscv_unwind_cache);
3819   cache->regs = trad_frame_alloc_saved_regs (this_frame);
3820   (*this_cache) = cache;
3821 
3822   /* Scan the prologue, filling in the cache.  */
3823   start_addr = get_frame_func (this_frame);
3824   pc = get_frame_pc (this_frame);
3825   riscv_scan_prologue (gdbarch, start_addr, pc, cache);
3826 
3827   /* We can now calculate the frame base address.  */
3828   cache->frame_base
3829     = (get_frame_register_unsigned (this_frame, cache->frame_base_reg)
3830        + cache->frame_base_offset);
3831   riscv_unwinder_debug_printf ("frame base is %s ($%s + 0x%x)",
3832                                      core_addr_to_string (cache->frame_base),
3833                                      gdbarch_register_name (gdbarch,
3834                                                                   cache->frame_base_reg),
3835                                      cache->frame_base_offset);
3836 
3837   /* The prologue scanner sets the address of registers stored to the stack
3838      as the offset of that register from the frame base.  The prologue
3839      scanner doesn't know the actual frame base value, and so is unable to
3840      compute the exact address.  We do now know the frame base value, so
3841      update the address of registers stored to the stack.  */
3842   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
3843   for (regno = 0; regno < numregs; ++regno)
3844     {
3845       if (cache->regs[regno].is_addr ())
3846           cache->regs[regno].set_addr (cache->regs[regno].addr ()
3847                                              + cache->frame_base);
3848     }
3849 
3850   /* The previous $pc can be found wherever the $ra value can be found.
3851      The previous $ra value is gone, this would have been stored be the
3852      previous frame if required.  */
3853   cache->regs[gdbarch_pc_regnum (gdbarch)] = cache->regs[RISCV_RA_REGNUM];
3854   cache->regs[RISCV_RA_REGNUM].set_unknown ();
3855 
3856   /* Build the frame id.  */
3857   cache->this_id = frame_id_build (cache->frame_base, start_addr);
3858 
3859   /* The previous $sp value is the frame base value.  */
3860   cache->regs[gdbarch_sp_regnum (gdbarch)].set_value (cache->frame_base);
3861 
3862   return cache;
3863 }
3864 
3865 /* Implement the this_id callback for RiscV frame unwinder.  */
3866 
3867 static void
riscv_frame_this_id(const frame_info_ptr & this_frame,void ** prologue_cache,struct frame_id * this_id)3868 riscv_frame_this_id (const frame_info_ptr &this_frame,
3869                          void **prologue_cache,
3870                          struct frame_id *this_id)
3871 {
3872   struct riscv_unwind_cache *cache;
3873 
3874   try
3875     {
3876       cache = riscv_frame_cache (this_frame, prologue_cache);
3877       *this_id = cache->this_id;
3878     }
3879   catch (const gdb_exception_error &ex)
3880     {
3881       /* Ignore errors, this leaves the frame id as the predefined outer
3882            frame id which terminates the backtrace at this point.  */
3883     }
3884 }
3885 
3886 /* Implement the prev_register callback for RiscV frame unwinder.  */
3887 
3888 static struct value *
riscv_frame_prev_register(const frame_info_ptr & this_frame,void ** prologue_cache,int regnum)3889 riscv_frame_prev_register (const frame_info_ptr &this_frame,
3890                                  void **prologue_cache,
3891                                  int regnum)
3892 {
3893   struct riscv_unwind_cache *cache;
3894 
3895   cache = riscv_frame_cache (this_frame, prologue_cache);
3896   return trad_frame_get_prev_register (this_frame, cache->regs, regnum);
3897 }
3898 
3899 /* Structure defining the RiscV normal frame unwind functions.  Since we
3900    are the fallback unwinder (DWARF unwinder is used first), we use the
3901    default frame sniffer, which always accepts the frame.  */
3902 
3903 static const struct frame_unwind riscv_frame_unwind =
3904 {
3905   /*.name          =*/ "riscv prologue",
3906   /*.type          =*/ NORMAL_FRAME,
3907   /*.stop_reason   =*/ default_frame_unwind_stop_reason,
3908   /*.this_id       =*/ riscv_frame_this_id,
3909   /*.prev_register =*/ riscv_frame_prev_register,
3910   /*.unwind_data   =*/ NULL,
3911   /*.sniffer       =*/ default_frame_sniffer,
3912   /*.dealloc_cache =*/ NULL,
3913   /*.prev_arch     =*/ NULL,
3914 };
3915 
3916 /* Extract a set of required target features out of ABFD.  If ABFD is
3917    nullptr then a RISCV_GDBARCH_FEATURES is returned in its default state.  */
3918 
3919 static struct riscv_gdbarch_features
riscv_features_from_bfd(const bfd * abfd)3920 riscv_features_from_bfd (const bfd *abfd)
3921 {
3922   struct riscv_gdbarch_features features;
3923 
3924   /* Now try to improve on the defaults by looking at the binary we are
3925      going to execute.  We assume the user knows what they are doing and
3926      that the target will match the binary.  Remember, this code path is
3927      only used at all if the target hasn't given us a description, so this
3928      is really a last ditched effort to do something sane before giving
3929      up.  */
3930   if (abfd != nullptr && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
3931     {
3932       unsigned char eclass = elf_elfheader (abfd)->e_ident[EI_CLASS];
3933       int e_flags = elf_elfheader (abfd)->e_flags;
3934 
3935       if (eclass == ELFCLASS32)
3936           features.xlen = 4;
3937       else if (eclass == ELFCLASS64)
3938           features.xlen = 8;
3939       else
3940           internal_error (_("unknown ELF header class %d"), eclass);
3941 
3942       if (e_flags & EF_RISCV_FLOAT_ABI_DOUBLE)
3943           features.flen = 8;
3944       else if (e_flags & EF_RISCV_FLOAT_ABI_SINGLE)
3945           features.flen = 4;
3946 
3947       if (e_flags & EF_RISCV_RVE)
3948           {
3949             if (features.xlen == 8)
3950               {
3951                 warning (_("64-bit ELF with RV32E flag set!  Assuming 32-bit"));
3952                 features.xlen = 4;
3953               }
3954             features.embedded = true;
3955           }
3956     }
3957 
3958   return features;
3959 }
3960 
3961 /* Find a suitable default target description.  Use the contents of INFO,
3962    specifically the bfd object being executed, to guide the selection of a
3963    suitable default target description.  */
3964 
3965 static const struct target_desc *
riscv_find_default_target_description(const struct gdbarch_info info)3966 riscv_find_default_target_description (const struct gdbarch_info info)
3967 {
3968   /* Extract desired feature set from INFO.  */
3969   struct riscv_gdbarch_features features
3970     = riscv_features_from_bfd (info.abfd);
3971 
3972   /* If the XLEN field is still 0 then we got nothing useful from INFO.BFD,
3973      maybe there was no bfd object.  In this case we fall back to a minimal
3974      useful target with no floating point, the x-register size is selected
3975      based on the architecture from INFO.  */
3976   if (features.xlen == 0)
3977     features.xlen = info.bfd_arch_info->bits_per_word == 32 ? 4 : 8;
3978 
3979   /* Now build a target description based on the feature set.  */
3980   return riscv_lookup_target_description (features);
3981 }
3982 
3983 /* Add all the RISC-V specific register groups into GDBARCH.  */
3984 
3985 static void
riscv_add_reggroups(struct gdbarch * gdbarch)3986 riscv_add_reggroups (struct gdbarch *gdbarch)
3987 {
3988   reggroup_add (gdbarch, csr_reggroup);
3989 }
3990 
3991 /* Implement the "dwarf2_reg_to_regnum" gdbarch method.  */
3992 
3993 static int
riscv_dwarf_reg_to_regnum(struct gdbarch * gdbarch,int reg)3994 riscv_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
3995 {
3996   if (reg <= RISCV_DWARF_REGNUM_X31)
3997     return RISCV_ZERO_REGNUM + (reg - RISCV_DWARF_REGNUM_X0);
3998 
3999   else if (reg <= RISCV_DWARF_REGNUM_F31)
4000     return RISCV_FIRST_FP_REGNUM + (reg - RISCV_DWARF_REGNUM_F0);
4001 
4002   else if (reg >= RISCV_DWARF_FIRST_CSR && reg <= RISCV_DWARF_LAST_CSR)
4003     return RISCV_FIRST_CSR_REGNUM + (reg - RISCV_DWARF_FIRST_CSR);
4004 
4005   else if (reg >= RISCV_DWARF_REGNUM_V0 && reg <= RISCV_DWARF_REGNUM_V31)
4006     return RISCV_V0_REGNUM + (reg - RISCV_DWARF_REGNUM_V0);
4007 
4008   return -1;
4009 }
4010 
4011 /* Implement the gcc_target_options method.  We have to select the arch and abi
4012    from the feature info.  We have enough feature info to select the abi, but
4013    not enough info for the arch given all of the possible architecture
4014    extensions.  So choose reasonable defaults for now.  */
4015 
4016 static std::string
riscv_gcc_target_options(struct gdbarch * gdbarch)4017 riscv_gcc_target_options (struct gdbarch *gdbarch)
4018 {
4019   int isa_xlen = riscv_isa_xlen (gdbarch);
4020   int isa_flen = riscv_isa_flen (gdbarch);
4021   int abi_xlen = riscv_abi_xlen (gdbarch);
4022   int abi_flen = riscv_abi_flen (gdbarch);
4023   std::string target_options;
4024 
4025   target_options = "-march=rv";
4026   if (isa_xlen == 8)
4027     target_options += "64";
4028   else
4029     target_options += "32";
4030   if (isa_flen == 8)
4031     target_options += "gc";
4032   else if (isa_flen == 4)
4033     target_options += "imafc";
4034   else
4035     target_options += "imac";
4036 
4037   target_options += " -mabi=";
4038   if (abi_xlen == 8)
4039     target_options += "lp64";
4040   else
4041     target_options += "ilp32";
4042   if (abi_flen == 8)
4043     target_options += "d";
4044   else if (abi_flen == 4)
4045     target_options += "f";
4046 
4047   /* The gdb loader doesn't handle link-time relaxation relocations.  */
4048   target_options += " -mno-relax";
4049 
4050   return target_options;
4051 }
4052 
4053 /* Call back from tdesc_use_registers, called for each unknown register
4054    found in the target description.
4055 
4056    See target-description.h (typedef tdesc_unknown_register_ftype) for a
4057    discussion of the arguments and return values.  */
4058 
4059 static int
riscv_tdesc_unknown_reg(struct gdbarch * gdbarch,tdesc_feature * feature,const char * reg_name,int possible_regnum)4060 riscv_tdesc_unknown_reg (struct gdbarch *gdbarch, tdesc_feature *feature,
4061                                const char *reg_name, int possible_regnum)
4062 {
4063   /* At one point in time GDB had an incorrect default target description
4064      that duplicated the fflags, frm, and fcsr registers in both the FPU
4065      and CSR register sets.
4066 
4067      Some targets (QEMU) copied these target descriptions into their source
4068      tree, and so we're now stuck working with some versions of QEMU that
4069      declare the same registers twice.
4070 
4071      To make matters worse, if GDB tries to read or write to these
4072      registers using the register number assigned in the FPU feature set,
4073      then QEMU will fail to read the register, so we must use the register
4074      number declared in the CSR feature set.
4075 
4076      Luckily, GDB scans the FPU feature first, and then the CSR feature,
4077      which means that the CSR feature will be the one we end up using, the
4078      versions of these registers in the FPU feature will appear as unknown
4079      registers and will be passed through to this code.
4080 
4081      To prevent these duplicate registers showing up in any of the register
4082      lists, and to prevent GDB every trying to access the FPU feature copies,
4083      we spot the three problematic registers here, and record the register
4084      number that GDB has assigned them.  Then in riscv_register_name we will
4085      return no name for the three duplicates, this hides the duplicates from
4086      the user.  */
4087   if (strcmp (tdesc_feature_name (feature), riscv_freg_feature.name ()) == 0)
4088     {
4089       riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4090       int *regnum_ptr = nullptr;
4091 
4092       if (strcmp (reg_name, "fflags") == 0)
4093           regnum_ptr = &tdep->duplicate_fflags_regnum;
4094       else if (strcmp (reg_name, "frm") == 0)
4095           regnum_ptr = &tdep->duplicate_frm_regnum;
4096       else if (strcmp (reg_name, "fcsr") == 0)
4097           regnum_ptr = &tdep->duplicate_fcsr_regnum;
4098 
4099       if (regnum_ptr != nullptr)
4100           {
4101             /* This means the register appears more than twice in the target
4102                description.  Just let GDB add this as another register.
4103                We'll have duplicates in the register name list, but there's
4104                not much more we can do.  */
4105             if (*regnum_ptr != -1)
4106               return -1;
4107 
4108             /* Record the number assigned to this register, then return the
4109                number (so it actually gets assigned to this register).  */
4110             *regnum_ptr = possible_regnum;
4111             return possible_regnum;
4112           }
4113     }
4114 
4115   /* Any unknown registers in the CSR feature are recorded within a single
4116      block so we can easily identify these registers when making choices
4117      about register groups in riscv_register_reggroup_p.  */
4118   if (strcmp (tdesc_feature_name (feature), riscv_csr_feature.name ()) == 0)
4119     {
4120       riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4121       if (tdep->unknown_csrs_first_regnum == -1)
4122           tdep->unknown_csrs_first_regnum = possible_regnum;
4123       gdb_assert (tdep->unknown_csrs_first_regnum
4124                       + tdep->unknown_csrs_count == possible_regnum);
4125       tdep->unknown_csrs_count++;
4126       return possible_regnum;
4127     }
4128 
4129   /* Some other unknown register.  Don't assign this a number now, it will
4130      be assigned a number automatically later by the target description
4131      handling code.  */
4132   return -1;
4133 }
4134 
4135 /* Implement the gnu_triplet_regexp method.  A single compiler supports both
4136    32-bit and 64-bit code, and may be named riscv32 or riscv64 or (not
4137    recommended) riscv.  */
4138 
4139 static const char *
riscv_gnu_triplet_regexp(struct gdbarch * gdbarch)4140 riscv_gnu_triplet_regexp (struct gdbarch *gdbarch)
4141 {
4142   return "riscv(32|64)?";
4143 }
4144 
4145 /* Implementation of `gdbarch_stap_is_single_operand', as defined in
4146    gdbarch.h.  */
4147 
4148 static int
riscv_stap_is_single_operand(struct gdbarch * gdbarch,const char * s)4149 riscv_stap_is_single_operand (struct gdbarch *gdbarch, const char *s)
4150 {
4151   return (ISDIGIT (*s) /* Literal number.  */
4152             || *s == '(' /* Register indirection.  */
4153             || ISALPHA (*s)); /* Register value.  */
4154 }
4155 
4156 /* String that appears before a register name in a SystemTap register
4157    indirect expression.  */
4158 
4159 static const char *const stap_register_indirection_prefixes[] =
4160 {
4161   "(", nullptr
4162 };
4163 
4164 /* String that appears after a register name in a SystemTap register
4165    indirect expression.  */
4166 
4167 static const char *const stap_register_indirection_suffixes[] =
4168 {
4169   ")", nullptr
4170 };
4171 
4172 /* Initialize the current architecture based on INFO.  If possible,
4173    re-use an architecture from ARCHES, which is a list of
4174    architectures already created during this debugging session.
4175 
4176    Called e.g. at program startup, when reading a core file, and when
4177    reading a binary file.  */
4178 
4179 static struct gdbarch *
riscv_gdbarch_init(struct gdbarch_info info,struct gdbarch_list * arches)4180 riscv_gdbarch_init (struct gdbarch_info info,
4181                         struct gdbarch_list *arches)
4182 {
4183   struct riscv_gdbarch_features features;
4184   const struct target_desc *tdesc = info.target_desc;
4185 
4186   /* Ensure we always have a target description.  */
4187   if (!tdesc_has_registers (tdesc))
4188     tdesc = riscv_find_default_target_description (info);
4189   gdb_assert (tdesc != nullptr);
4190 
4191   riscv_gdbarch_debug_printf ("have got a target description");
4192 
4193   tdesc_arch_data_up tdesc_data = tdesc_data_alloc ();
4194   std::vector<riscv_pending_register_alias> pending_aliases;
4195 
4196   bool valid_p = (riscv_xreg_feature.check (tdesc, tdesc_data.get (),
4197                                                       &pending_aliases, &features)
4198                       && riscv_freg_feature.check (tdesc, tdesc_data.get (),
4199                                                          &pending_aliases, &features)
4200                       && riscv_virtual_feature.check (tdesc, tdesc_data.get (),
4201                                                               &pending_aliases, &features)
4202                       && riscv_csr_feature.check (tdesc, tdesc_data.get (),
4203                                                         &pending_aliases, &features)
4204                       && riscv_vector_feature.check (tdesc, tdesc_data.get (),
4205                                                              &pending_aliases, &features));
4206   if (!valid_p)
4207     {
4208       riscv_gdbarch_debug_printf ("target description is not valid");
4209       return NULL;
4210     }
4211 
4212   if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FFLAGS_REGNUM))
4213     features.has_fflags_reg = true;
4214   if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FRM_REGNUM))
4215     features.has_frm_reg = true;
4216   if (tdesc_found_register (tdesc_data.get (), RISCV_CSR_FCSR_REGNUM))
4217     features.has_fcsr_reg = true;
4218 
4219   /* Have a look at what the supplied (if any) bfd object requires of the
4220      target, then check that this matches with what the target is
4221      providing.  */
4222   struct riscv_gdbarch_features abi_features
4223     = riscv_features_from_bfd (info.abfd);
4224 
4225   /* If the ABI_FEATURES xlen is 0 then this indicates we got no useful abi
4226      features from the INFO object.  In this case we just treat the
4227      hardware features as defining the abi.  */
4228   if (abi_features.xlen == 0)
4229     abi_features = features;
4230 
4231   /* In theory a binary compiled for RV32 could run on an RV64 target,
4232      however, this has not been tested in GDB yet, so for now we require
4233      that the requested xlen match the targets xlen.  */
4234   if (abi_features.xlen != features.xlen)
4235     error (_("bfd requires xlen %d, but target has xlen %d"),
4236               abi_features.xlen, features.xlen);
4237   /* We do support running binaries compiled for 32-bit float on targets
4238      with 64-bit float, so we only complain if the binary requires more
4239      than the target has available.  */
4240   if (abi_features.flen > features.flen)
4241     error (_("bfd requires flen %d, but target has flen %d"),
4242               abi_features.flen, features.flen);
4243 
4244   /* Find a candidate among the list of pre-declared architectures.  */
4245   for (arches = gdbarch_list_lookup_by_info (arches, &info);
4246        arches != NULL;
4247        arches = gdbarch_list_lookup_by_info (arches->next, &info))
4248     {
4249       /* Check that the feature set of the ARCHES matches the feature set
4250            we are looking for.  If it doesn't then we can't reuse this
4251            gdbarch.  */
4252       riscv_gdbarch_tdep *other_tdep
4253           = gdbarch_tdep<riscv_gdbarch_tdep> (arches->gdbarch);
4254 
4255       if (other_tdep->isa_features != features
4256             || other_tdep->abi_features != abi_features)
4257           continue;
4258 
4259       break;
4260     }
4261 
4262   if (arches != NULL)
4263     return arches->gdbarch;
4264 
4265   /* None found, so create a new architecture from the information provided.  */
4266   gdbarch *gdbarch
4267     = gdbarch_alloc (&info, gdbarch_tdep_up (new riscv_gdbarch_tdep));
4268   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4269 
4270   tdep->isa_features = features;
4271   tdep->abi_features = abi_features;
4272 
4273   /* Target data types.  */
4274   set_gdbarch_short_bit (gdbarch, 16);
4275   set_gdbarch_int_bit (gdbarch, 32);
4276   set_gdbarch_long_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4277   set_gdbarch_long_long_bit (gdbarch, 64);
4278   set_gdbarch_float_bit (gdbarch, 32);
4279   set_gdbarch_double_bit (gdbarch, 64);
4280   set_gdbarch_long_double_bit (gdbarch, 128);
4281   set_gdbarch_long_double_format (gdbarch, floatformats_ieee_quad);
4282   set_gdbarch_ptr_bit (gdbarch, riscv_isa_xlen (gdbarch) * 8);
4283   set_gdbarch_char_signed (gdbarch, 0);
4284   set_gdbarch_type_align (gdbarch, riscv_type_align);
4285 
4286   /* Information about the target architecture.  */
4287   set_gdbarch_return_value_as_value (gdbarch, riscv_return_value);
4288   set_gdbarch_breakpoint_kind_from_pc (gdbarch, riscv_breakpoint_kind_from_pc);
4289   set_gdbarch_sw_breakpoint_from_kind (gdbarch, riscv_sw_breakpoint_from_kind);
4290   set_gdbarch_have_nonsteppable_watchpoint (gdbarch, 1);
4291 
4292   /* Functions to analyze frames.  */
4293   set_gdbarch_skip_prologue (gdbarch, riscv_skip_prologue);
4294   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
4295   set_gdbarch_frame_align (gdbarch, riscv_frame_align);
4296 
4297   /* Functions handling dummy frames.  */
4298   set_gdbarch_call_dummy_location (gdbarch, ON_STACK);
4299   set_gdbarch_push_dummy_code (gdbarch, riscv_push_dummy_code);
4300   set_gdbarch_push_dummy_call (gdbarch, riscv_push_dummy_call);
4301 
4302   /* Frame unwinders.  Use DWARF debug info if available, otherwise use our own
4303      unwinder.  */
4304   dwarf2_append_unwinders (gdbarch);
4305   frame_unwind_append_unwinder (gdbarch, &riscv_frame_unwind);
4306 
4307   /* Register architecture.  */
4308   riscv_add_reggroups (gdbarch);
4309 
4310   /* Internal <-> external register number maps.  */
4311   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, riscv_dwarf_reg_to_regnum);
4312 
4313   /* We reserve all possible register numbers for the known registers.
4314      This means the target description mechanism will add any target
4315      specific registers after this number.  This helps make debugging GDB
4316      just a little easier.  */
4317   set_gdbarch_num_regs (gdbarch, RISCV_LAST_REGNUM + 1);
4318 
4319   /* Some specific register numbers GDB likes to know about.  */
4320   set_gdbarch_sp_regnum (gdbarch, RISCV_SP_REGNUM);
4321   set_gdbarch_pc_regnum (gdbarch, RISCV_PC_REGNUM);
4322 
4323   set_gdbarch_print_registers_info (gdbarch, riscv_print_registers_info);
4324 
4325   set_tdesc_pseudo_register_name (gdbarch, riscv_pseudo_register_name);
4326   set_tdesc_pseudo_register_type (gdbarch, riscv_pseudo_register_type);
4327   set_tdesc_pseudo_register_reggroup_p (gdbarch,
4328                                                   riscv_pseudo_register_reggroup_p);
4329   set_gdbarch_pseudo_register_read (gdbarch, riscv_pseudo_register_read);
4330   set_gdbarch_deprecated_pseudo_register_write (gdbarch,
4331                                                             riscv_pseudo_register_write);
4332 
4333   /* Finalise the target description registers.  */
4334   tdesc_use_registers (gdbarch, tdesc, std::move (tdesc_data),
4335                            riscv_tdesc_unknown_reg);
4336 
4337   /* Calculate the number of pseudo registers we need.  The fflags and frm
4338      registers are sub-fields of the fcsr CSR register (csr3).  However,
4339      these registers can also be accessed directly as separate CSR
4340      registers (fflags is csr1, and frm is csr2).  And so, some targets
4341      might choose to offer direct access to all three registers in the
4342      target description, while other targets might choose to only offer
4343      access to fcsr.
4344 
4345      As we scan the target description we spot which of fcsr, fflags, and
4346      frm are available.  If fcsr is available but either of fflags and/or
4347      frm are not available, then we add pseudo-registers to provide the
4348      missing functionality.
4349 
4350      This has to be done after the call to tdesc_use_registers as we don't
4351      know the final register number until after that call, and the pseudo
4352      register numbers need to be after the physical registers.  */
4353   int num_pseudo_regs = 0;
4354   int next_pseudo_regnum = gdbarch_num_regs (gdbarch);
4355 
4356   if (features.has_fflags_reg)
4357     tdep->fflags_regnum = RISCV_CSR_FFLAGS_REGNUM;
4358   else if (features.has_fcsr_reg)
4359     {
4360       tdep->fflags_regnum = next_pseudo_regnum;
4361       pending_aliases.emplace_back ("csr1", (void *) &tdep->fflags_regnum);
4362       next_pseudo_regnum++;
4363       num_pseudo_regs++;
4364     }
4365 
4366   if (features.has_frm_reg)
4367     tdep->frm_regnum = RISCV_CSR_FRM_REGNUM;
4368   else if (features.has_fcsr_reg)
4369     {
4370       tdep->frm_regnum = next_pseudo_regnum;
4371       pending_aliases.emplace_back ("csr2", (void *) &tdep->frm_regnum);
4372       next_pseudo_regnum++;
4373       num_pseudo_regs++;
4374     }
4375 
4376   set_gdbarch_num_pseudo_regs (gdbarch, num_pseudo_regs);
4377 
4378   /* Override the register type callback setup by the target description
4379      mechanism.  This allows us to provide special type for floating point
4380      registers.  */
4381   set_gdbarch_register_type (gdbarch, riscv_register_type);
4382 
4383   /* Override the register name callback setup by the target description
4384      mechanism.  This allows us to force our preferred names for the
4385      registers, no matter what the target description called them.  */
4386   set_gdbarch_register_name (gdbarch, riscv_register_name);
4387 
4388   /* Tell GDB which RISC-V registers are read-only. */
4389   set_gdbarch_cannot_store_register (gdbarch, riscv_cannot_store_register);
4390 
4391   /* Override the register group callback setup by the target description
4392      mechanism.  This allows us to force registers into the groups we
4393      want, ignoring what the target tells us.  */
4394   set_gdbarch_register_reggroup_p (gdbarch, riscv_register_reggroup_p);
4395 
4396   /* Create register aliases for alternative register names.  We only
4397      create aliases for registers which were mentioned in the target
4398      description.  */
4399   for (const auto &alias : pending_aliases)
4400     alias.create (gdbarch);
4401 
4402   /* Compile command hooks.  */
4403   set_gdbarch_gcc_target_options (gdbarch, riscv_gcc_target_options);
4404   set_gdbarch_gnu_triplet_regexp (gdbarch, riscv_gnu_triplet_regexp);
4405 
4406   /* Disassembler options support.  */
4407   set_gdbarch_valid_disassembler_options (gdbarch,
4408                                                     disassembler_options_riscv ());
4409   set_gdbarch_disassembler_options (gdbarch, &riscv_disassembler_options);
4410 
4411   /* SystemTap Support.  */
4412   set_gdbarch_stap_is_single_operand (gdbarch, riscv_stap_is_single_operand);
4413   set_gdbarch_stap_register_indirection_prefixes
4414     (gdbarch, stap_register_indirection_prefixes);
4415   set_gdbarch_stap_register_indirection_suffixes
4416     (gdbarch, stap_register_indirection_suffixes);
4417 
4418   /* Hook in OS ABI-specific overrides, if they have been registered.  */
4419   gdbarch_init_osabi (info, gdbarch);
4420 
4421   register_riscv_ravenscar_ops (gdbarch);
4422 
4423   return gdbarch;
4424 }
4425 
4426 /* This decodes the current instruction and determines the address of the
4427    next instruction.  */
4428 
4429 static CORE_ADDR
riscv_next_pc(struct regcache * regcache,CORE_ADDR pc)4430 riscv_next_pc (struct regcache *regcache, CORE_ADDR pc)
4431 {
4432   struct gdbarch *gdbarch = regcache->arch ();
4433   const riscv_gdbarch_tdep *tdep
4434     = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4435   struct riscv_insn insn;
4436   CORE_ADDR next_pc;
4437 
4438   insn.decode (gdbarch, pc);
4439   next_pc = pc + insn.length ();
4440 
4441   if (insn.opcode () == riscv_insn::JAL)
4442     next_pc = pc + insn.imm_signed ();
4443   else if (insn.opcode () == riscv_insn::JALR)
4444     {
4445       LONGEST source;
4446       regcache->cooked_read (insn.rs1 (), &source);
4447       next_pc = (source + insn.imm_signed ()) & ~(CORE_ADDR) 0x1;
4448     }
4449   else if (insn.opcode () == riscv_insn::BEQ)
4450     {
4451       LONGEST src1, src2;
4452       regcache->cooked_read (insn.rs1 (), &src1);
4453       regcache->cooked_read (insn.rs2 (), &src2);
4454       if (src1 == src2)
4455           next_pc = pc + insn.imm_signed ();
4456     }
4457   else if (insn.opcode () == riscv_insn::BNE)
4458     {
4459       LONGEST src1, src2;
4460       regcache->cooked_read (insn.rs1 (), &src1);
4461       regcache->cooked_read (insn.rs2 (), &src2);
4462       if (src1 != src2)
4463           next_pc = pc + insn.imm_signed ();
4464     }
4465   else if (insn.opcode () == riscv_insn::BLT)
4466     {
4467       LONGEST src1, src2;
4468       regcache->cooked_read (insn.rs1 (), &src1);
4469       regcache->cooked_read (insn.rs2 (), &src2);
4470       if (src1 < src2)
4471           next_pc = pc + insn.imm_signed ();
4472     }
4473   else if (insn.opcode () == riscv_insn::BGE)
4474     {
4475       LONGEST src1, src2;
4476       regcache->cooked_read (insn.rs1 (), &src1);
4477       regcache->cooked_read (insn.rs2 (), &src2);
4478       if (src1 >= src2)
4479           next_pc = pc + insn.imm_signed ();
4480     }
4481   else if (insn.opcode () == riscv_insn::BLTU)
4482     {
4483       ULONGEST src1, src2;
4484       regcache->cooked_read (insn.rs1 (), &src1);
4485       regcache->cooked_read (insn.rs2 (), &src2);
4486       if (src1 < src2)
4487           next_pc = pc + insn.imm_signed ();
4488     }
4489   else if (insn.opcode () == riscv_insn::BGEU)
4490     {
4491       ULONGEST src1, src2;
4492       regcache->cooked_read (insn.rs1 (), &src1);
4493       regcache->cooked_read (insn.rs2 (), &src2);
4494       if (src1 >= src2)
4495           next_pc = pc + insn.imm_signed ();
4496     }
4497   else if (insn.opcode () == riscv_insn::ECALL)
4498     {
4499       if (tdep->syscall_next_pc != nullptr)
4500           next_pc = tdep->syscall_next_pc (get_current_frame ());
4501     }
4502 
4503   return next_pc;
4504 }
4505 
4506 /* Return true if INSN is not a control transfer instruction and is allowed to
4507    appear in the middle of the lr/sc sequence.  */
4508 
4509 static bool
riscv_insn_is_non_cti_and_allowed_in_atomic_sequence(const struct riscv_insn & insn)4510 riscv_insn_is_non_cti_and_allowed_in_atomic_sequence
4511   (const struct riscv_insn &insn)
4512 {
4513   switch (insn.opcode ())
4514     {
4515     case riscv_insn::LUI:
4516     case riscv_insn::AUIPC:
4517     case riscv_insn::ADDI:
4518     case riscv_insn::ADDIW:
4519     case riscv_insn::SLTI:
4520     case riscv_insn::SLTIU:
4521     case riscv_insn::XORI:
4522     case riscv_insn::ORI:
4523     case riscv_insn::ANDI:
4524     case riscv_insn::SLLI:
4525     case riscv_insn::SLLIW:
4526     case riscv_insn::SRLI:
4527     case riscv_insn::SRLIW:
4528     case riscv_insn::SRAI:
4529     case riscv_insn::ADD:
4530     case riscv_insn::ADDW:
4531     case riscv_insn::SRAIW:
4532     case riscv_insn::SUB:
4533     case riscv_insn::SUBW:
4534     case riscv_insn::SLL:
4535     case riscv_insn::SLLW:
4536     case riscv_insn::SLT:
4537     case riscv_insn::SLTU:
4538     case riscv_insn::XOR:
4539     case riscv_insn::SRL:
4540     case riscv_insn::SRLW:
4541     case riscv_insn::SRA:
4542     case riscv_insn::SRAW:
4543     case riscv_insn::OR:
4544     case riscv_insn::AND:
4545       return true;
4546     }
4547 
4548     return false;
4549 }
4550 
4551 /* Return true if INSN is a direct branch instruction.  */
4552 
4553 static bool
riscv_insn_is_direct_branch(const struct riscv_insn & insn)4554 riscv_insn_is_direct_branch (const struct riscv_insn &insn)
4555 {
4556   switch (insn.opcode ())
4557     {
4558     case riscv_insn::BEQ:
4559     case riscv_insn::BNE:
4560     case riscv_insn::BLT:
4561     case riscv_insn::BGE:
4562     case riscv_insn::BLTU:
4563     case riscv_insn::BGEU:
4564     case riscv_insn::JAL:
4565       return true;
4566     }
4567 
4568     return false;
4569 }
4570 
4571 /* We can't put a breakpoint in the middle of a lr/sc atomic sequence, so look
4572    for the end of the sequence and put the breakpoint there.  */
4573 
4574 static std::vector<CORE_ADDR>
riscv_deal_with_atomic_sequence(struct regcache * regcache,CORE_ADDR pc)4575 riscv_deal_with_atomic_sequence (struct regcache *regcache, CORE_ADDR pc)
4576 {
4577   struct gdbarch *gdbarch = regcache->arch ();
4578   struct riscv_insn insn;
4579   CORE_ADDR cur_step_pc = pc, next_pc;
4580   std::vector<CORE_ADDR> next_pcs;
4581   bool found_valid_atomic_sequence = false;
4582   enum riscv_insn::opcode lr_opcode;
4583 
4584   /* First instruction has to be a load reserved.  */
4585   insn.decode (gdbarch, cur_step_pc);
4586   lr_opcode = insn.opcode ();
4587   if (lr_opcode != riscv_insn::LR_D && lr_opcode != riscv_insn::LR_W)
4588     return {};
4589 
4590   /* The loop comprises only an LR/SC sequence and code to retry the sequence in
4591      the case of failure, and must comprise at most 16 instructions placed
4592      sequentially in memory.  While our code tries to follow these restrictions,
4593      it has the following limitations:
4594 
4595        (a) We expect the loop to start with an LR and end with a BNE.
4596              Apparently this does not cover all cases for a valid sequence.
4597        (b) The atomic limitations only apply to the code that is actually
4598              executed, so here again it's overly restrictive.
4599        (c) The lr/sc are required to be for the same target address, but this
4600              information is only known at runtime.  Same as (b), in order to check
4601              this we will end up needing to simulate the sequence, which is more
4602              complicated than what we're doing right now.
4603 
4604      Also note that we only expect a maximum of (16-2) instructions in the for
4605      loop as we have assumed the presence of LR and BNE at the beginning and end
4606      respectively.  */
4607   for (int insn_count = 0; insn_count < 16 - 2; ++insn_count)
4608     {
4609       cur_step_pc += insn.length ();
4610       insn.decode (gdbarch, cur_step_pc);
4611 
4612       /* The dynamic code executed between lr/sc can only contain instructions
4613            from the base I instruction set, excluding loads, stores, backward
4614            jumps, taken backward branches, JALR, FENCE, FENCE.I, and SYSTEM
4615            instructions.  If the C extension is supported, then compressed forms
4616            of the aforementioned I instructions are also permitted.  */
4617 
4618       if (riscv_insn_is_non_cti_and_allowed_in_atomic_sequence (insn))
4619           continue;
4620       /* Look for a conditional branch instruction, check if it's taken forward
4621            or not.  */
4622       else if (riscv_insn_is_direct_branch (insn))
4623           {
4624             if (insn.imm_signed () > 0)
4625               {
4626                 next_pc = cur_step_pc + insn.imm_signed ();
4627                 next_pcs.push_back (next_pc);
4628               }
4629             else
4630               break;
4631           }
4632       /* Look for a paired SC instruction which closes the atomic sequence.  */
4633       else if ((insn.opcode () == riscv_insn::SC_D
4634                     && lr_opcode == riscv_insn::LR_D)
4635                  || (insn.opcode () == riscv_insn::SC_W
4636                        && lr_opcode == riscv_insn::LR_W))
4637           found_valid_atomic_sequence = true;
4638       else
4639           break;
4640     }
4641 
4642   if (!found_valid_atomic_sequence)
4643     return {};
4644 
4645   /* Next instruction should be branch to start.  */
4646   insn.decode (gdbarch, cur_step_pc);
4647   if (insn.opcode () != riscv_insn::BNE)
4648     return {};
4649   if (pc != (cur_step_pc + insn.imm_signed ()))
4650     return {};
4651   cur_step_pc += insn.length ();
4652 
4653   /* Remove all PCs that jump within the sequence.  */
4654   auto matcher = [cur_step_pc] (const CORE_ADDR addr) -> bool
4655     {
4656       return addr < cur_step_pc;
4657     };
4658   auto it = std::remove_if (next_pcs.begin (), next_pcs.end (), matcher);
4659   next_pcs.erase (it, next_pcs.end ());
4660 
4661   next_pc = cur_step_pc;
4662   next_pcs.push_back (next_pc);
4663   return next_pcs;
4664 }
4665 
4666 /* This is called just before we want to resume the inferior, if we want to
4667    single-step it but there is no hardware or kernel single-step support.  We
4668    find the target of the coming instruction and breakpoint it.  */
4669 
4670 std::vector<CORE_ADDR>
riscv_software_single_step(struct regcache * regcache)4671 riscv_software_single_step (struct regcache *regcache)
4672 {
4673   CORE_ADDR cur_pc = regcache_read_pc (regcache), next_pc;
4674   std::vector<CORE_ADDR> next_pcs
4675     = riscv_deal_with_atomic_sequence (regcache, cur_pc);
4676 
4677   if (!next_pcs.empty ())
4678     return next_pcs;
4679 
4680   next_pc = riscv_next_pc (regcache, cur_pc);
4681 
4682   return {next_pc};
4683 }
4684 
4685 /* Create RISC-V specific reggroups.  */
4686 
4687 static void
riscv_init_reggroups()4688 riscv_init_reggroups ()
4689 {
4690   csr_reggroup = reggroup_new ("csr", USER_REGGROUP);
4691 }
4692 
4693 /* See riscv-tdep.h.  */
4694 
4695 void
riscv_supply_regset(const struct regset * regset,struct regcache * regcache,int regnum,const void * regs,size_t len)4696 riscv_supply_regset (const struct regset *regset,
4697                          struct regcache *regcache, int regnum,
4698                          const void *regs, size_t len)
4699 {
4700   regcache->supply_regset (regset, regnum, regs, len);
4701 
4702   if (regnum == -1 || regnum == RISCV_ZERO_REGNUM)
4703     regcache->raw_supply_zeroed (RISCV_ZERO_REGNUM);
4704 
4705   struct gdbarch *gdbarch = regcache->arch ();
4706   riscv_gdbarch_tdep *tdep = gdbarch_tdep<riscv_gdbarch_tdep> (gdbarch);
4707 
4708   if (regnum == -1
4709       || regnum == tdep->fflags_regnum
4710       || regnum == tdep->frm_regnum)
4711     {
4712       int fcsr_regnum = RISCV_CSR_FCSR_REGNUM;
4713 
4714       /* Ensure that FCSR has been read into REGCACHE.  */
4715       if (regnum != -1)
4716           regcache->supply_regset (regset, fcsr_regnum, regs, len);
4717 
4718       /* Grab the FCSR value if it is now in the regcache.  We must check
4719            the status first as, if the register was not supplied by REGSET,
4720            this call will trigger a recursive attempt to fetch the
4721            registers.  */
4722       if (regcache->get_register_status (fcsr_regnum) == REG_VALID)
4723           {
4724             /* If we have an fcsr register then we should have fflags and frm
4725                too, either provided by the target, or provided as a pseudo
4726                register by GDB.  */
4727             gdb_assert (tdep->fflags_regnum >= 0);
4728             gdb_assert (tdep->frm_regnum >= 0);
4729 
4730             ULONGEST fcsr_val;
4731             regcache->raw_read (fcsr_regnum, &fcsr_val);
4732 
4733             /* Extract the fflags and frm values.  */
4734             ULONGEST fflags_val = fcsr_val & 0x1f;
4735             ULONGEST frm_val = (fcsr_val >> 5) & 0x7;
4736 
4737             /* And supply these if needed.  We can only supply real
4738                registers, so don't try to supply fflags or frm if they are
4739                implemented as pseudo-registers.  */
4740             if ((regnum == -1 || regnum == tdep->fflags_regnum)
4741                 && tdep->fflags_regnum < gdbarch_num_regs (gdbarch))
4742               regcache->raw_supply_integer (tdep->fflags_regnum,
4743                                                     (gdb_byte *) &fflags_val,
4744                                                     sizeof (fflags_val),
4745                                                     /* is_signed */ false);
4746 
4747             if ((regnum == -1 || regnum == tdep->frm_regnum)
4748                 && tdep->frm_regnum < gdbarch_num_regs (gdbarch))
4749               regcache->raw_supply_integer (tdep->frm_regnum,
4750                                                     (gdb_byte *)&frm_val,
4751                                                     sizeof (fflags_val),
4752                                                     /* is_signed */ false);
4753           }
4754     }
4755 }
4756 
4757 void _initialize_riscv_tdep ();
4758 void
_initialize_riscv_tdep()4759 _initialize_riscv_tdep ()
4760 {
4761   riscv_init_reggroups ();
4762 
4763   gdbarch_register (bfd_arch_riscv, riscv_gdbarch_init, NULL);
4764 
4765   /* Add root prefix command for all "set debug riscv" and "show debug
4766      riscv" commands.  */
4767   add_setshow_prefix_cmd ("riscv", no_class,
4768                                 _("RISC-V specific debug commands."),
4769                                 _("RISC-V specific debug commands."),
4770                                 &setdebugriscvcmdlist, &showdebugriscvcmdlist,
4771                                 &setdebuglist, &showdebuglist);
4772 
4773   add_setshow_boolean_cmd ("breakpoints", class_maintenance,
4774                                  &riscv_debug_breakpoints,  _("\
4775 Set riscv breakpoint debugging."), _("\
4776 Show riscv breakpoint debugging."), _("\
4777 When non-zero, print debugging information for the riscv specific parts\n\
4778 of the breakpoint mechanism."),
4779                                  nullptr,
4780                                  show_riscv_debug_variable,
4781                                  &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4782 
4783   add_setshow_boolean_cmd ("infcall", class_maintenance,
4784                                  &riscv_debug_infcall,  _("\
4785 Set riscv inferior call debugging."), _("\
4786 Show riscv inferior call debugging."), _("\
4787 When non-zero, print debugging information for the riscv specific parts\n\
4788 of the inferior call mechanism."),
4789                                  nullptr,
4790                                  show_riscv_debug_variable,
4791                                  &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4792 
4793   add_setshow_boolean_cmd ("unwinder", class_maintenance,
4794                                  &riscv_debug_unwinder,  _("\
4795 Set riscv stack unwinding debugging."), _("\
4796 Show riscv stack unwinding debugging."), _("\
4797 When on, print debugging information for the riscv specific parts\n\
4798 of the stack unwinding mechanism."),
4799                                  nullptr,
4800                                  show_riscv_debug_variable,
4801                                  &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4802 
4803   add_setshow_boolean_cmd ("gdbarch", class_maintenance,
4804                                  &riscv_debug_gdbarch,  _("\
4805 Set riscv gdbarch initialisation debugging."), _("\
4806 Show riscv gdbarch initialisation debugging."), _("\
4807 When non-zero, print debugging information for the riscv gdbarch\n\
4808 initialisation process."),
4809                                  nullptr,
4810                                  show_riscv_debug_variable,
4811                                  &setdebugriscvcmdlist, &showdebugriscvcmdlist);
4812 
4813   /* Add root prefix command for all "set riscv" and "show riscv" commands.  */
4814   add_setshow_prefix_cmd ("riscv", no_class,
4815                                 _("RISC-V specific commands."),
4816                                 _("RISC-V specific commands."),
4817                                 &setriscvcmdlist, &showriscvcmdlist,
4818                                 &setlist, &showlist);
4819 
4820 
4821   use_compressed_breakpoints = AUTO_BOOLEAN_AUTO;
4822   add_setshow_auto_boolean_cmd ("use-compressed-breakpoints", no_class,
4823                                         &use_compressed_breakpoints,
4824                                         _("\
4825 Set debugger's use of compressed breakpoints."), _("\
4826 Show debugger's use of compressed breakpoints."), _("\
4827 Debugging compressed code requires compressed breakpoints to be used. If\n\
4828 left to 'auto' then gdb will use them if the existing instruction is a\n\
4829 compressed instruction. If that doesn't give the correct behavior, then\n\
4830 this option can be used."),
4831                                         NULL,
4832                                         show_use_compressed_breakpoints,
4833                                         &setriscvcmdlist,
4834                                         &showriscvcmdlist);
4835 }
4836