Home | History | Annotate | Line # | Download | only in opcodes
riscv-dis.c revision 1.1.1.6
      1 /* RISC-V disassembler
      2    Copyright (C) 2011-2024 Free Software Foundation, Inc.
      3 
      4    Contributed by Andrew Waterman (andrew (at) sifive.com).
      5    Based on MIPS target.
      6 
      7    This file is part of the GNU opcodes library.
      8 
      9    This library is free software; you can redistribute it and/or modify
     10    it under the terms of the GNU General Public License as published by
     11    the Free Software Foundation; either version 3, or (at your option)
     12    any later version.
     13 
     14    It is distributed in the hope that it will be useful, but WITHOUT
     15    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
     16    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
     17    License for more details.
     18 
     19    You should have received a copy of the GNU General Public License
     20    along with this program; see the file COPYING3. If not,
     21    see <http://www.gnu.org/licenses/>.  */
     22 
     23 #include "sysdep.h"
     24 #include "disassemble.h"
     25 #include "libiberty.h"
     26 #include "opcode/riscv.h"
     27 #include "opintl.h"
     28 #include "elf-bfd.h"
     29 #include "elf/riscv.h"
     30 #include "elfxx-riscv.h"
     31 
     32 #include <stdint.h>
     33 #include <ctype.h>
     34 
     35 /* The RISC-V disassembler produces styled output using
     36    disassemble_info::fprintf_styled_func.  This define prevents use of
     37    disassemble_info::fprintf_func which is for unstyled output.  */
     38 #define fprintf_func please_use_fprintf_styled_func_instead
     39 
     40 /* Current XLEN for the disassembler.  */
     41 static unsigned xlen = 0;
     42 
     43 /* Default ISA specification version (constant as of now).  */
     44 static enum riscv_spec_class default_isa_spec = ISA_SPEC_CLASS_DRAFT - 1;
     45 
     46 /* Default privileged specification
     47    (as specified by the ELF attributes or the `priv-spec' option).  */
     48 static enum riscv_spec_class default_priv_spec = PRIV_SPEC_CLASS_NONE;
     49 
     50 static riscv_subset_list_t riscv_subsets;
     51 static riscv_parse_subset_t riscv_rps_dis =
     52 {
     53   &riscv_subsets,	/* subset_list.  */
     54   opcodes_error_handler,/* error_handler.  */
     55   &xlen,		/* xlen.  */
     56   &default_isa_spec,	/* isa_spec.  */
     57   false,		/* check_unknown_prefixed_ext.  */
     58 };
     59 
     60 struct riscv_private_data
     61 {
     62   bfd_vma gp;
     63   bfd_vma print_addr;
     64   bfd_vma hi_addr[OP_MASK_RD + 1];
     65   bool to_print_addr;
     66   bool has_gp;
     67 };
     68 
     69 /* Used for mapping symbols.  */
     70 static int last_map_symbol = -1;
     71 static bfd_vma last_stop_offset = 0;
     72 static bfd_vma last_map_symbol_boundary = 0;
     73 static enum riscv_seg_mstate last_map_state = MAP_NONE;
     74 static asection *last_map_section = NULL;
     75 
     76 /* Register names as used by the disassembler.  */
     77 static const char (*riscv_gpr_names)[NRC];
     78 static const char (*riscv_fpr_names)[NRC];
     79 
     80 /* If set, disassemble as most general instruction.  */
     81 static bool no_aliases = false;
     82 
     83 /* If set, disassemble without checking architectire string, just like what
     84    we did at the beginning.  */
     85 static bool all_ext = false;
     86 
     87 /* Set default RISC-V disassembler options.  */
     88 
     89 static void
     90 set_default_riscv_dis_options (void)
     91 {
     92   riscv_gpr_names = riscv_gpr_names_abi;
     93   riscv_fpr_names = riscv_fpr_names_abi;
     94   no_aliases = false;
     95 }
     96 
     97 /* Parse RISC-V disassembler option (without arguments).  */
     98 
     99 static bool
    100 parse_riscv_dis_option_without_args (const char *option)
    101 {
    102   if (strcmp (option, "no-aliases") == 0)
    103     no_aliases = true;
    104   else if (strcmp (option, "numeric") == 0)
    105     {
    106       riscv_gpr_names = riscv_gpr_names_numeric;
    107       riscv_fpr_names = riscv_fpr_names_numeric;
    108     }
    109   else if (strcmp (option, "max") == 0)
    110     all_ext = true;
    111   else
    112     return false;
    113   return true;
    114 }
    115 
    116 /* Parse RISC-V disassembler option (possibly with arguments).  */
    117 
    118 static void
    119 parse_riscv_dis_option (const char *option)
    120 {
    121   char *equal, *value;
    122 
    123   if (parse_riscv_dis_option_without_args (option))
    124     return;
    125 
    126   equal = strchr (option, '=');
    127   if (equal == NULL)
    128     {
    129       /* The option without '=' should be defined above.  */
    130       opcodes_error_handler (_("unrecognized disassembler option: %s"), option);
    131       return;
    132     }
    133   if (equal == option
    134       || *(equal + 1) == '\0')
    135     {
    136       /* Invalid options with '=', no option name before '=',
    137        and no value after '='.  */
    138       opcodes_error_handler (_("unrecognized disassembler option with '=': %s"),
    139                             option);
    140       return;
    141     }
    142 
    143   *equal = '\0';
    144   value = equal + 1;
    145   if (strcmp (option, "priv-spec") == 0)
    146     {
    147       enum riscv_spec_class priv_spec = PRIV_SPEC_CLASS_NONE;
    148       const char *name = NULL;
    149 
    150       RISCV_GET_PRIV_SPEC_CLASS (value, priv_spec);
    151       if (priv_spec == PRIV_SPEC_CLASS_NONE)
    152 	opcodes_error_handler (_("unknown privileged spec set by %s=%s"),
    153 			       option, value);
    154       else if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
    155 	default_priv_spec = priv_spec;
    156       else if (default_priv_spec != priv_spec)
    157 	{
    158 	  RISCV_GET_PRIV_SPEC_NAME (name, default_priv_spec);
    159 	  opcodes_error_handler (_("mis-matched privilege spec set by %s=%s, "
    160 				   "the elf privilege attribute is %s"),
    161 				 option, value, name);
    162 	}
    163     }
    164   else
    165     {
    166       /* xgettext:c-format */
    167       opcodes_error_handler (_("unrecognized disassembler option: %s"), option);
    168     }
    169 }
    170 
    171 /* Parse RISC-V disassembler options.  */
    172 
    173 static void
    174 parse_riscv_dis_options (const char *opts_in)
    175 {
    176   char *opts = xstrdup (opts_in), *opt = opts, *opt_end = opts;
    177 
    178   set_default_riscv_dis_options ();
    179 
    180   for ( ; opt_end != NULL; opt = opt_end + 1)
    181     {
    182       if ((opt_end = strchr (opt, ',')) != NULL)
    183 	*opt_end = 0;
    184       parse_riscv_dis_option (opt);
    185     }
    186 
    187   free (opts);
    188 }
    189 
    190 /* Print one argument from an array.  */
    191 
    192 static void
    193 arg_print (struct disassemble_info *info, unsigned long val,
    194 	   const char* const* array, size_t size)
    195 {
    196   const char *s = val >= size || array[val] == NULL ? "unknown" : array[val];
    197   (*info->fprintf_styled_func) (info->stream, dis_style_text, "%s", s);
    198 }
    199 
    200 /* If we need to print an address, set its value and state.  */
    201 
    202 static void
    203 maybe_print_address (struct riscv_private_data *pd, int base_reg, int offset,
    204 		     int wide)
    205 {
    206   if (pd->hi_addr[base_reg] != (bfd_vma)-1)
    207     {
    208       pd->print_addr = (base_reg != 0 ? pd->hi_addr[base_reg] : 0) + offset;
    209       pd->hi_addr[base_reg] = -1;
    210     }
    211   else if (base_reg == X_GP && pd->has_gp)
    212     pd->print_addr = pd->gp + offset;
    213   else if (base_reg == X_TP || base_reg == 0)
    214     pd->print_addr = offset;
    215   else
    216     return;  /* Don't print the address.  */
    217   pd->to_print_addr = true;
    218 
    219   /* Sign-extend a 32-bit value to a 64-bit value.  */
    220   if (wide)
    221     pd->print_addr = (bfd_vma)(int32_t) pd->print_addr;
    222 
    223   /* Fit into a 32-bit value on RV32.  */
    224   if (xlen == 32)
    225     pd->print_addr = (bfd_vma)(uint32_t)pd->print_addr;
    226 }
    227 
    228 /* Get Zcmp reg_list field.  */
    229 
    230 static void
    231 print_reg_list (disassemble_info *info, insn_t l)
    232 {
    233   bool numeric = riscv_gpr_names == riscv_gpr_names_numeric;
    234   unsigned reg_list = (int)EXTRACT_OPERAND (REG_LIST, l);
    235   unsigned r_start = numeric ? X_S2 : X_S0;
    236   info->fprintf_styled_func (info->stream, dis_style_register,
    237 			     "%s", riscv_gpr_names[X_RA]);
    238 
    239   if (reg_list == 5)
    240     {
    241       info->fprintf_styled_func (info->stream, dis_style_text, ",");
    242       info->fprintf_styled_func (info->stream, dis_style_register,
    243 				 "%s", riscv_gpr_names[X_S0]);
    244     }
    245   else if (reg_list == 6 || (numeric && reg_list > 6))
    246     {
    247       info->fprintf_styled_func (info->stream, dis_style_text, ",");
    248       info->fprintf_styled_func (info->stream, dis_style_register,
    249 				 "%s", riscv_gpr_names[X_S0]);
    250       info->fprintf_styled_func (info->stream, dis_style_text, "-");
    251       info->fprintf_styled_func (info->stream, dis_style_register,
    252 				 "%s", riscv_gpr_names[X_S1]);
    253     }
    254 
    255   if (reg_list == 15)
    256     {
    257       info->fprintf_styled_func (info->stream, dis_style_text, ",");
    258       info->fprintf_styled_func (info->stream, dis_style_register,
    259 				 "%s", riscv_gpr_names[r_start]);
    260       info->fprintf_styled_func (info->stream, dis_style_text, "-");
    261       info->fprintf_styled_func (info->stream, dis_style_register,
    262 				 "%s", riscv_gpr_names[X_S11]);
    263     }
    264   else if (reg_list == 7 && numeric)
    265     {
    266       info->fprintf_styled_func (info->stream, dis_style_text, ",");
    267       info->fprintf_styled_func (info->stream, dis_style_register,
    268 				 "%s", riscv_gpr_names[X_S2]);
    269     }
    270   else if (reg_list > 6)
    271     {
    272       info->fprintf_styled_func (info->stream, dis_style_text, ",");
    273       info->fprintf_styled_func (info->stream, dis_style_register,
    274 				 "%s", riscv_gpr_names[r_start]);
    275       info->fprintf_styled_func (info->stream, dis_style_text, "-");
    276       info->fprintf_styled_func (info->stream, dis_style_register,
    277 				 "%s", riscv_gpr_names[reg_list + 11]);
    278     }
    279 }
    280 
    281 /* Get Zcmp sp adjustment immediate.  */
    282 
    283 static int
    284 riscv_get_spimm (insn_t l)
    285 {
    286   int spimm = riscv_get_sp_base(l, *riscv_rps_dis.xlen);
    287   spimm += EXTRACT_ZCMP_SPIMM (l);
    288   if (((l ^ MATCH_CM_PUSH) & MASK_CM_PUSH) == 0)
    289     spimm *= -1;
    290   return spimm;
    291 }
    292 
    293 /* Get s-register regno by using sreg number.
    294    e.g. the regno of s0 is 8, so
    295    riscv_zcmp_get_sregno (0) equals 8.  */
    296 
    297 static unsigned
    298 riscv_zcmp_get_sregno (unsigned sreg_idx)
    299 {
    300   return sreg_idx > 1 ?
    301       sreg_idx + 16 : sreg_idx + 8;
    302 }
    303 
    304 /* Print insn arguments for 32/64-bit code.  */
    305 
    306 static void
    307 print_insn_args (const char *oparg, insn_t l, bfd_vma pc, disassemble_info *info)
    308 {
    309   struct riscv_private_data *pd = info->private_data;
    310   int rs1 = (l >> OP_SH_RS1) & OP_MASK_RS1;
    311   int rd = (l >> OP_SH_RD) & OP_MASK_RD;
    312   fprintf_styled_ftype print = info->fprintf_styled_func;
    313   const char *opargStart;
    314 
    315   if (*oparg != '\0')
    316     print (info->stream, dis_style_text, "\t");
    317 
    318   for (; *oparg != '\0'; oparg++)
    319     {
    320       opargStart = oparg;
    321       switch (*oparg)
    322 	{
    323 	case 'C': /* RVC */
    324 	  switch (*++oparg)
    325 	    {
    326 	    case 's': /* RS1 x8-x15.  */
    327 	    case 'w': /* RS1 x8-x15.  */
    328 	      print (info->stream, dis_style_register, "%s",
    329 		     riscv_gpr_names[EXTRACT_OPERAND (CRS1S, l) + 8]);
    330 	      break;
    331 	    case 't': /* RS2 x8-x15.  */
    332 	    case 'x': /* RS2 x8-x15.  */
    333 	      print (info->stream, dis_style_register, "%s",
    334 		     riscv_gpr_names[EXTRACT_OPERAND (CRS2S, l) + 8]);
    335 	      break;
    336 	    case 'U': /* RS1, constrained to equal RD.  */
    337 	      print (info->stream, dis_style_register,
    338 		     "%s", riscv_gpr_names[rd]);
    339 	      break;
    340 	    case 'c': /* RS1, constrained to equal sp.  */
    341 	      print (info->stream, dis_style_register, "%s",
    342 		     riscv_gpr_names[X_SP]);
    343 	      break;
    344 	    case 'V': /* RS2 */
    345 	      print (info->stream, dis_style_register, "%s",
    346 		     riscv_gpr_names[EXTRACT_OPERAND (CRS2, l)]);
    347 	      break;
    348 	    case 'o':
    349 	    case 'j':
    350 	      if (((l & MASK_C_ADDI) == MATCH_C_ADDI) && rd != 0)
    351 		maybe_print_address (pd, rd, EXTRACT_CITYPE_IMM (l), 0);
    352 	      if (info->mach == bfd_mach_riscv64
    353 		  && ((l & MASK_C_ADDIW) == MATCH_C_ADDIW) && rd != 0)
    354 		maybe_print_address (pd, rd, EXTRACT_CITYPE_IMM (l), 1);
    355 	      print (info->stream, dis_style_immediate, "%d",
    356 		     (int)EXTRACT_CITYPE_IMM (l));
    357 	      break;
    358 	    case 'k':
    359 	      print (info->stream, dis_style_address_offset, "%d",
    360 		     (int)EXTRACT_CLTYPE_LW_IMM (l));
    361 	      break;
    362 	    case 'l':
    363 	      print (info->stream, dis_style_address_offset, "%d",
    364 		     (int)EXTRACT_CLTYPE_LD_IMM (l));
    365 	      break;
    366 	    case 'm':
    367 	      print (info->stream, dis_style_address_offset, "%d",
    368 		     (int)EXTRACT_CITYPE_LWSP_IMM (l));
    369 	      break;
    370 	    case 'n':
    371 	      print (info->stream, dis_style_address_offset, "%d",
    372 		     (int)EXTRACT_CITYPE_LDSP_IMM (l));
    373 	      break;
    374 	    case 'K':
    375 	      print (info->stream, dis_style_immediate, "%d",
    376 		     (int)EXTRACT_CIWTYPE_ADDI4SPN_IMM (l));
    377 	      break;
    378 	    case 'L':
    379 	      print (info->stream, dis_style_immediate, "%d",
    380 		     (int)EXTRACT_CITYPE_ADDI16SP_IMM (l));
    381 	      break;
    382 	    case 'M':
    383 	      print (info->stream, dis_style_address_offset, "%d",
    384 		     (int)EXTRACT_CSSTYPE_SWSP_IMM (l));
    385 	      break;
    386 	    case 'N':
    387 	      print (info->stream, dis_style_address_offset, "%d",
    388 		     (int)EXTRACT_CSSTYPE_SDSP_IMM (l));
    389 	      break;
    390 	    case 'p':
    391 	      info->target = EXTRACT_CBTYPE_IMM (l) + pc;
    392 	      (*info->print_address_func) (info->target, info);
    393 	      break;
    394 	    case 'a':
    395 	      info->target = EXTRACT_CJTYPE_IMM (l) + pc;
    396 	      (*info->print_address_func) (info->target, info);
    397 	      break;
    398 	    case 'u':
    399 	      print (info->stream, dis_style_immediate, "0x%x",
    400 		     (unsigned)(EXTRACT_CITYPE_IMM (l) & (RISCV_BIGIMM_REACH-1)));
    401 	      break;
    402 	    case '>':
    403 	      print (info->stream, dis_style_immediate, "0x%x",
    404 		     (unsigned)EXTRACT_CITYPE_IMM (l) & 0x3f);
    405 	      break;
    406 	    case '<':
    407 	      print (info->stream, dis_style_immediate, "0x%x",
    408 		     (unsigned)EXTRACT_CITYPE_IMM (l) & 0x1f);
    409 	      break;
    410 	    case 'T': /* Floating-point RS2.  */
    411 	      print (info->stream, dis_style_register, "%s",
    412 		     riscv_fpr_names[EXTRACT_OPERAND (CRS2, l)]);
    413 	      break;
    414 	    case 'D': /* Floating-point RS2 x8-x15.  */
    415 	      print (info->stream, dis_style_register, "%s",
    416 		     riscv_fpr_names[EXTRACT_OPERAND (CRS2S, l) + 8]);
    417 	      break;
    418 	    }
    419 	  break;
    420 
    421 	case 'V': /* RVV */
    422 	  switch (*++oparg)
    423 	    {
    424 	    case 'd':
    425 	    case 'f':
    426 	      print (info->stream, dis_style_register, "%s",
    427 		     riscv_vecr_names_numeric[EXTRACT_OPERAND (VD, l)]);
    428 	      break;
    429 	    case 'e':
    430 	      if (!EXTRACT_OPERAND (VWD, l))
    431 		print (info->stream, dis_style_register, "%s",
    432 		       riscv_gpr_names[0]);
    433 	      else
    434 		print (info->stream, dis_style_register, "%s",
    435 		       riscv_vecr_names_numeric[EXTRACT_OPERAND (VD, l)]);
    436 	      break;
    437 	    case 's':
    438 	      print (info->stream, dis_style_register, "%s",
    439 		     riscv_vecr_names_numeric[EXTRACT_OPERAND (VS1, l)]);
    440 	      break;
    441 	    case 't':
    442 	    case 'u': /* VS1 == VS2 already verified at this point.  */
    443 	    case 'v': /* VD == VS1 == VS2 already verified at this point.  */
    444 	      print (info->stream, dis_style_register, "%s",
    445 		     riscv_vecr_names_numeric[EXTRACT_OPERAND (VS2, l)]);
    446 	      break;
    447 	    case '0':
    448 	      print (info->stream, dis_style_register, "%s",
    449 		     riscv_vecr_names_numeric[0]);
    450 	      break;
    451 	    case 'b':
    452 	    case 'c':
    453 	      {
    454 		int imm = (*oparg == 'b') ? EXTRACT_RVV_VB_IMM (l)
    455 					  : EXTRACT_RVV_VC_IMM (l);
    456 		unsigned int imm_vlmul = EXTRACT_OPERAND (VLMUL, imm);
    457 		unsigned int imm_vsew = EXTRACT_OPERAND (VSEW, imm);
    458 		unsigned int imm_vta = EXTRACT_OPERAND (VTA, imm);
    459 		unsigned int imm_vma = EXTRACT_OPERAND (VMA, imm);
    460 		unsigned int imm_vtype_res = (imm >> 8);
    461 
    462 		if (imm_vsew < ARRAY_SIZE (riscv_vsew)
    463 		    && imm_vlmul < ARRAY_SIZE (riscv_vlmul)
    464 		    && imm_vta < ARRAY_SIZE (riscv_vta)
    465 		    && imm_vma < ARRAY_SIZE (riscv_vma)
    466 		    && !imm_vtype_res
    467 		    && riscv_vsew[imm_vsew] != NULL
    468 		    && riscv_vlmul[imm_vlmul] != NULL)
    469 		  print (info->stream, dis_style_text, "%s,%s,%s,%s",
    470 			 riscv_vsew[imm_vsew],
    471 			 riscv_vlmul[imm_vlmul], riscv_vta[imm_vta],
    472 			 riscv_vma[imm_vma]);
    473 		else
    474 		  print (info->stream, dis_style_immediate, "%d", imm);
    475 	      }
    476 	      break;
    477 	    case 'i':
    478 	      print (info->stream, dis_style_immediate, "%d",
    479 		     (int)EXTRACT_RVV_VI_IMM (l));
    480 	      break;
    481 	    case 'j':
    482 	      print (info->stream, dis_style_immediate, "%d",
    483 		     (int)EXTRACT_RVV_VI_UIMM (l));
    484 	      break;
    485 	    case 'k':
    486 	      print (info->stream, dis_style_immediate, "%d",
    487 		     (int)EXTRACT_RVV_OFFSET (l));
    488 	      break;
    489 	    case 'l':
    490 	      print (info->stream, dis_style_immediate, "%d",
    491 		     (int)EXTRACT_RVV_VI_UIMM6 (l));
    492 	      break;
    493 	    case 'm':
    494 	      if (!EXTRACT_OPERAND (VMASK, l))
    495 		{
    496 		  print (info->stream, dis_style_text, ",");
    497 		  print (info->stream, dis_style_register, "%s",
    498 			 riscv_vecm_names_numeric[0]);
    499 		}
    500 	      break;
    501 	    }
    502 	  break;
    503 
    504 	case ',':
    505 	case '(':
    506 	case ')':
    507 	case '[':
    508 	case ']':
    509 	case '{':
    510 	case '}':
    511 	  print (info->stream, dis_style_text, "%c", *oparg);
    512 	  break;
    513 
    514 	case '0':
    515 	  /* Only print constant 0 if it is the last argument.  */
    516 	  if (!oparg[1])
    517 	    print (info->stream, dis_style_immediate, "0");
    518 	  break;
    519 
    520 	case 's':
    521 	  if ((l & MASK_JALR) == MATCH_JALR)
    522 	    maybe_print_address (pd, rs1, EXTRACT_ITYPE_IMM (l), 0);
    523 	  print (info->stream, dis_style_register, "%s", riscv_gpr_names[rs1]);
    524 	  break;
    525 
    526 	case 't':
    527 	  print (info->stream, dis_style_register, "%s",
    528 		 riscv_gpr_names[EXTRACT_OPERAND (RS2, l)]);
    529 	  break;
    530 
    531 	case 'u':
    532 	  print (info->stream, dis_style_immediate, "0x%x",
    533 		 (unsigned)EXTRACT_UTYPE_IMM (l) >> RISCV_IMM_BITS);
    534 	  break;
    535 
    536 	case 'm':
    537 	  arg_print (info, EXTRACT_OPERAND (RM, l),
    538 		     riscv_rm, ARRAY_SIZE (riscv_rm));
    539 	  break;
    540 
    541 	case 'P':
    542 	  arg_print (info, EXTRACT_OPERAND (PRED, l),
    543 		     riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ));
    544 	  break;
    545 
    546 	case 'Q':
    547 	  arg_print (info, EXTRACT_OPERAND (SUCC, l),
    548 		     riscv_pred_succ, ARRAY_SIZE (riscv_pred_succ));
    549 	  break;
    550 
    551 	case 'o':
    552 	  maybe_print_address (pd, rs1, EXTRACT_ITYPE_IMM (l), 0);
    553 	  /* Fall through.  */
    554 	case 'j':
    555 	  if (((l & MASK_ADDI) == MATCH_ADDI && rs1 != 0)
    556 	      || (l & MASK_JALR) == MATCH_JALR)
    557 	    maybe_print_address (pd, rs1, EXTRACT_ITYPE_IMM (l), 0);
    558 	  if (info->mach == bfd_mach_riscv64
    559 	      && ((l & MASK_ADDIW) == MATCH_ADDIW) && rs1 != 0)
    560 	    maybe_print_address (pd, rs1, EXTRACT_ITYPE_IMM (l), 1);
    561 	  print (info->stream, dis_style_immediate, "%d",
    562 		 (int)EXTRACT_ITYPE_IMM (l));
    563 	  break;
    564 
    565 	case 'q':
    566 	  maybe_print_address (pd, rs1, EXTRACT_STYPE_IMM (l), 0);
    567 	  print (info->stream, dis_style_address_offset, "%d",
    568 		 (int)EXTRACT_STYPE_IMM (l));
    569 	  break;
    570 
    571 	case 'a':
    572 	  info->target = EXTRACT_JTYPE_IMM (l) + pc;
    573 	  (*info->print_address_func) (info->target, info);
    574 	  break;
    575 
    576 	case 'p':
    577 	  info->target = EXTRACT_BTYPE_IMM (l) + pc;
    578 	  (*info->print_address_func) (info->target, info);
    579 	  break;
    580 
    581 	case 'd':
    582 	  if ((l & MASK_AUIPC) == MATCH_AUIPC)
    583 	    pd->hi_addr[rd] = pc + EXTRACT_UTYPE_IMM (l);
    584 	  else if ((l & MASK_LUI) == MATCH_LUI)
    585 	    pd->hi_addr[rd] = EXTRACT_UTYPE_IMM (l);
    586 	  else if ((l & MASK_C_LUI) == MATCH_C_LUI)
    587 	    pd->hi_addr[rd] = EXTRACT_CITYPE_LUI_IMM (l);
    588 	  print (info->stream, dis_style_register, "%s", riscv_gpr_names[rd]);
    589 	  break;
    590 
    591 	case 'y':
    592 	  print (info->stream, dis_style_immediate, "0x%x",
    593 		 EXTRACT_OPERAND (BS, l));
    594 	  break;
    595 
    596 	case 'z':
    597 	  print (info->stream, dis_style_register, "%s", riscv_gpr_names[0]);
    598 	  break;
    599 
    600 	case '>':
    601 	  print (info->stream, dis_style_immediate, "0x%x",
    602 		 EXTRACT_OPERAND (SHAMT, l));
    603 	  break;
    604 
    605 	case '<':
    606 	  print (info->stream, dis_style_immediate, "0x%x",
    607 		 EXTRACT_OPERAND (SHAMTW, l));
    608 	  break;
    609 
    610 	case 'S':
    611 	case 'U':
    612 	  print (info->stream, dis_style_register, "%s", riscv_fpr_names[rs1]);
    613 	  break;
    614 
    615 	case 'T':
    616 	  print (info->stream, dis_style_register, "%s",
    617 		 riscv_fpr_names[EXTRACT_OPERAND (RS2, l)]);
    618 	  break;
    619 
    620 	case 'D':
    621 	  print (info->stream, dis_style_register, "%s", riscv_fpr_names[rd]);
    622 	  break;
    623 
    624 	case 'R':
    625 	  print (info->stream, dis_style_register, "%s",
    626 		 riscv_fpr_names[EXTRACT_OPERAND (RS3, l)]);
    627 	  break;
    628 
    629 	case 'E':
    630 	  {
    631 	    static const char *riscv_csr_hash[4096]; /* Total 2^12 CSRs.  */
    632 	    static bool init_csr = false;
    633 	    unsigned int csr = EXTRACT_OPERAND (CSR, l);
    634 
    635 	    if (!init_csr)
    636 	      {
    637 		unsigned int i;
    638 		for (i = 0; i < 4096; i++)
    639 		  riscv_csr_hash[i] = NULL;
    640 
    641 		/* Set to the newest privileged version.  */
    642 		if (default_priv_spec == PRIV_SPEC_CLASS_NONE)
    643 		  default_priv_spec = PRIV_SPEC_CLASS_DRAFT - 1;
    644 
    645 #define DECLARE_CSR(name, num, class, define_version, abort_version)	\
    646 		if (riscv_csr_hash[num] == NULL 			\
    647 		    && ((define_version == PRIV_SPEC_CLASS_NONE 	\
    648 			 && abort_version == PRIV_SPEC_CLASS_NONE)	\
    649 			|| (default_priv_spec >= define_version 	\
    650 			    && default_priv_spec < abort_version)))	\
    651 		  riscv_csr_hash[num] = #name;
    652 #define DECLARE_CSR_ALIAS(name, num, class, define_version, abort_version) \
    653 		DECLARE_CSR (name, num, class, define_version, abort_version)
    654 #include "opcode/riscv-opc.h"
    655 #undef DECLARE_CSR
    656 	      }
    657 
    658 	    if (riscv_csr_hash[csr] != NULL)
    659 	      if (riscv_subset_supports (&riscv_rps_dis, "xtheadvector")
    660 		  && (csr == CSR_VSTART
    661 		      || csr == CSR_VXSAT
    662 		      || csr == CSR_VXRM
    663 		      || csr == CSR_VL
    664 		      || csr == CSR_VTYPE
    665 		      || csr == CSR_VLENB))
    666 		print (info->stream, dis_style_register, "%s",
    667 		       concat ("th.", riscv_csr_hash[csr], NULL));
    668 	      else
    669 		print (info->stream, dis_style_register, "%s",
    670 		       riscv_csr_hash[csr]);
    671 	    else
    672 	      print (info->stream, dis_style_immediate, "0x%x", csr);
    673 	    break;
    674 	  }
    675 
    676 	case 'Y':
    677 	  print (info->stream, dis_style_immediate, "0x%x",
    678 		 EXTRACT_OPERAND (RNUM, l));
    679 	  break;
    680 
    681 	case 'Z':
    682 	  print (info->stream, dis_style_immediate, "%d", rs1);
    683 	  break;
    684 
    685 	case 'W': /* Various operands for standard z extensions.  */
    686 	  switch (*++oparg)
    687 	    {
    688 	    case 'i':
    689 	      switch (*++oparg)
    690 		{
    691 		case 'f':
    692 		  print (info->stream, dis_style_address_offset, "%d",
    693 			 (int) EXTRACT_STYPE_IMM (l));
    694 		  break;
    695 		default:
    696 		  goto undefined_modifier;
    697 		}
    698 	      break;
    699 	    case 'f':
    700 	      switch (*++oparg)
    701 		{
    702 		case 'v':
    703 		  if (riscv_fli_symval[rs1])
    704 		    print (info->stream, dis_style_text, "%s",
    705 			   riscv_fli_symval[rs1]);
    706 		  else
    707 		    print (info->stream, dis_style_immediate, "%a",
    708 			   riscv_fli_numval[rs1]);
    709 		  break;
    710 		default:
    711 		  goto undefined_modifier;
    712 		}
    713 	      break;
    714 	    case 'c': /* Zcb extension 16 bits length instruction fields. */
    715 	      switch (*++oparg)
    716 		{
    717 		case '1':
    718 		    print (info->stream, dis_style_register, "%s",
    719 		      riscv_gpr_names[riscv_zcmp_get_sregno (EXTRACT_OPERAND (SREG1, l))]);
    720 		    break;
    721 		case '2':
    722 		    print (info->stream, dis_style_register, "%s",
    723 		      riscv_gpr_names[riscv_zcmp_get_sregno (EXTRACT_OPERAND (SREG2, l))]);
    724 		    break;
    725 		case 'b':
    726 		  print (info->stream, dis_style_immediate, "%d",
    727 			 (int)EXTRACT_ZCB_BYTE_UIMM (l));
    728 		  break;
    729 		case 'h':
    730 		  print (info->stream, dis_style_immediate, "%d",
    731 			 (int)EXTRACT_ZCB_HALFWORD_UIMM (l));
    732 		  break;
    733 		case 'r':
    734 		  print_reg_list (info, l);
    735 		  break;
    736 		case 'p':
    737 		  print (info->stream, dis_style_immediate, "%d",
    738 			 riscv_get_spimm (l));
    739 		  break;
    740 		case 'i':
    741 		case 'I':
    742 		  print (info->stream, dis_style_address_offset,
    743 			 "%" PRIu64, EXTRACT_ZCMT_INDEX (l));
    744 		  break;
    745 		default:
    746 		  goto undefined_modifier;
    747 		}
    748 	      break;
    749 	    default:
    750 	      goto undefined_modifier;
    751 	    }
    752 	  break;
    753 
    754 	case 'X': /* Vendor-specific operands.  */
    755 	  switch (*++oparg)
    756 	    {
    757 	    case 't': /* Vendor-specific (T-head) operands.  */
    758 	      {
    759 		size_t n;
    760 		size_t s;
    761 		bool sign;
    762 		switch (*++oparg)
    763 		  {
    764 		  case 'V':
    765 		   ++oparg;
    766 		   if (*oparg != 'c')
    767 		      goto undefined_modifier;
    768 
    769 		    int imm = (*oparg == 'b') ? EXTRACT_RVV_VB_IMM (l)
    770 					      : EXTRACT_RVV_VC_IMM (l);
    771 		    unsigned int imm_vediv = EXTRACT_OPERAND (XTHEADVEDIV, imm);
    772 		    unsigned int imm_vlmul = EXTRACT_OPERAND (XTHEADVLMUL, imm);
    773 		    unsigned int imm_vsew = EXTRACT_OPERAND (XTHEADVSEW, imm);
    774 		    unsigned int imm_vtype_res
    775 		      = EXTRACT_OPERAND (XTHEADVTYPE_RES, imm);
    776 		    if (imm_vsew < ARRAY_SIZE (riscv_vsew)
    777 			&& imm_vlmul < ARRAY_SIZE (riscv_th_vlen)
    778 			&& imm_vediv < ARRAY_SIZE (riscv_th_vediv)
    779 			&& ! imm_vtype_res)
    780 		      print (info->stream, dis_style_text, "%s,%s,%s",
    781 			     riscv_vsew[imm_vsew], riscv_th_vlen[imm_vlmul],
    782 			     riscv_th_vediv[imm_vediv]);
    783 		    else
    784 		      print (info->stream, dis_style_immediate, "%d", imm);
    785 		    break;
    786 		  case 'l': /* Integer immediate, literal.  */
    787 		    oparg++;
    788 		    while (*oparg && *oparg != ',')
    789 		      {
    790 			print (info->stream, dis_style_immediate, "%c", *oparg);
    791 			oparg++;
    792 		      }
    793 		    oparg--;
    794 		    break;
    795 		  case 's': /* Integer immediate, 'XsN@S' ... N-bit signed immediate at bit S.  */
    796 		    sign = true;
    797 		    goto print_imm;
    798 		  case 'u': /* Integer immediate, 'XuN@S' ... N-bit unsigned immediate at bit S.  */
    799 		    sign = false;
    800 		    goto print_imm;
    801 		  print_imm:
    802 		    n = strtol (oparg + 1, (char **)&oparg, 10);
    803 		    if (*oparg != '@')
    804 		      goto undefined_modifier;
    805 		    s = strtol (oparg + 1, (char **)&oparg, 10);
    806 		    oparg--;
    807 
    808 		    if (!sign)
    809 		      print (info->stream, dis_style_immediate, "%lu",
    810 			     (unsigned long)EXTRACT_U_IMM (n, s, l));
    811 		    else
    812 		      print (info->stream, dis_style_immediate, "%li",
    813 			     (signed long)EXTRACT_S_IMM (n, s, l));
    814 		    break;
    815 		  default:
    816 		    goto undefined_modifier;
    817 		  }
    818 	      }
    819 	      break;
    820 	    case 'c': /* Vendor-specific (CORE-V) operands.  */
    821 	      switch (*++oparg)
    822 		{
    823 		  case '2':
    824 		    print (info->stream, dis_style_immediate, "%d",
    825 			((int) EXTRACT_CV_IS2_UIMM5 (l)));
    826 		    break;
    827 		  case '3':
    828 		    print (info->stream, dis_style_immediate, "%d",
    829 			((int) EXTRACT_CV_IS3_UIMM5 (l)));
    830 		    break;
    831 		  case '4':
    832 		    print (info->stream, dis_style_immediate, "%d",
    833 			   ((int) EXTRACT_CV_BI_IMM5 (l)));
    834 		    break;
    835 		  case '5':
    836 		    print (info->stream, dis_style_immediate, "%d",
    837 			   ((int) EXTRACT_CV_SIMD_IMM6 (l)));
    838 		    break;
    839 		  case '6':
    840 		    print (info->stream, dis_style_immediate, "%d",
    841 			   ((int) EXTRACT_CV_BITMANIP_UIMM5 (l)));
    842 		    break;
    843 		  case '7':
    844 		    print (info->stream, dis_style_immediate, "%d",
    845 			   ((int) EXTRACT_CV_BITMANIP_UIMM2 (l)));
    846 		    break;
    847 		  case '8':
    848 		    print (info->stream, dis_style_immediate, "%d",
    849 			   ((int) EXTRACT_CV_SIMD_UIMM6 (l)));
    850 		    ++oparg;
    851 		    break;
    852 		  default:
    853 		    goto undefined_modifier;
    854 		}
    855 	      break;
    856 	    case 's': /* Vendor-specific (SiFive) operands.  */
    857 	      switch (*++oparg)
    858 		{
    859 		/* SiFive vector coprocessor interface.  */
    860 		case 'd':
    861 		  print (info->stream, dis_style_register, "0x%x",
    862 			 (unsigned) EXTRACT_OPERAND (RD, l));
    863 		  break;
    864 		case 't':
    865 		  print (info->stream, dis_style_register, "0x%x",
    866 			 (unsigned) EXTRACT_OPERAND (RS2, l));
    867 		  break;
    868 		case 'O':
    869 		  switch (*++oparg)
    870 		    {
    871 		    case '2':
    872 		      print (info->stream, dis_style_register, "0x%x",
    873 			     (unsigned) EXTRACT_OPERAND (XSO2, l));
    874 		      break;
    875 		    case '1':
    876 		      print (info->stream, dis_style_register, "0x%x",
    877 			     (unsigned) EXTRACT_OPERAND (XSO1, l));
    878 		      break;
    879 		    }
    880 		  break;
    881 		}
    882 	      break;
    883 	    default:
    884 	      goto undefined_modifier;
    885 	    }
    886 	  break;
    887 
    888 	default:
    889 	undefined_modifier:
    890 	  /* xgettext:c-format */
    891 	  print (info->stream, dis_style_text,
    892 		 _("# internal error, undefined modifier (%c)"),
    893 		 *opargStart);
    894 	  return;
    895 	}
    896     }
    897 }
    898 
    899 /* Print the RISC-V instruction at address MEMADDR in debugged memory,
    900    on using INFO.  Returns length of the instruction, in bytes.
    901    BIGENDIAN must be 1 if this is big-endian code, 0 if
    902    this is little-endian code.  */
    903 
    904 static int
    905 riscv_disassemble_insn (bfd_vma memaddr,
    906 			insn_t word,
    907 			const bfd_byte *packet,
    908 			disassemble_info *info)
    909 {
    910   const struct riscv_opcode *op;
    911   static bool init = false;
    912   static const struct riscv_opcode *riscv_hash[OP_MASK_OP + 1];
    913   struct riscv_private_data *pd = info->private_data;
    914   int insnlen, i;
    915   bool printed;
    916 
    917 #define OP_HASH_IDX(i) ((i) & (riscv_insn_length (i) == 2 ? 0x3 : OP_MASK_OP))
    918 
    919   /* Build a hash table to shorten the search time.  */
    920   if (! init)
    921     {
    922       for (op = riscv_opcodes; op->name; op++)
    923 	if (!riscv_hash[OP_HASH_IDX (op->match)])
    924 	  riscv_hash[OP_HASH_IDX (op->match)] = op;
    925 
    926       init = true;
    927     }
    928 
    929   insnlen = riscv_insn_length (word);
    930 
    931   /* RISC-V instructions are always little-endian.  */
    932   info->endian_code = BFD_ENDIAN_LITTLE;
    933 
    934   info->bytes_per_chunk = insnlen % 4 == 0 ? 4 : 2;
    935   info->bytes_per_line = 8;
    936   /* We don't support constant pools, so this must be code.  */
    937   info->display_endian = info->endian_code;
    938   info->insn_info_valid = 1;
    939   info->branch_delay_insns = 0;
    940   info->data_size = 0;
    941   info->insn_type = dis_nonbranch;
    942   info->target = 0;
    943   info->target2 = 0;
    944 
    945   op = riscv_hash[OP_HASH_IDX (word)];
    946   if (op != NULL)
    947     {
    948       /* If XLEN is not known, get its value from the ELF class.  */
    949       if (info->mach == bfd_mach_riscv64)
    950 	xlen = 64;
    951       else if (info->mach == bfd_mach_riscv32)
    952 	xlen = 32;
    953       else if (info->section != NULL)
    954 	{
    955 	  Elf_Internal_Ehdr *ehdr = elf_elfheader (info->section->owner);
    956 	  xlen = ehdr->e_ident[EI_CLASS] == ELFCLASS64 ? 64 : 32;
    957 	}
    958 
    959       /* If arch has the Zfinx extension, replace FPR with GPR.  */
    960       if (riscv_subset_supports (&riscv_rps_dis, "zfinx"))
    961 	riscv_fpr_names = riscv_gpr_names;
    962       else
    963 	riscv_fpr_names = riscv_gpr_names == riscv_gpr_names_abi ?
    964 			  riscv_fpr_names_abi : riscv_fpr_names_numeric;
    965 
    966       for (; op->name; op++)
    967 	{
    968 	  /* Ignore macro insns.  */
    969 	  if (op->pinfo == INSN_MACRO)
    970 	    continue;
    971 	  /* Does the opcode match?  */
    972 	  if (! (op->match_func) (op, word))
    973 	    continue;
    974 	  /* Is this a pseudo-instruction and may we print it as such?  */
    975 	  if (no_aliases && (op->pinfo & INSN_ALIAS))
    976 	    continue;
    977 	  /* Is this instruction restricted to a certain value of XLEN?  */
    978 	  if ((op->xlen_requirement != 0) && (op->xlen_requirement != xlen))
    979 	    continue;
    980 	  /* Is this instruction supported by the current architecture?  */
    981 	  if (!all_ext
    982 	      && !riscv_multi_subset_supports (&riscv_rps_dis, op->insn_class))
    983 	    continue;
    984 
    985 	  /* It's a match.  */
    986 	  (*info->fprintf_styled_func) (info->stream, dis_style_mnemonic,
    987 					"%s", op->name);
    988 	  print_insn_args (op->args, word, memaddr, info);
    989 
    990 	  /* Try to disassemble multi-instruction addressing sequences.  */
    991 	  if (pd->to_print_addr)
    992 	    {
    993 	      info->target = pd->print_addr;
    994 	      (*info->fprintf_styled_func)
    995 		(info->stream, dis_style_comment_start, " # ");
    996 	      (*info->print_address_func) (info->target, info);
    997 	      pd->to_print_addr = false;
    998 	    }
    999 
   1000 	  /* Finish filling out insn_info fields.  */
   1001 	  switch (op->pinfo & INSN_TYPE)
   1002 	    {
   1003 	    case INSN_BRANCH:
   1004 	      info->insn_type = dis_branch;
   1005 	      break;
   1006 	    case INSN_CONDBRANCH:
   1007 	      info->insn_type = dis_condbranch;
   1008 	      break;
   1009 	    case INSN_JSR:
   1010 	      info->insn_type = dis_jsr;
   1011 	      break;
   1012 	    case INSN_DREF:
   1013 	      info->insn_type = dis_dref;
   1014 	      break;
   1015 	    default:
   1016 	      break;
   1017 	    }
   1018 
   1019 	  if (op->pinfo & INSN_DATA_SIZE)
   1020 	    {
   1021 	      int size = ((op->pinfo & INSN_DATA_SIZE)
   1022 			  >> INSN_DATA_SIZE_SHIFT);
   1023 	      info->data_size = 1 << (size - 1);
   1024 	    }
   1025 
   1026 	  return insnlen;
   1027 	}
   1028     }
   1029 
   1030   /* We did not find a match, so just print the instruction bits in
   1031      the shape of an assembler .insn directive.  */
   1032   info->insn_type = dis_noninsn;
   1033   (*info->fprintf_styled_func)
   1034     (info->stream, dis_style_assembler_directive, ".insn");
   1035   (*info->fprintf_styled_func) (info->stream, dis_style_text, "\t");
   1036   (*info->fprintf_styled_func) (info->stream, dis_style_immediate,
   1037 				"%d", insnlen);
   1038   (*info->fprintf_styled_func) (info->stream, dis_style_text, ", ");
   1039   (*info->fprintf_styled_func) (info->stream, dis_style_immediate, "0x");
   1040   for (i = insnlen, printed = false; i >= 2; )
   1041     {
   1042       i -= 2;
   1043       word = bfd_get_bits (packet + i, 16, false);
   1044       if (!word && !printed && i)
   1045 	continue;
   1046 
   1047       (*info->fprintf_styled_func) (info->stream, dis_style_immediate,
   1048 				    "%04x", (unsigned int) word);
   1049       printed = true;
   1050     }
   1051 
   1052   return insnlen;
   1053 }
   1054 
   1055 /* If we find the suitable mapping symbol update the STATE.
   1056    Otherwise, do nothing.  */
   1057 
   1058 static void
   1059 riscv_update_map_state (int n,
   1060 			enum riscv_seg_mstate *state,
   1061 			struct disassemble_info *info)
   1062 {
   1063   const char *name;
   1064 
   1065   /* If the symbol is in a different section, ignore it.  */
   1066   if (info->section != NULL
   1067       && info->section != info->symtab[n]->section)
   1068     return;
   1069 
   1070   name = bfd_asymbol_name(info->symtab[n]);
   1071   if (strcmp (name, "$x") == 0)
   1072     *state = MAP_INSN;
   1073   else if (strcmp (name, "$d") == 0)
   1074     *state = MAP_DATA;
   1075   else if (strncmp (name, "$xrv", 4) == 0)
   1076     {
   1077       *state = MAP_INSN;
   1078       riscv_release_subset_list (&riscv_subsets);
   1079 
   1080       /* ISA mapping string may be numbered, suffixed with '.n'. Do not
   1081 	 consider this as part of the ISA string.  */
   1082       char *suffix = strchr (name, '.');
   1083       if (suffix)
   1084 	{
   1085 	  int suffix_index = (int)(suffix - name);
   1086 	  char *name_substr = xmalloc (suffix_index + 1);
   1087 	  strncpy (name_substr, name, suffix_index);
   1088 	  name_substr[suffix_index] = '\0';
   1089 	  riscv_parse_subset (&riscv_rps_dis, name_substr + 2);
   1090 	  free (name_substr);
   1091 	}
   1092       else
   1093 	riscv_parse_subset (&riscv_rps_dis, name + 2);
   1094     }
   1095 }
   1096 
   1097 /* Return true if we find the suitable mapping symbol.
   1098    Otherwise, return false.  */
   1099 
   1100 static bool
   1101 riscv_is_valid_mapping_symbol (int n,
   1102 			     struct disassemble_info *info)
   1103 {
   1104   const char *name;
   1105 
   1106   /* If the symbol is in a different section, ignore it.  */
   1107   if (info->section != NULL
   1108       && info->section != info->symtab[n]->section)
   1109     return false;
   1110 
   1111   name = bfd_asymbol_name(info->symtab[n]);
   1112   return riscv_elf_is_mapping_symbols (name);
   1113 }
   1114 
   1115 /* Check the sorted symbol table (sorted by the symbol value), find the
   1116    suitable mapping symbols.  */
   1117 
   1118 static enum riscv_seg_mstate
   1119 riscv_search_mapping_symbol (bfd_vma memaddr,
   1120 			     struct disassemble_info *info)
   1121 {
   1122   enum riscv_seg_mstate mstate;
   1123   bool from_last_map_symbol;
   1124   bool found = false;
   1125   int symbol = -1;
   1126   int n;
   1127 
   1128   /* Return the last map state if the address is still within the range of the
   1129      last mapping symbol.  */
   1130   if (last_map_section == info->section
   1131       && (memaddr < last_map_symbol_boundary))
   1132     return last_map_state;
   1133 
   1134   last_map_section = info->section;
   1135 
   1136   /* Decide whether to print the data or instruction by default, in case
   1137      we can not find the corresponding mapping symbols.  */
   1138   mstate = MAP_DATA;
   1139   if ((info->section
   1140        && info->section->flags & SEC_CODE)
   1141       || !info->section)
   1142     mstate = MAP_INSN;
   1143 
   1144   if (info->symtab_size == 0
   1145       || bfd_asymbol_flavour (*info->symtab) != bfd_target_elf_flavour)
   1146     return mstate;
   1147 
   1148   /* Reset the last_map_symbol if we start to dump a new section.  */
   1149   if (memaddr <= 0)
   1150     last_map_symbol = -1;
   1151 
   1152   /* If the last stop offset is different from the current one, then
   1153      don't use the last_map_symbol to search.  We usually reset the
   1154      info->stop_offset when handling a new section.  */
   1155   from_last_map_symbol = (last_map_symbol >= 0
   1156 			  && info->stop_offset == last_stop_offset);
   1157 
   1158   /* Start scanning from wherever we finished last time, or the start
   1159      of the function.  */
   1160   n = from_last_map_symbol ? last_map_symbol : info->symtab_pos + 1;
   1161 
   1162   /* Find the suitable mapping symbol to dump.  */
   1163   for (; n < info->symtab_size; n++)
   1164     {
   1165       bfd_vma addr = bfd_asymbol_value (info->symtab[n]);
   1166       /* We have searched all possible symbols in the range.  */
   1167       if (addr > memaddr)
   1168 	break;
   1169       if (riscv_is_valid_mapping_symbol (n, info))
   1170 	{
   1171 	  symbol = n;
   1172 	  found = true;
   1173 	  /* Do not stop searching, in case there are some mapping
   1174 	     symbols have the same value, but have different names.
   1175 	     Use the last one.  */
   1176 	}
   1177     }
   1178 
   1179   /* We can not find the suitable mapping symbol above.  Therefore, we
   1180      look forwards and try to find it again, but don't go past the start
   1181      of the section.  Otherwise a data section without mapping symbols
   1182      can pick up a text mapping symbol of a preceeding section.  */
   1183   if (!found)
   1184     {
   1185       n = from_last_map_symbol ? last_map_symbol : info->symtab_pos;
   1186 
   1187       for (; n >= 0; n--)
   1188 	{
   1189 	  bfd_vma addr = bfd_asymbol_value (info->symtab[n]);
   1190 	  /* We have searched all possible symbols in the range.  */
   1191 	  if (addr < (info->section ? info->section->vma : 0))
   1192 	    break;
   1193 	  /* Stop searching once we find the closed mapping symbol.  */
   1194 	  if (riscv_is_valid_mapping_symbol (n, info))
   1195 	    {
   1196 	      symbol = n;
   1197 	      found = true;
   1198 	      break;
   1199 	    }
   1200 	}
   1201     }
   1202 
   1203   if (found)
   1204     {
   1205       riscv_update_map_state (symbol, &mstate, info);
   1206 
   1207       /* Find the next mapping symbol to determine the boundary of this mapping
   1208 	 symbol.  */
   1209 
   1210       bool found_next = false;
   1211       /* Try to found next mapping symbol.  */
   1212       for (n = symbol + 1; n < info->symtab_size; n++)
   1213 	{
   1214 	  if (info->symtab[symbol]->section != info->symtab[n]->section)
   1215 	    continue;
   1216 
   1217 	  bfd_vma addr = bfd_asymbol_value (info->symtab[n]);
   1218 	  const char *sym_name = bfd_asymbol_name(info->symtab[n]);
   1219 	  if (sym_name[0] == '$' && (sym_name[1] == 'x' || sym_name[1] == 'd'))
   1220 	    {
   1221 	      /* The next mapping symbol has been found, and it represents the
   1222 		 boundary of this mapping symbol.  */
   1223 	      found_next = true;
   1224 	      last_map_symbol_boundary = addr;
   1225 	      break;
   1226 	    }
   1227 	}
   1228 
   1229       /* No further mapping symbol has been found, indicating that the boundary
   1230 	 of the current mapping symbol is the end of this section.  */
   1231       if (!found_next)
   1232 	last_map_symbol_boundary = info->section->vma + info->section->size;
   1233     }
   1234 
   1235   /* Save the information for next use.  */
   1236   last_map_symbol = symbol;
   1237   last_stop_offset = info->stop_offset;
   1238 
   1239   return mstate;
   1240 }
   1241 
   1242 /* Decide which data size we should print.  */
   1243 
   1244 static bfd_vma
   1245 riscv_data_length (bfd_vma memaddr,
   1246 		   disassemble_info *info)
   1247 {
   1248   bfd_vma length;
   1249   bool found = false;
   1250 
   1251   length = 4;
   1252   if (info->symtab_size != 0
   1253       && bfd_asymbol_flavour (*info->symtab) == bfd_target_elf_flavour
   1254       && last_map_symbol >= 0)
   1255     {
   1256       int n;
   1257       enum riscv_seg_mstate m = MAP_NONE;
   1258       for (n = last_map_symbol + 1; n < info->symtab_size; n++)
   1259 	{
   1260 	  bfd_vma addr = bfd_asymbol_value (info->symtab[n]);
   1261 	  if (addr > memaddr
   1262 	      && riscv_is_valid_mapping_symbol (n, info))
   1263 	    {
   1264 	      if (addr - memaddr < length)
   1265 		length = addr - memaddr;
   1266 	      found = true;
   1267 	      riscv_update_map_state (n, &m, info);
   1268 	      break;
   1269 	    }
   1270 	}
   1271     }
   1272   if (!found)
   1273     {
   1274       /* Do not set the length which exceeds the section size.  */
   1275       bfd_vma offset = info->section->vma + info->section->size;
   1276       offset -= memaddr;
   1277       length = (offset < length) ? offset : length;
   1278     }
   1279   length = length == 3 ? 2 : length;
   1280   return length;
   1281 }
   1282 
   1283 /* Dump the data contents.  */
   1284 
   1285 static int
   1286 riscv_disassemble_data (bfd_vma memaddr ATTRIBUTE_UNUSED,
   1287 			insn_t data,
   1288 			const bfd_byte *packet ATTRIBUTE_UNUSED,
   1289 			disassemble_info *info)
   1290 {
   1291   info->display_endian = info->endian;
   1292 
   1293   switch (info->bytes_per_chunk)
   1294     {
   1295     case 1:
   1296       info->bytes_per_line = 6;
   1297       (*info->fprintf_styled_func)
   1298 	(info->stream, dis_style_assembler_directive, ".byte");
   1299       (*info->fprintf_styled_func) (info->stream, dis_style_text, "\t");
   1300       (*info->fprintf_styled_func) (info->stream, dis_style_immediate,
   1301 				    "0x%02x", (unsigned)data);
   1302       break;
   1303     case 2:
   1304       info->bytes_per_line = 8;
   1305       (*info->fprintf_styled_func)
   1306 	(info->stream, dis_style_assembler_directive, ".short");
   1307       (*info->fprintf_styled_func) (info->stream, dis_style_text, "\t");
   1308       (*info->fprintf_styled_func)
   1309 	(info->stream, dis_style_immediate, "0x%04x", (unsigned) data);
   1310       break;
   1311     case 4:
   1312       info->bytes_per_line = 8;
   1313       (*info->fprintf_styled_func)
   1314 	(info->stream, dis_style_assembler_directive, ".word");
   1315       (*info->fprintf_styled_func) (info->stream, dis_style_text, "\t");
   1316       (*info->fprintf_styled_func)
   1317 	(info->stream, dis_style_immediate, "0x%08lx",
   1318 	 (unsigned long) data);
   1319       break;
   1320     case 8:
   1321       info->bytes_per_line = 8;
   1322       (*info->fprintf_styled_func)
   1323 	(info->stream, dis_style_assembler_directive, ".dword");
   1324       (*info->fprintf_styled_func) (info->stream, dis_style_text, "\t");
   1325       (*info->fprintf_styled_func)
   1326 	(info->stream, dis_style_immediate, "0x%016llx",
   1327 	 (unsigned long long) data);
   1328       break;
   1329     default:
   1330       abort ();
   1331     }
   1332   return info->bytes_per_chunk;
   1333 }
   1334 
   1335 static bool
   1336 riscv_init_disasm_info (struct disassemble_info *info)
   1337 {
   1338   int i;
   1339 
   1340   struct riscv_private_data *pd =
   1341 	xcalloc (1, sizeof (struct riscv_private_data));
   1342   pd->gp = 0;
   1343   pd->print_addr = 0;
   1344   for (i = 0; i < (int) ARRAY_SIZE (pd->hi_addr); i++)
   1345     pd->hi_addr[i] = -1;
   1346   pd->to_print_addr = false;
   1347   pd->has_gp = false;
   1348 
   1349   for (i = 0; i < info->symtab_size; i++)
   1350     {
   1351       asymbol *sym = info->symtab[i];
   1352       if (strcmp (bfd_asymbol_name (sym), RISCV_GP_SYMBOL) == 0)
   1353 	{
   1354 	  pd->gp = bfd_asymbol_value (sym);
   1355 	  pd->has_gp = true;
   1356 	}
   1357     }
   1358 
   1359   info->private_data = pd;
   1360   return true;
   1361 }
   1362 
   1363 int
   1364 print_insn_riscv (bfd_vma memaddr, struct disassemble_info *info)
   1365 {
   1366   bfd_byte packet[RISCV_MAX_INSN_LEN];
   1367   insn_t insn = 0;
   1368   bfd_vma dump_size;
   1369   int status;
   1370   enum riscv_seg_mstate mstate;
   1371   int (*riscv_disassembler) (bfd_vma, insn_t, const bfd_byte *,
   1372 			     struct disassemble_info *);
   1373 
   1374   if (info->disassembler_options != NULL)
   1375     {
   1376       parse_riscv_dis_options (info->disassembler_options);
   1377       /* Avoid repeatedly parsing the options.  */
   1378       info->disassembler_options = NULL;
   1379     }
   1380   else if (riscv_gpr_names == NULL)
   1381     set_default_riscv_dis_options ();
   1382 
   1383   if (info->private_data == NULL && !riscv_init_disasm_info (info))
   1384     return -1;
   1385 
   1386   mstate = riscv_search_mapping_symbol (memaddr, info);
   1387   /* Save the last mapping state.  */
   1388   last_map_state = mstate;
   1389 
   1390   /* Set the size to dump.  */
   1391   if (mstate == MAP_DATA
   1392       && (info->flags & DISASSEMBLE_DATA) == 0)
   1393     {
   1394       dump_size = riscv_data_length (memaddr, info);
   1395       info->bytes_per_chunk = dump_size;
   1396       riscv_disassembler = riscv_disassemble_data;
   1397     }
   1398   else
   1399     {
   1400       /* Get the first 2-bytes to check the lenghth of instruction.  */
   1401       status = (*info->read_memory_func) (memaddr, packet, 2, info);
   1402       if (status != 0)
   1403 	{
   1404 	  (*info->memory_error_func) (status, memaddr, info);
   1405 	  return -1;
   1406 	}
   1407       insn = (insn_t) bfd_getl16 (packet);
   1408       dump_size = riscv_insn_length (insn);
   1409       riscv_disassembler = riscv_disassemble_insn;
   1410     }
   1411 
   1412   /* Fetch the instruction to dump.  */
   1413   status = (*info->read_memory_func) (memaddr, packet, dump_size, info);
   1414   if (status != 0)
   1415     {
   1416       (*info->memory_error_func) (status, memaddr, info);
   1417       return -1;
   1418     }
   1419   insn = (insn_t) bfd_get_bits (packet, dump_size * 8, false);
   1420 
   1421   return (*riscv_disassembler) (memaddr, insn, packet, info);
   1422 }
   1423 
   1424 disassembler_ftype
   1425 riscv_get_disassembler (bfd *abfd)
   1426 {
   1427   const char *default_arch = "rv64gc";
   1428 
   1429   if (abfd && bfd_get_flavour (abfd) == bfd_target_elf_flavour)
   1430     {
   1431       const char *sec_name = get_elf_backend_data (abfd)->obj_attrs_section;
   1432       if (bfd_get_section_by_name (abfd, sec_name) != NULL)
   1433 	{
   1434 	  obj_attribute *attr = elf_known_obj_attributes_proc (abfd);
   1435 	  unsigned int Tag_a = Tag_RISCV_priv_spec;
   1436 	  unsigned int Tag_b = Tag_RISCV_priv_spec_minor;
   1437 	  unsigned int Tag_c = Tag_RISCV_priv_spec_revision;
   1438 	  riscv_get_priv_spec_class_from_numbers (attr[Tag_a].i,
   1439 						  attr[Tag_b].i,
   1440 						  attr[Tag_c].i,
   1441 						  &default_priv_spec);
   1442 	  default_arch = attr[Tag_RISCV_arch].s;
   1443 	}
   1444     }
   1445 
   1446   riscv_release_subset_list (&riscv_subsets);
   1447   riscv_parse_subset (&riscv_rps_dis, default_arch);
   1448   return print_insn_riscv;
   1449 }
   1450 
   1451 /* Prevent use of the fake labels that are generated as part of the DWARF
   1452    and for relaxable relocations in the assembler.  */
   1453 
   1454 bool
   1455 riscv_symbol_is_valid (asymbol * sym,
   1456                        struct disassemble_info * info ATTRIBUTE_UNUSED)
   1457 {
   1458   const char * name;
   1459 
   1460   if (sym == NULL)
   1461     return false;
   1462 
   1463   name = bfd_asymbol_name (sym);
   1464 
   1465   return (strcmp (name, RISCV_FAKE_LABEL_NAME) != 0
   1466 	  && !riscv_elf_is_mapping_symbols (name));
   1467 }
   1468 
   1469 
   1471 /* Indices into option argument vector for options accepting an argument.
   1472    Use RISCV_OPTION_ARG_NONE for options accepting no argument.  */
   1473 
   1474 typedef enum
   1475 {
   1476   RISCV_OPTION_ARG_NONE = -1,
   1477   RISCV_OPTION_ARG_PRIV_SPEC,
   1478 
   1479   RISCV_OPTION_ARG_COUNT
   1480 } riscv_option_arg_t;
   1481 
   1482 /* Valid RISCV disassembler options.  */
   1483 
   1484 static struct
   1485 {
   1486   const char *name;
   1487   const char *description;
   1488   riscv_option_arg_t arg;
   1489 } riscv_options[] =
   1490 {
   1491   { "numeric",
   1492     N_("Print numeric register names, rather than ABI names."),
   1493     RISCV_OPTION_ARG_NONE },
   1494   { "no-aliases",
   1495     N_("Disassemble only into canonical instructions."),
   1496     RISCV_OPTION_ARG_NONE },
   1497   { "priv-spec=",
   1498     N_("Print the CSR according to the chosen privilege spec."),
   1499     RISCV_OPTION_ARG_PRIV_SPEC }
   1500 };
   1501 
   1502 /* Build the structure representing valid RISCV disassembler options.
   1503    This is done dynamically for maintenance ease purpose; a static
   1504    initializer would be unreadable.  */
   1505 
   1506 const disasm_options_and_args_t *
   1507 disassembler_options_riscv (void)
   1508 {
   1509   static disasm_options_and_args_t *opts_and_args;
   1510 
   1511   if (opts_and_args == NULL)
   1512     {
   1513       size_t num_options = ARRAY_SIZE (riscv_options);
   1514       size_t num_args = RISCV_OPTION_ARG_COUNT;
   1515       disasm_option_arg_t *args;
   1516       disasm_options_t *opts;
   1517       size_t i, priv_spec_count;
   1518 
   1519       args = XNEWVEC (disasm_option_arg_t, num_args + 1);
   1520 
   1521       args[RISCV_OPTION_ARG_PRIV_SPEC].name = "SPEC";
   1522       priv_spec_count = PRIV_SPEC_CLASS_DRAFT - PRIV_SPEC_CLASS_NONE - 1;
   1523       args[RISCV_OPTION_ARG_PRIV_SPEC].values
   1524         = XNEWVEC (const char *, priv_spec_count + 1);
   1525       for (i = 0; i < priv_spec_count; i++)
   1526 	args[RISCV_OPTION_ARG_PRIV_SPEC].values[i]
   1527           = riscv_priv_specs[i].name;
   1528       /* The array we return must be NULL terminated.  */
   1529       args[RISCV_OPTION_ARG_PRIV_SPEC].values[i] = NULL;
   1530 
   1531       /* The array we return must be NULL terminated.  */
   1532       args[num_args].name = NULL;
   1533       args[num_args].values = NULL;
   1534 
   1535       opts_and_args = XNEW (disasm_options_and_args_t);
   1536       opts_and_args->args = args;
   1537 
   1538       opts = &opts_and_args->options;
   1539       opts->name = XNEWVEC (const char *, num_options + 1);
   1540       opts->description = XNEWVEC (const char *, num_options + 1);
   1541       opts->arg = XNEWVEC (const disasm_option_arg_t *, num_options + 1);
   1542       for (i = 0; i < num_options; i++)
   1543 	{
   1544 	  opts->name[i] = riscv_options[i].name;
   1545 	  opts->description[i] = _(riscv_options[i].description);
   1546 	  if (riscv_options[i].arg != RISCV_OPTION_ARG_NONE)
   1547 	    opts->arg[i] = &args[riscv_options[i].arg];
   1548 	  else
   1549 	    opts->arg[i] = NULL;
   1550 	}
   1551       /* The array we return must be NULL terminated.  */
   1552       opts->name[i] = NULL;
   1553       opts->description[i] = NULL;
   1554       opts->arg[i] = NULL;
   1555     }
   1556 
   1557   return opts_and_args;
   1558 }
   1559 
   1560 void
   1561 print_riscv_disassembler_options (FILE *stream)
   1562 {
   1563   const disasm_options_and_args_t *opts_and_args;
   1564   const disasm_option_arg_t *args;
   1565   const disasm_options_t *opts;
   1566   size_t max_len = 0;
   1567   size_t i;
   1568   size_t j;
   1569 
   1570   opts_and_args = disassembler_options_riscv ();
   1571   opts = &opts_and_args->options;
   1572   args = opts_and_args->args;
   1573 
   1574   fprintf (stream, _("\n\
   1575 The following RISC-V specific disassembler options are supported for use\n\
   1576 with the -M switch (multiple options should be separated by commas):\n"));
   1577   fprintf (stream, "\n");
   1578 
   1579   /* Compute the length of the longest option name.  */
   1580   for (i = 0; opts->name[i] != NULL; i++)
   1581     {
   1582       size_t len = strlen (opts->name[i]);
   1583 
   1584       if (opts->arg[i] != NULL)
   1585 	len += strlen (opts->arg[i]->name);
   1586       if (max_len < len)
   1587 	max_len = len;
   1588     }
   1589 
   1590   for (i = 0, max_len++; opts->name[i] != NULL; i++)
   1591     {
   1592       fprintf (stream, "  %s", opts->name[i]);
   1593       if (opts->arg[i] != NULL)
   1594 	fprintf (stream, "%s", opts->arg[i]->name);
   1595       if (opts->description[i] != NULL)
   1596 	{
   1597 	  size_t len = strlen (opts->name[i]);
   1598 
   1599 	  if (opts->arg != NULL && opts->arg[i] != NULL)
   1600 	    len += strlen (opts->arg[i]->name);
   1601 	  fprintf (stream, "%*c %s", (int) (max_len - len), ' ',
   1602                    opts->description[i]);
   1603 	}
   1604       fprintf (stream, "\n");
   1605     }
   1606 
   1607   for (i = 0; args[i].name != NULL; i++)
   1608     {
   1609       if (args[i].values == NULL)
   1610 	continue;
   1611       fprintf (stream, _("\n\
   1612   For the options above, the following values are supported for \"%s\":\n   "),
   1613 	       args[i].name);
   1614       for (j = 0; args[i].values[j] != NULL; j++)
   1615 	fprintf (stream, " %s", args[i].values[j]);
   1616       fprintf (stream, _("\n"));
   1617     }
   1618 
   1619   fprintf (stream, _("\n"));
   1620 }
   1621 
   1622 void disassemble_free_riscv (struct disassemble_info *info ATTRIBUTE_UNUSED)
   1623 {
   1624   riscv_release_subset_list (&riscv_subsets);
   1625 }
   1626