gdb/avr-tdep.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Target-dependent code for Atmel AVR, for GDB.

  2.    Copyright (C) 1996-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. /* Contributed by Theodore A. Roth, troth@openavr.org */

  15. /* Portions of this file were taken from the original gdb-4.18 patch developed
  16.    by Denis Chertykov, denisc@overta.ru */

  17. #include "defs.h"
  18. #include "frame.h"
  19. #include "frame-unwind.h"
  20. #include "frame-base.h"
  21. #include "trad-frame.h"
  22. #include "gdbcmd.h"
  23. #include "gdbcore.h"
  24. #include "gdbtypes.h"
  25. #include "inferior.h"
  26. #include "symfile.h"
  27. #include "arch-utils.h"
  28. #include "regcache.h"
  29. #include "dis-asm.h"
  30. #include "objfiles.h"

  31. /* AVR Background:

  32.    (AVR micros are pure Harvard Architecture processors.)

  33.    The AVR family of microcontrollers have three distinctly different memory
  34.    spaces: flash, sram and eeprom.  The flash is 16 bits wide and is used for
  35.    the most part to store program instructions.  The sram is 8 bits wide and is
  36.    used for the stack and the heap.  Some devices lack sram and some can have
  37.    an additional external sram added on as a peripheral.

  38.    The eeprom is 8 bits wide and is used to store data when the device is
  39.    powered down.  Eeprom is not directly accessible, it can only be accessed
  40.    via io-registers using a special algorithm.  Accessing eeprom via gdb's
  41.    remote serial protocol ('m' or 'M' packets) looks difficult to do and is
  42.    not included at this time.

  43.    [The eeprom could be read manually via ``x/b <eaddr + AVR_EMEM_START>'' or
  44.    written using ``set {unsigned char}<eaddr + AVR_EMEM_START>''.  For this to
  45.    work, the remote target must be able to handle eeprom accesses and perform
  46.    the address translation.]

  47.    All three memory spaces have physical addresses beginning at 0x0.  In
  48.    addition, the flash is addressed by gcc/binutils/gdb with respect to 8 bit
  49.    bytes instead of the 16 bit wide words used by the real device for the
  50.    Program Counter.

  51.    In order for remote targets to work correctly, extra bits must be added to
  52.    addresses before they are send to the target or received from the target
  53.    via the remote serial protocol.  The extra bits are the MSBs and are used to
  54.    decode which memory space the address is referring to.  */

  55. /* Constants: prefixed with AVR_ to avoid name space clashes */

  56. /* Address space flags */

  57. /* We are assigning the TYPE_INSTANCE_FLAG_ADDRESS_CLASS_1 to the flash address
  58.    space.  */

  59. #define AVR_TYPE_ADDRESS_CLASS_FLASH TYPE_ADDRESS_CLASS_1
  60. #define AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH  \
  61.   TYPE_INSTANCE_FLAG_ADDRESS_CLASS_1


  62. enum
  63. {
  64.   AVR_REG_W = 24,
  65.   AVR_REG_X = 26,
  66.   AVR_REG_Y = 28,
  67.   AVR_FP_REGNUM = 28,
  68.   AVR_REG_Z = 30,

  69.   AVR_SREG_REGNUM = 32,
  70.   AVR_SP_REGNUM = 33,
  71.   AVR_PC_REGNUM = 34,

  72.   AVR_NUM_REGS = 32 + 1 /*SREG*/ + 1 /*SP*/ + 1 /*PC*/,
  73.   AVR_NUM_REG_BYTES = 32 + 1 /*SREG*/ + 2 /*SP*/ + 4 /*PC*/,

  74.   /* Pseudo registers.  */
  75.   AVR_PSEUDO_PC_REGNUM = 35,
  76.   AVR_NUM_PSEUDO_REGS = 1,

  77.   AVR_PC_REG_INDEX = 35,        /* index into array of registers */

  78.   AVR_MAX_PROLOGUE_SIZE = 64,        /* bytes */

  79.   /* Count of pushed registers.  From r2 to r17 (inclusively), r28, r29 */
  80.   AVR_MAX_PUSHES = 18,

  81.   /* Number of the last pushed register.  r17 for current avr-gcc */
  82.   AVR_LAST_PUSHED_REGNUM = 17,

  83.   AVR_ARG1_REGNUM = 24,         /* Single byte argument */
  84.   AVR_ARGN_REGNUM = 25,         /* Multi byte argments */

  85.   AVR_RET1_REGNUM = 24,         /* Single byte return value */
  86.   AVR_RETN_REGNUM = 25,         /* Multi byte return value */

  87.   /* FIXME: TRoth/2002-01-??: Can we shift all these memory masks left 8
  88.      bits?  Do these have to match the bfd vma values?  It sure would make
  89.      things easier in the future if they didn't need to match.

  90.      Note: I chose these values so as to be consistent with bfd vma
  91.      addresses.

  92.      TRoth/2002-04-08: There is already a conflict with very large programs
  93.      in the mega128.  The mega128 has 128K instruction bytes (64K words),
  94.      thus the Most Significant Bit is 0x10000 which gets masked off my
  95.      AVR_MEM_MASK.

  96.      The problem manifests itself when trying to set a breakpoint in a
  97.      function which resides in the upper half of the instruction space and
  98.      thus requires a 17-bit address.

  99.      For now, I've just removed the EEPROM mask and changed AVR_MEM_MASK
  100.      from 0x00ff0000 to 0x00f00000.  Eeprom is not accessible from gdb yet,
  101.      but could be for some remote targets by just adding the correct offset
  102.      to the address and letting the remote target handle the low-level
  103.      details of actually accessing the eeprom.  */

  104.   AVR_IMEM_START = 0x00000000,        /* INSN memory */
  105.   AVR_SMEM_START = 0x00800000,        /* SRAM memory */
  106. #if 1
  107.   /* No eeprom mask defined */
  108.   AVR_MEM_MASK = 0x00f00000,        /* mask to determine memory space */
  109. #else
  110.   AVR_EMEM_START = 0x00810000,        /* EEPROM memory */
  111.   AVR_MEM_MASK = 0x00ff0000,        /* mask to determine memory space */
  112. #endif
  113. };

  114. /* Prologue types:

  115.    NORMAL and CALL are the typical types (the -mcall-prologues gcc option
  116.    causes the generation of the CALL type prologues).  */

  117. enum {
  118.     AVR_PROLOGUE_NONE,              /* No prologue */
  119.     AVR_PROLOGUE_NORMAL,
  120.     AVR_PROLOGUE_CALL,              /* -mcall-prologues */
  121.     AVR_PROLOGUE_MAIN,
  122.     AVR_PROLOGUE_INTR,              /* interrupt handler */
  123.     AVR_PROLOGUE_SIG,               /* signal handler */
  124. };

  125. /* Any function with a frame looks like this
  126.    .......    <-SP POINTS HERE
  127.    LOCALS1    <-FP POINTS HERE
  128.    LOCALS0
  129.    SAVED FP
  130.    SAVED R3
  131.    SAVED R2
  132.    RET PC
  133.    FIRST ARG
  134.    SECOND ARG */

  135. struct avr_unwind_cache
  136. {
  137.   /* The previous frame's inner most stack address.  Used as this
  138.      frame ID's stack_addr.  */
  139.   CORE_ADDR prev_sp;
  140.   /* The frame's base, optionally used by the high-level debug info.  */
  141.   CORE_ADDR base;
  142.   int size;
  143.   int prologue_type;
  144.   /* Table indicating the location of each and every register.  */
  145.   struct trad_frame_saved_reg *saved_regs;
  146. };

  147. struct gdbarch_tdep
  148. {
  149.   /* Number of bytes stored to the stack by call instructions.
  150.      2 bytes for avr1-5 and avrxmega1-5, 3 bytes for avr6 and avrxmega6-7.  */
  151.   int call_length;

  152.   /* Type for void.  */
  153.   struct type *void_type;
  154.   /* Type for a function returning void.  */
  155.   struct type *func_void_type;
  156.   /* Type for a pointer to a function.  Used for the type of PC.  */
  157.   struct type *pc_type;
  158. };

  159. /* Lookup the name of a register given it's number.  */

  160. static const char *
  161. avr_register_name (struct gdbarch *gdbarch, int regnum)
  162. {
  163.   static const char * const register_names[] = {
  164.     "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
  165.     "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
  166.     "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
  167.     "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
  168.     "SREG", "SP", "PC2",
  169.     "pc"
  170.   };
  171.   if (regnum < 0)
  172.     return NULL;
  173.   if (regnum >= (sizeof (register_names) / sizeof (*register_names)))
  174.     return NULL;
  175.   return register_names[regnum];
  176. }

  177. /* Return the GDB type object for the "standard" data type
  178.    of data in register N.  */

  179. static struct type *
  180. avr_register_type (struct gdbarch *gdbarch, int reg_nr)
  181. {
  182.   if (reg_nr == AVR_PC_REGNUM)
  183.     return builtin_type (gdbarch)->builtin_uint32;
  184.   if (reg_nr == AVR_PSEUDO_PC_REGNUM)
  185.     return gdbarch_tdep (gdbarch)->pc_type;
  186.   if (reg_nr == AVR_SP_REGNUM)
  187.     return builtin_type (gdbarch)->builtin_data_ptr;
  188.   return builtin_type (gdbarch)->builtin_uint8;
  189. }

  190. /* Instruction address checks and convertions.  */

  191. static CORE_ADDR
  192. avr_make_iaddr (CORE_ADDR x)
  193. {
  194.   return ((x) | AVR_IMEM_START);
  195. }

  196. /* FIXME: TRoth: Really need to use a larger mask for instructions.  Some
  197.    devices are already up to 128KBytes of flash space.

  198.    TRoth/2002-04-8: See comment above where AVR_IMEM_START is defined.  */

  199. static CORE_ADDR
  200. avr_convert_iaddr_to_raw (CORE_ADDR x)
  201. {
  202.   return ((x) & 0xffffffff);
  203. }

  204. /* SRAM address checks and convertions.  */

  205. static CORE_ADDR
  206. avr_make_saddr (CORE_ADDR x)
  207. {
  208.   /* Return 0 for NULL.  */
  209.   if (x == 0)
  210.     return 0;

  211.   return ((x) | AVR_SMEM_START);
  212. }

  213. static CORE_ADDR
  214. avr_convert_saddr_to_raw (CORE_ADDR x)
  215. {
  216.   return ((x) & 0xffffffff);
  217. }

  218. /* EEPROM address checks and convertions.  I don't know if these will ever
  219.    actually be used, but I've added them just the same.  TRoth */

  220. /* TRoth/2002-04-08: Commented out for now to allow fix for problem with large
  221.    programs in the mega128.  */

  222. /*  static CORE_ADDR */
  223. /*  avr_make_eaddr (CORE_ADDR x) */
  224. /*  { */
  225. /*    return ((x) | AVR_EMEM_START); */
  226. /*  } */

  227. /*  static int */
  228. /*  avr_eaddr_p (CORE_ADDR x) */
  229. /*  { */
  230. /*    return (((x) & AVR_MEM_MASK) == AVR_EMEM_START); */
  231. /*  } */

  232. /*  static CORE_ADDR */
  233. /*  avr_convert_eaddr_to_raw (CORE_ADDR x) */
  234. /*  { */
  235. /*    return ((x) & 0xffffffff); */
  236. /*  } */

  237. /* Convert from address to pointer and vice-versa.  */

  238. static void
  239. avr_address_to_pointer (struct gdbarch *gdbarch,
  240.                         struct type *type, gdb_byte *buf, CORE_ADDR addr)
  241. {
  242.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);

  243.   /* Is it a data address in flash?  */
  244.   if (AVR_TYPE_ADDRESS_CLASS_FLASH (type))
  245.     {
  246.       /* A data pointer in flash is byte addressed.  */
  247.       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
  248.                               avr_convert_iaddr_to_raw (addr));
  249.     }
  250.   /* Is it a code address?  */
  251.   else if (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC
  252.            || TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_METHOD)
  253.     {
  254.       /* A code pointer is word (16 bits) addressed.  We shift the address down
  255.          by 1 bit to convert it to a pointer.  */
  256.       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
  257.                               avr_convert_iaddr_to_raw (addr >> 1));
  258.     }
  259.   else
  260.     {
  261.       /* Strip off any upper segment bits.  */
  262.       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
  263.                               avr_convert_saddr_to_raw (addr));
  264.     }
  265. }

  266. static CORE_ADDR
  267. avr_pointer_to_address (struct gdbarch *gdbarch,
  268.                         struct type *type, const gdb_byte *buf)
  269. {
  270.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  271.   CORE_ADDR addr
  272.     = extract_unsigned_integer (buf, TYPE_LENGTH (type), byte_order);

  273.   /* Is it a data address in flash?  */
  274.   if (AVR_TYPE_ADDRESS_CLASS_FLASH (type))
  275.     {
  276.       /* A data pointer in flash is already byte addressed.  */
  277.       return avr_make_iaddr (addr);
  278.     }
  279.   /* Is it a code address?  */
  280.   else if (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC
  281.            || TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_METHOD
  282.            || TYPE_CODE_SPACE (TYPE_TARGET_TYPE (type)))
  283.     {
  284.       /* A code pointer is word (16 bits) addressed so we shift it up
  285.          by 1 bit to convert it to an address.  */
  286.       return avr_make_iaddr (addr << 1);
  287.     }
  288.   else
  289.     return avr_make_saddr (addr);
  290. }

  291. static CORE_ADDR
  292. avr_integer_to_address (struct gdbarch *gdbarch,
  293.                         struct type *type, const gdb_byte *buf)
  294. {
  295.   ULONGEST addr = unpack_long (type, buf);

  296.   return avr_make_saddr (addr);
  297. }

  298. static CORE_ADDR
  299. avr_read_pc (struct regcache *regcache)
  300. {
  301.   ULONGEST pc;
  302.   regcache_cooked_read_unsigned (regcache, AVR_PC_REGNUM, &pc);
  303.   return avr_make_iaddr (pc);
  304. }

  305. static void
  306. avr_write_pc (struct regcache *regcache, CORE_ADDR val)
  307. {
  308.   regcache_cooked_write_unsigned (regcache, AVR_PC_REGNUM,
  309.                                   avr_convert_iaddr_to_raw (val));
  310. }

  311. static enum register_status
  312. avr_pseudo_register_read (struct gdbarch *gdbarch, struct regcache *regcache,
  313.                           int regnum, gdb_byte *buf)
  314. {
  315.   ULONGEST val;
  316.   enum register_status status;

  317.   switch (regnum)
  318.     {
  319.     case AVR_PSEUDO_PC_REGNUM:
  320.       status = regcache_raw_read_unsigned (regcache, AVR_PC_REGNUM, &val);
  321.       if (status != REG_VALID)
  322.         return status;
  323.       val >>= 1;
  324.       store_unsigned_integer (buf, 4, gdbarch_byte_order (gdbarch), val);
  325.       return status;
  326.     default:
  327.       internal_error (__FILE__, __LINE__, _("invalid regnum"));
  328.     }
  329. }

  330. static void
  331. avr_pseudo_register_write (struct gdbarch *gdbarch, struct regcache *regcache,
  332.                            int regnum, const gdb_byte *buf)
  333. {
  334.   ULONGEST val;

  335.   switch (regnum)
  336.     {
  337.     case AVR_PSEUDO_PC_REGNUM:
  338.       val = extract_unsigned_integer (buf, 4, gdbarch_byte_order (gdbarch));
  339.       val <<= 1;
  340.       regcache_raw_write_unsigned (regcache, AVR_PC_REGNUM, val);
  341.       break;
  342.     default:
  343.       internal_error (__FILE__, __LINE__, _("invalid regnum"));
  344.     }
  345. }

  346. /* Function: avr_scan_prologue

  347.    This function decodes an AVR function prologue to determine:
  348.      1) the size of the stack frame
  349.      2) which registers are saved on it
  350.      3) the offsets of saved regs
  351.    This information is stored in the avr_unwind_cache structure.

  352.    Some devices lack the sbiw instruction, so on those replace this:
  353.         sbiw    r28, XX
  354.    with this:
  355.         subi    r28,lo8(XX)
  356.         sbci    r29,hi8(XX)

  357.    A typical AVR function prologue with a frame pointer might look like this:
  358.         push    rXX        ; saved regs
  359.         ...
  360.         push    r28
  361.         push    r29
  362.         in      r28,__SP_L__
  363.         in      r29,__SP_H__
  364.         sbiw    r28,<LOCALS_SIZE>
  365.         in      __tmp_reg__,__SREG__
  366.         cli
  367.         out     __SP_H__,r29
  368.         out     __SREG__,__tmp_reg__
  369.         out     __SP_L__,r28

  370.    A typical AVR function prologue without a frame pointer might look like
  371.    this:
  372.         push    rXX        ; saved regs
  373.         ...

  374.    A main function prologue looks like this:
  375.         ldi     r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>)
  376.         ldi     r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>)
  377.         out     __SP_H__,r29
  378.         out     __SP_L__,r28

  379.    A signal handler prologue looks like this:
  380.         push    __zero_reg__
  381.         push    __tmp_reg__
  382.         in      __tmp_reg__, __SREG__
  383.         push    __tmp_reg__
  384.         clr     __zero_reg__
  385.         push    rXX             ; save registers r18:r27, r30:r31
  386.         ...
  387.         push    r28             ; save frame pointer
  388.         push    r29
  389.         in      r28, __SP_L__
  390.         in      r29, __SP_H__
  391.         sbiw    r28, <LOCALS_SIZE>
  392.         out     __SP_H__, r29
  393.         out     __SP_L__, r28

  394.    A interrupt handler prologue looks like this:
  395.         sei
  396.         push    __zero_reg__
  397.         push    __tmp_reg__
  398.         in      __tmp_reg__, __SREG__
  399.         push    __tmp_reg__
  400.         clr     __zero_reg__
  401.         push    rXX             ; save registers r18:r27, r30:r31
  402.         ...
  403.         push    r28             ; save frame pointer
  404.         push    r29
  405.         in      r28, __SP_L__
  406.         in      r29, __SP_H__
  407.         sbiw    r28, <LOCALS_SIZE>
  408.         cli
  409.         out     __SP_H__, r29
  410.         sei
  411.         out     __SP_L__, r28

  412.    A `-mcall-prologues' prologue looks like this (Note that the megas use a
  413.    jmp instead of a rjmp, thus the prologue is one word larger since jmp is a
  414.    32 bit insn and rjmp is a 16 bit insn):
  415.         ldi     r26,lo8(<LOCALS_SIZE>)
  416.         ldi     r27,hi8(<LOCALS_SIZE>)
  417.         ldi     r30,pm_lo8(.L_foo_body)
  418.         ldi     r31,pm_hi8(.L_foo_body)
  419.         rjmp    __prologue_saves__+RRR
  420.         .L_foo_body:  */

  421. /* Not really part of a prologue, but still need to scan for it, is when a
  422.    function prologue moves values passed via registers as arguments to new
  423.    registers.  In this case, all local variables live in registers, so there
  424.    may be some register saves.  This is what it looks like:
  425.         movw    rMM, rNN
  426.         ...

  427.    There could be multiple movw's.  If the target doesn't have a movw insn, it
  428.    will use two mov insns.  This could be done after any of the above prologue
  429.    types.  */

  430. static CORE_ADDR
  431. avr_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR pc_beg, CORE_ADDR pc_end,
  432.                    struct avr_unwind_cache *info)
  433. {
  434.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  435.   int i;
  436.   unsigned short insn;
  437.   int scan_stage = 0;
  438.   struct bound_minimal_symbol msymbol;
  439.   unsigned char prologue[AVR_MAX_PROLOGUE_SIZE];
  440.   int vpc = 0;
  441.   int len;

  442.   len = pc_end - pc_beg;
  443.   if (len > AVR_MAX_PROLOGUE_SIZE)
  444.     len = AVR_MAX_PROLOGUE_SIZE;

  445.   /* FIXME: TRoth/2003-06-11: This could be made more efficient by only
  446.      reading in the bytes of the prologue.  The problem is that the figuring
  447.      out where the end of the prologue is is a bit difficult.  The old code
  448.      tried to do that, but failed quite often.  */
  449.   read_memory (pc_beg, prologue, len);

  450.   /* Scanning main()'s prologue
  451.      ldi r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>)
  452.      ldi r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>)
  453.      out __SP_H__,r29
  454.      out __SP_L__,r28 */

  455.   if (len >= 4)
  456.     {
  457.       CORE_ADDR locals;
  458.       static const unsigned char img[] = {
  459.         0xde, 0xbf,                /* out __SP_H__,r29 */
  460.         0xcd, 0xbf                /* out __SP_L__,r28 */
  461.       };

  462.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  463.       /* ldi r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>) */
  464.       if ((insn & 0xf0f0) == 0xe0c0)
  465.         {
  466.           locals = (insn & 0xf) | ((insn & 0x0f00) >> 4);
  467.           insn = extract_unsigned_integer (&prologue[vpc + 2], 2, byte_order);
  468.           /* ldi r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>) */
  469.           if ((insn & 0xf0f0) == 0xe0d0)
  470.             {
  471.               locals |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
  472.               if (vpc + 4 + sizeof (img) < len
  473.                   && memcmp (prologue + vpc + 4, img, sizeof (img)) == 0)
  474.                 {
  475.                   info->prologue_type = AVR_PROLOGUE_MAIN;
  476.                   info->base = locals;
  477.                   return pc_beg + 4;
  478.                 }
  479.             }
  480.         }
  481.     }

  482.   /* Scanning `-mcall-prologues' prologue
  483.      Classic prologue is 10 bytes, mega prologue is a 12 bytes long */

  484.   while (1)        /* Using a while to avoid many goto's */
  485.     {
  486.       int loc_size;
  487.       int body_addr;
  488.       unsigned num_pushes;
  489.       int pc_offset = 0;

  490.       /* At least the fifth instruction must have been executed to
  491.          modify frame shape.  */
  492.       if (len < 10)
  493.         break;

  494.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  495.       /* ldi r26,<LOCALS_SIZE> */
  496.       if ((insn & 0xf0f0) != 0xe0a0)
  497.         break;
  498.       loc_size = (insn & 0xf) | ((insn & 0x0f00) >> 4);
  499.       pc_offset += 2;

  500.       insn = extract_unsigned_integer (&prologue[vpc + 2], 2, byte_order);
  501.       /* ldi r27,<LOCALS_SIZE> / 256 */
  502.       if ((insn & 0xf0f0) != 0xe0b0)
  503.         break;
  504.       loc_size |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
  505.       pc_offset += 2;

  506.       insn = extract_unsigned_integer (&prologue[vpc + 4], 2, byte_order);
  507.       /* ldi r30,pm_lo8(.L_foo_body) */
  508.       if ((insn & 0xf0f0) != 0xe0e0)
  509.         break;
  510.       body_addr = (insn & 0xf) | ((insn & 0x0f00) >> 4);
  511.       pc_offset += 2;

  512.       insn = extract_unsigned_integer (&prologue[vpc + 6], 2, byte_order);
  513.       /* ldi r31,pm_hi8(.L_foo_body) */
  514.       if ((insn & 0xf0f0) != 0xe0f0)
  515.         break;
  516.       body_addr |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
  517.       pc_offset += 2;

  518.       msymbol = lookup_minimal_symbol ("__prologue_saves__", NULL, NULL);
  519.       if (!msymbol.minsym)
  520.         break;

  521.       insn = extract_unsigned_integer (&prologue[vpc + 8], 2, byte_order);
  522.       /* rjmp __prologue_saves__+RRR */
  523.       if ((insn & 0xf000) == 0xc000)
  524.         {
  525.           /* Extract PC relative offset from RJMP */
  526.           i = (insn & 0xfff) | (insn & 0x800 ? (-1 ^ 0xfff) : 0);
  527.           /* Convert offset to byte addressable mode */
  528.           i *= 2;
  529.           /* Destination address */
  530.           i += pc_beg + 10;

  531.           if (body_addr != (pc_beg + 10)/2)
  532.             break;

  533.           pc_offset += 2;
  534.         }
  535.       else if ((insn & 0xfe0e) == 0x940c)
  536.         {
  537.           /* Extract absolute PC address from JMP */
  538.           i = (((insn & 0x1) | ((insn & 0x1f0) >> 3) << 16)
  539.                | (extract_unsigned_integer (&prologue[vpc + 10], 2, byte_order)
  540.                   & 0xffff));
  541.           /* Convert address to byte addressable mode */
  542.           i *= 2;

  543.           if (body_addr != (pc_beg + 12)/2)
  544.             break;

  545.           pc_offset += 4;
  546.         }
  547.       else
  548.         break;

  549.       /* Resolve offset (in words) from __prologue_saves__ symbol.
  550.          Which is a pushes count in `-mcall-prologues' mode */
  551.       num_pushes = AVR_MAX_PUSHES - (i - BMSYMBOL_VALUE_ADDRESS (msymbol)) / 2;

  552.       if (num_pushes > AVR_MAX_PUSHES)
  553.         {
  554.           fprintf_unfiltered (gdb_stderr, _("Num pushes too large: %d\n"),
  555.                               num_pushes);
  556.           num_pushes = 0;
  557.         }

  558.       if (num_pushes)
  559.         {
  560.           int from;

  561.           info->saved_regs[AVR_FP_REGNUM + 1].addr = num_pushes;
  562.           if (num_pushes >= 2)
  563.             info->saved_regs[AVR_FP_REGNUM].addr = num_pushes - 1;

  564.           i = 0;
  565.           for (from = AVR_LAST_PUSHED_REGNUM + 1 - (num_pushes - 2);
  566.                from <= AVR_LAST_PUSHED_REGNUM; ++from)
  567.             info->saved_regs [from].addr = ++i;
  568.         }
  569.       info->size = loc_size + num_pushes;
  570.       info->prologue_type = AVR_PROLOGUE_CALL;

  571.       return pc_beg + pc_offset;
  572.     }

  573.   /* Scan for the beginning of the prologue for an interrupt or signal
  574.      function.  Note that we have to set the prologue type here since the
  575.      third stage of the prologue may not be present (e.g. no saved registered
  576.      or changing of the SP register).  */

  577.   if (1)
  578.     {
  579.       static const unsigned char img[] = {
  580.         0x78, 0x94,                /* sei */
  581.         0x1f, 0x92,                /* push r1 */
  582.         0x0f, 0x92,                /* push r0 */
  583.         0x0f, 0xb6,                /* in r0,0x3f SREG */
  584.         0x0f, 0x92,                /* push r0 */
  585.         0x11, 0x24                /* clr r1 */
  586.       };
  587.       if (len >= sizeof (img)
  588.           && memcmp (prologue, img, sizeof (img)) == 0)
  589.         {
  590.           info->prologue_type = AVR_PROLOGUE_INTR;
  591.           vpc += sizeof (img);
  592.           info->saved_regs[AVR_SREG_REGNUM].addr = 3;
  593.           info->saved_regs[0].addr = 2;
  594.           info->saved_regs[1].addr = 1;
  595.           info->size += 3;
  596.         }
  597.       else if (len >= sizeof (img) - 2
  598.                && memcmp (img + 2, prologue, sizeof (img) - 2) == 0)
  599.         {
  600.           info->prologue_type = AVR_PROLOGUE_SIG;
  601.           vpc += sizeof (img) - 2;
  602.           info->saved_regs[AVR_SREG_REGNUM].addr = 3;
  603.           info->saved_regs[0].addr = 2;
  604.           info->saved_regs[1].addr = 1;
  605.           info->size += 2;
  606.         }
  607.     }

  608.   /* First stage of the prologue scanning.
  609.      Scan pushes (saved registers) */

  610.   for (; vpc < len; vpc += 2)
  611.     {
  612.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  613.       if ((insn & 0xfe0f) == 0x920f)        /* push rXX */
  614.         {
  615.           /* Bits 4-9 contain a mask for registers R0-R32.  */
  616.           int regno = (insn & 0x1f0) >> 4;
  617.           info->size++;
  618.           info->saved_regs[regno].addr = info->size;
  619.           scan_stage = 1;
  620.         }
  621.       else
  622.         break;
  623.     }

  624.   gdb_assert (vpc < AVR_MAX_PROLOGUE_SIZE);

  625.   /* Handle static small stack allocation using rcall or push.  */

  626.   while (scan_stage == 1 && vpc < len)
  627.     {
  628.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  629.       if (insn == 0xd000)        /* rcall .+0 */
  630.         {
  631.           info->size += gdbarch_tdep (gdbarch)->call_length;
  632.           vpc += 2;
  633.         }
  634.       else if (insn == 0x920f || insn == 0x921f/* push r0 or push r1 */
  635.         {
  636.           info->size += 1;
  637.           vpc += 2;
  638.         }
  639.       else
  640.         break;
  641.     }

  642.   /* Second stage of the prologue scanning.
  643.      Scan:
  644.      in r28,__SP_L__
  645.      in r29,__SP_H__ */

  646.   if (scan_stage == 1 && vpc < len)
  647.     {
  648.       static const unsigned char img[] = {
  649.         0xcd, 0xb7,                /* in r28,__SP_L__ */
  650.         0xde, 0xb7                /* in r29,__SP_H__ */
  651.       };

  652.       if (vpc + sizeof (img) < len
  653.           && memcmp (prologue + vpc, img, sizeof (img)) == 0)
  654.         {
  655.           vpc += 4;
  656.           scan_stage = 2;
  657.         }
  658.     }

  659.   /* Third stage of the prologue scanning.  (Really two stages).
  660.      Scan for:
  661.      sbiw r28,XX or subi r28,lo8(XX)
  662.                     sbci r29,hi8(XX)
  663.      in __tmp_reg__,__SREG__
  664.      cli
  665.      out __SP_H__,r29
  666.      out __SREG__,__tmp_reg__
  667.      out __SP_L__,r28 */

  668.   if (scan_stage == 2 && vpc < len)
  669.     {
  670.       int locals_size = 0;
  671.       static const unsigned char img[] = {
  672.         0x0f, 0xb6,                /* in r0,0x3f */
  673.         0xf8, 0x94,                /* cli */
  674.         0xde, 0xbf,                /* out 0x3e,r29 ; SPH */
  675.         0x0f, 0xbe,                /* out 0x3f,r0  ; SREG */
  676.         0xcd, 0xbf                /* out 0x3d,r28 ; SPL */
  677.       };
  678.       static const unsigned char img_sig[] = {
  679.         0xde, 0xbf,                /* out 0x3e,r29 ; SPH */
  680.         0xcd, 0xbf                /* out 0x3d,r28 ; SPL */
  681.       };
  682.       static const unsigned char img_int[] = {
  683.         0xf8, 0x94,                /* cli */
  684.         0xde, 0xbf,                /* out 0x3e,r29 ; SPH */
  685.         0x78, 0x94,                /* sei */
  686.         0xcd, 0xbf                /* out 0x3d,r28 ; SPL */
  687.       };

  688.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  689.       if ((insn & 0xff30) == 0x9720)        /* sbiw r28,XXX */
  690.         {
  691.           locals_size = (insn & 0xf) | ((insn & 0xc0) >> 2);
  692.           vpc += 2;
  693.         }
  694.       else if ((insn & 0xf0f0) == 0x50c0)        /* subi r28,lo8(XX) */
  695.         {
  696.           locals_size = (insn & 0xf) | ((insn & 0xf00) >> 4);
  697.           vpc += 2;
  698.           insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  699.           vpc += 2;
  700.           locals_size += ((insn & 0xf) | ((insn & 0xf00) >> 4)) << 8;
  701.         }
  702.       else
  703.         return pc_beg + vpc;

  704.       /* Scan the last part of the prologue.  May not be present for interrupt
  705.          or signal handler functions, which is why we set the prologue type
  706.          when we saw the beginning of the prologue previously.  */

  707.       if (vpc + sizeof (img_sig) < len
  708.           && memcmp (prologue + vpc, img_sig, sizeof (img_sig)) == 0)
  709.         {
  710.           vpc += sizeof (img_sig);
  711.         }
  712.       else if (vpc + sizeof (img_int) < len
  713.                && memcmp (prologue + vpc, img_int, sizeof (img_int)) == 0)
  714.         {
  715.           vpc += sizeof (img_int);
  716.         }
  717.       if (vpc + sizeof (img) < len
  718.           && memcmp (prologue + vpc, img, sizeof (img)) == 0)
  719.         {
  720.           info->prologue_type = AVR_PROLOGUE_NORMAL;
  721.           vpc += sizeof (img);
  722.         }

  723.       info->size += locals_size;

  724.       /* Fall through.  */
  725.     }

  726.   /* If we got this far, we could not scan the prologue, so just return the pc
  727.      of the frame plus an adjustment for argument move insns.  */

  728.   for (; vpc < len; vpc += 2)
  729.     {
  730.       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
  731.       if ((insn & 0xff00) == 0x0100)        /* movw rXX, rYY */
  732.         continue;
  733.       else if ((insn & 0xfc00) == 0x2c00) /* mov rXX, rYY */
  734.         continue;
  735.       else
  736.           break;
  737.     }

  738.   return pc_beg + vpc;
  739. }

  740. static CORE_ADDR
  741. avr_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
  742. {
  743.   CORE_ADDR func_addr, func_end;
  744.   CORE_ADDR post_prologue_pc;

  745.   /* See what the symbol table says */

  746.   if (!find_pc_partial_function (pc, NULL, &func_addr, &func_end))
  747.     return pc;

  748.   post_prologue_pc = skip_prologue_using_sal (gdbarch, func_addr);
  749.   if (post_prologue_pc != 0)
  750.     return max (pc, post_prologue_pc);

  751.   {
  752.     CORE_ADDR prologue_end = pc;
  753.     struct avr_unwind_cache info = {0};
  754.     struct trad_frame_saved_reg saved_regs[AVR_NUM_REGS];

  755.     info.saved_regs = saved_regs;

  756.     /* Need to run the prologue scanner to figure out if the function has a
  757.        prologue and possibly skip over moving arguments passed via registers
  758.        to other registers.  */

  759.     prologue_end = avr_scan_prologue (gdbarch, func_addr, func_end, &info);

  760.     if (info.prologue_type != AVR_PROLOGUE_NONE)
  761.       return prologue_end;
  762.   }

  763.   /* Either we didn't find the start of this function (nothing we can do),
  764.      or there's no line info, or the line after the prologue is after
  765.      the end of the function (there probably isn't a prologue).  */

  766.   return pc;
  767. }

  768. /* Not all avr devices support the BREAK insn.  Those that don't should treat
  769.    it as a NOP.  Thus, it should be ok.  Since the avr is currently a remote
  770.    only target, this shouldn't be a problem (I hope).  TRoth/2003-05-14  */

  771. static const unsigned char *
  772. avr_breakpoint_from_pc (struct gdbarch *gdbarch,
  773.                         CORE_ADDR *pcptr, int *lenptr)
  774. {
  775.     static const unsigned char avr_break_insn [] = { 0x98, 0x95 };
  776.     *lenptr = sizeof (avr_break_insn);
  777.     return avr_break_insn;
  778. }

  779. /* Determine, for architecture GDBARCH, how a return value of TYPE
  780.    should be returned.  If it is supposed to be returned in registers,
  781.    and READBUF is non-zero, read the appropriate value from REGCACHE,
  782.    and copy it into READBUF.  If WRITEBUF is non-zero, write the value
  783.    from WRITEBUF into REGCACHE.  */

  784. static enum return_value_convention
  785. avr_return_value (struct gdbarch *gdbarch, struct value *function,
  786.                   struct type *valtype, struct regcache *regcache,
  787.                   gdb_byte *readbuf, const gdb_byte *writebuf)
  788. {
  789.   int i;
  790.   /* Single byte are returned in r24.
  791.      Otherwise, the MSB of the return value is always in r25, calculate which
  792.      register holds the LSB.  */
  793.   int lsb_reg;

  794.   if ((TYPE_CODE (valtype) == TYPE_CODE_STRUCT
  795.        || TYPE_CODE (valtype) == TYPE_CODE_UNION
  796.        || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
  797.       && TYPE_LENGTH (valtype) > 8)
  798.     return RETURN_VALUE_STRUCT_CONVENTION;

  799.   if (TYPE_LENGTH (valtype) <= 2)
  800.     lsb_reg = 24;
  801.   else if (TYPE_LENGTH (valtype) <= 4)
  802.     lsb_reg = 22;
  803.   else if (TYPE_LENGTH (valtype) <= 8)
  804.     lsb_reg = 18;
  805.   else
  806.     gdb_assert_not_reached ("unexpected type length");

  807.   if (writebuf != NULL)
  808.     {
  809.       for (i = 0; i < TYPE_LENGTH (valtype); i++)
  810.         regcache_cooked_write (regcache, lsb_reg + i, writebuf + i);
  811.     }

  812.   if (readbuf != NULL)
  813.     {
  814.       for (i = 0; i < TYPE_LENGTH (valtype); i++)
  815.         regcache_cooked_read (regcache, lsb_reg + i, readbuf + i);
  816.     }

  817.   return RETURN_VALUE_REGISTER_CONVENTION;
  818. }


  819. /* Put here the code to store, into fi->saved_regs, the addresses of
  820.    the saved registers of frame described by FRAME_INFO.  This
  821.    includes special registers such as pc and fp saved in special ways
  822.    in the stack frame.  sp is even more special: the address we return
  823.    for it IS the sp for the next frame.  */

  824. static struct avr_unwind_cache *
  825. avr_frame_unwind_cache (struct frame_info *this_frame,
  826.                         void **this_prologue_cache)
  827. {
  828.   CORE_ADDR start_pc, current_pc;
  829.   ULONGEST prev_sp;
  830.   ULONGEST this_base;
  831.   struct avr_unwind_cache *info;
  832.   struct gdbarch *gdbarch;
  833.   struct gdbarch_tdep *tdep;
  834.   int i;

  835.   if (*this_prologue_cache)
  836.     return *this_prologue_cache;

  837.   info = FRAME_OBSTACK_ZALLOC (struct avr_unwind_cache);
  838.   *this_prologue_cache = info;
  839.   info->saved_regs = trad_frame_alloc_saved_regs (this_frame);

  840.   info->size = 0;
  841.   info->prologue_type = AVR_PROLOGUE_NONE;

  842.   start_pc = get_frame_func (this_frame);
  843.   current_pc = get_frame_pc (this_frame);
  844.   if ((start_pc > 0) && (start_pc <= current_pc))
  845.     avr_scan_prologue (get_frame_arch (this_frame),
  846.                        start_pc, current_pc, info);

  847.   if ((info->prologue_type != AVR_PROLOGUE_NONE)
  848.       && (info->prologue_type != AVR_PROLOGUE_MAIN))
  849.     {
  850.       ULONGEST high_base;       /* High byte of FP */

  851.       /* The SP was moved to the FP.  This indicates that a new frame
  852.          was created.  Get THIS frame's FP value by unwinding it from
  853.          the next frame.  */
  854.       this_base = get_frame_register_unsigned (this_frame, AVR_FP_REGNUM);
  855.       high_base = get_frame_register_unsigned (this_frame, AVR_FP_REGNUM + 1);
  856.       this_base += (high_base << 8);

  857.       /* The FP points at the last saved register.  Adjust the FP back
  858.          to before the first saved register giving the SP.  */
  859.       prev_sp = this_base + info->size;
  860.    }
  861.   else
  862.     {
  863.       /* Assume that the FP is this frame's SP but with that pushed
  864.          stack space added back.  */
  865.       this_base = get_frame_register_unsigned (this_frame, AVR_SP_REGNUM);
  866.       prev_sp = this_base + info->size;
  867.     }

  868.   /* Add 1 here to adjust for the post-decrement nature of the push
  869.      instruction.*/
  870.   info->prev_sp = avr_make_saddr (prev_sp + 1);
  871.   info->base = avr_make_saddr (this_base);

  872.   gdbarch = get_frame_arch (this_frame);

  873.   /* Adjust all the saved registers so that they contain addresses and not
  874.      offsets.  */
  875.   for (i = 0; i < gdbarch_num_regs (gdbarch) - 1; i++)
  876.     if (info->saved_regs[i].addr > 0)
  877.       info->saved_regs[i].addr = info->prev_sp - info->saved_regs[i].addr;

  878.   /* Except for the main and startup code, the return PC is always saved on
  879.      the stack and is at the base of the frame.  */

  880.   if (info->prologue_type != AVR_PROLOGUE_MAIN)
  881.     info->saved_regs[AVR_PC_REGNUM].addr = info->prev_sp;

  882.   /* The previous frame's SP needed to be computed.  Save the computed
  883.      value.  */
  884.   tdep = gdbarch_tdep (gdbarch);
  885.   trad_frame_set_value (info->saved_regs, AVR_SP_REGNUM,
  886.                         info->prev_sp - 1 + tdep->call_length);

  887.   return info;
  888. }

  889. static CORE_ADDR
  890. avr_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
  891. {
  892.   ULONGEST pc;

  893.   pc = frame_unwind_register_unsigned (next_frame, AVR_PC_REGNUM);

  894.   return avr_make_iaddr (pc);
  895. }

  896. static CORE_ADDR
  897. avr_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
  898. {
  899.   ULONGEST sp;

  900.   sp = frame_unwind_register_unsigned (next_frame, AVR_SP_REGNUM);

  901.   return avr_make_saddr (sp);
  902. }

  903. /* Given a GDB frame, determine the address of the calling function's
  904.    frame.  This will be used to create a new GDB frame struct.  */

  905. static void
  906. avr_frame_this_id (struct frame_info *this_frame,
  907.                    void **this_prologue_cache,
  908.                    struct frame_id *this_id)
  909. {
  910.   struct avr_unwind_cache *info
  911.     = avr_frame_unwind_cache (this_frame, this_prologue_cache);
  912.   CORE_ADDR base;
  913.   CORE_ADDR func;
  914.   struct frame_id id;

  915.   /* The FUNC is easy.  */
  916.   func = get_frame_func (this_frame);

  917.   /* Hopefully the prologue analysis either correctly determined the
  918.      frame's base (which is the SP from the previous frame), or set
  919.      that base to "NULL".  */
  920.   base = info->prev_sp;
  921.   if (base == 0)
  922.     return;

  923.   id = frame_id_build (base, func);
  924.   (*this_id) = id;
  925. }

  926. static struct value *
  927. avr_frame_prev_register (struct frame_info *this_frame,
  928.                          void **this_prologue_cache, int regnum)
  929. {
  930.   struct gdbarch *gdbarch = get_frame_arch (this_frame);
  931.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  932.   struct avr_unwind_cache *info
  933.     = avr_frame_unwind_cache (this_frame, this_prologue_cache);

  934.   if (regnum == AVR_PC_REGNUM || regnum == AVR_PSEUDO_PC_REGNUM)
  935.     {
  936.       if (trad_frame_addr_p (info->saved_regs, AVR_PC_REGNUM))
  937.         {
  938.           /* Reading the return PC from the PC register is slightly
  939.              abnormal.  register_size(AVR_PC_REGNUM) says it is 4 bytes,
  940.              but in reality, only two bytes (3 in upcoming mega256) are
  941.              stored on the stack.

  942.              Also, note that the value on the stack is an addr to a word
  943.              not a byte, so we will need to multiply it by two at some
  944.              point.

  945.              And to confuse matters even more, the return address stored
  946.              on the stack is in big endian byte order, even though most
  947.              everything else about the avr is little endian.  Ick!  */
  948.           ULONGEST pc;
  949.           int i;
  950.           gdb_byte buf[3];
  951.           struct gdbarch *gdbarch = get_frame_arch (this_frame);
  952.           struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);

  953.           read_memory (info->saved_regs[AVR_PC_REGNUM].addr,
  954.                        buf, tdep->call_length);

  955.           /* Extract the PC read from memory as a big-endian.  */
  956.           pc = 0;
  957.           for (i = 0; i < tdep->call_length; i++)
  958.             pc = (pc << 8) | buf[i];

  959.           if (regnum == AVR_PC_REGNUM)
  960.             pc <<= 1;

  961.           return frame_unwind_got_constant (this_frame, regnum, pc);
  962.         }

  963.       return frame_unwind_got_optimized (this_frame, regnum);
  964.     }

  965.   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
  966. }

  967. static const struct frame_unwind avr_frame_unwind = {
  968.   NORMAL_FRAME,
  969.   default_frame_unwind_stop_reason,
  970.   avr_frame_this_id,
  971.   avr_frame_prev_register,
  972.   NULL,
  973.   default_frame_sniffer
  974. };

  975. static CORE_ADDR
  976. avr_frame_base_address (struct frame_info *this_frame, void **this_cache)
  977. {
  978.   struct avr_unwind_cache *info
  979.     = avr_frame_unwind_cache (this_frame, this_cache);

  980.   return info->base;
  981. }

  982. static const struct frame_base avr_frame_base = {
  983.   &avr_frame_unwind,
  984.   avr_frame_base_address,
  985.   avr_frame_base_address,
  986.   avr_frame_base_address
  987. };

  988. /* Assuming THIS_FRAME is a dummy, return the frame ID of that dummy
  989.    frame.  The frame ID's base needs to match the TOS value saved by
  990.    save_dummy_frame_tos(), and the PC match the dummy frame's breakpoint.  */

  991. static struct frame_id
  992. avr_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
  993. {
  994.   ULONGEST base;

  995.   base = get_frame_register_unsigned (this_frame, AVR_SP_REGNUM);
  996.   return frame_id_build (avr_make_saddr (base), get_frame_pc (this_frame));
  997. }

  998. /* When arguments must be pushed onto the stack, they go on in reverse
  999.    order.  The below implements a FILO (stack) to do this.  */

  1000. struct stack_item
  1001. {
  1002.   int len;
  1003.   struct stack_item *prev;
  1004.   void *data;
  1005. };

  1006. static struct stack_item *
  1007. push_stack_item (struct stack_item *prev, const bfd_byte *contents, int len)
  1008. {
  1009.   struct stack_item *si;
  1010.   si = xmalloc (sizeof (struct stack_item));
  1011.   si->data = xmalloc (len);
  1012.   si->len = len;
  1013.   si->prev = prev;
  1014.   memcpy (si->data, contents, len);
  1015.   return si;
  1016. }

  1017. static struct stack_item *pop_stack_item (struct stack_item *si);
  1018. static struct stack_item *
  1019. pop_stack_item (struct stack_item *si)
  1020. {
  1021.   struct stack_item *dead = si;
  1022.   si = si->prev;
  1023.   xfree (dead->data);
  1024.   xfree (dead);
  1025.   return si;
  1026. }

  1027. /* Setup the function arguments for calling a function in the inferior.

  1028.    On the AVR architecture, there are 18 registers (R25 to R8) which are
  1029.    dedicated for passing function arguments.  Up to the first 18 arguments
  1030.    (depending on size) may go into these registers.  The rest go on the stack.

  1031.    All arguments are aligned to start in even-numbered registers (odd-sized
  1032.    arguments, including char, have one free register above them).  For example,
  1033.    an int in arg1 and a char in arg2 would be passed as such:

  1034.       arg1 -> r25:r24
  1035.       arg2 -> r22

  1036.    Arguments that are larger than 2 bytes will be split between two or more
  1037.    registers as available, but will NOT be split between a register and the
  1038.    stack.  Arguments that go onto the stack are pushed last arg first (this is
  1039.    similar to the d10v).  */

  1040. /* NOTE: TRoth/2003-06-17: The rest of this comment is old looks to be
  1041.    inaccurate.

  1042.    An exceptional case exists for struct arguments (and possibly other
  1043.    aggregates such as arrays) -- if the size is larger than WORDSIZE bytes but
  1044.    not a multiple of WORDSIZE bytes.  In this case the argument is never split
  1045.    between the registers and the stack, but instead is copied in its entirety
  1046.    onto the stack, AND also copied into as many registers as there is room
  1047.    for.  In other words, space in registers permitting, two copies of the same
  1048.    argument are passed in.  As far as I can tell, only the one on the stack is
  1049.    used, although that may be a function of the level of compiler
  1050.    optimization.  I suspect this is a compiler bug.  Arguments of these odd
  1051.    sizes are left-justified within the word (as opposed to arguments smaller
  1052.    than WORDSIZE bytes, which are right-justified).

  1053.    If the function is to return an aggregate type such as a struct, the caller
  1054.    must allocate space into which the callee will copy the return value.  In
  1055.    this case, a pointer to the return value location is passed into the callee
  1056.    in register R0, which displaces one of the other arguments passed in via
  1057.    registers R0 to R2.  */

  1058. static CORE_ADDR
  1059. avr_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
  1060.                      struct regcache *regcache, CORE_ADDR bp_addr,
  1061.                      int nargs, struct value **args, CORE_ADDR sp,
  1062.                      int struct_return, CORE_ADDR struct_addr)
  1063. {
  1064.   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
  1065.   int i;
  1066.   gdb_byte buf[3];
  1067.   int call_length = gdbarch_tdep (gdbarch)->call_length;
  1068.   CORE_ADDR return_pc = avr_convert_iaddr_to_raw (bp_addr);
  1069.   int regnum = AVR_ARGN_REGNUM;
  1070.   struct stack_item *si = NULL;

  1071.   if (struct_return)
  1072.     {
  1073.       regcache_cooked_write_unsigned
  1074.         (regcache, regnum--, (struct_addr >> 8) & 0xff);
  1075.       regcache_cooked_write_unsigned
  1076.         (regcache, regnum--, struct_addr & 0xff);
  1077.       /* SP being post decremented, we need to reserve one byte so that the
  1078.          return address won't overwrite the result (or vice-versa).  */
  1079.       if (sp == struct_addr)
  1080.         sp--;
  1081.     }

  1082.   for (i = 0; i < nargs; i++)
  1083.     {
  1084.       int last_regnum;
  1085.       int j;
  1086.       struct value *arg = args[i];
  1087.       struct type *type = check_typedef (value_type (arg));
  1088.       const bfd_byte *contents = value_contents (arg);
  1089.       int len = TYPE_LENGTH (type);

  1090.       /* Calculate the potential last register needed.  */
  1091.       last_regnum = regnum - (len + (len & 1));

  1092.       /* If there are registers available, use them.  Once we start putting
  1093.          stuff on the stack, all subsequent args go on stack.  */
  1094.       if ((si == NULL) && (last_regnum >= 8))
  1095.         {
  1096.           ULONGEST val;

  1097.           /* Skip a register for odd length args.  */
  1098.           if (len & 1)
  1099.             regnum--;

  1100.           val = extract_unsigned_integer (contents, len, byte_order);
  1101.           for (j = 0; j < len; j++)
  1102.             regcache_cooked_write_unsigned
  1103.               (regcache, regnum--, val >> (8 * (len - j - 1)));
  1104.         }
  1105.       /* No registers available, push the args onto the stack.  */
  1106.       else
  1107.         {
  1108.           /* From here on, we don't care about regnum.  */
  1109.           si = push_stack_item (si, contents, len);
  1110.         }
  1111.     }

  1112.   /* Push args onto the stack.  */
  1113.   while (si)
  1114.     {
  1115.       sp -= si->len;
  1116.       /* Add 1 to sp here to account for post decr nature of pushes.  */
  1117.       write_memory (sp + 1, si->data, si->len);
  1118.       si = pop_stack_item (si);
  1119.     }

  1120.   /* Set the return address.  For the avr, the return address is the BP_ADDR.
  1121.      Need to push the return address onto the stack noting that it needs to be
  1122.      in big-endian order on the stack.  */
  1123.   for (i = 1; i <= call_length; i++)
  1124.     {
  1125.       buf[call_length - i] = return_pc & 0xff;
  1126.       return_pc >>= 8;
  1127.     }

  1128.   sp -= call_length;
  1129.   /* Use 'sp + 1' since pushes are post decr ops.  */
  1130.   write_memory (sp + 1, buf, call_length);

  1131.   /* Finally, update the SP register.  */
  1132.   regcache_cooked_write_unsigned (regcache, AVR_SP_REGNUM,
  1133.                                   avr_convert_saddr_to_raw (sp));

  1134.   /* Return SP value for the dummy frame, where the return address hasn't been
  1135.      pushed.  */
  1136.   return sp + call_length;
  1137. }

  1138. /* Unfortunately dwarf2 register for SP is 32.  */

  1139. static int
  1140. avr_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
  1141. {
  1142.   if (reg >= 0 && reg < 32)
  1143.     return reg;
  1144.   if (reg == 32)
  1145.     return AVR_SP_REGNUM;

  1146.   warning (_("Unmapped DWARF Register #%d encountered."), reg);

  1147.   return -1;
  1148. }

  1149. /* Implementation of `address_class_type_flags' gdbarch method.

  1150.    This method maps DW_AT_address_class attributes to a
  1151.    type_instance_flag_value.  */

  1152. static int
  1153. avr_address_class_type_flags (int byte_size, int dwarf2_addr_class)
  1154. {
  1155.   /* The value 1 of the DW_AT_address_class attribute corresponds to the
  1156.      __flash qualifier.  Note that this attribute is only valid with
  1157.      pointer types and therefore the flag is set to the pointer type and
  1158.      not its target type.  */
  1159.   if (dwarf2_addr_class == 1 && byte_size == 2)
  1160.     return AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH;
  1161.   return 0;
  1162. }

  1163. /* Implementation of `address_class_type_flags_to_name' gdbarch method.

  1164.    Convert a type_instance_flag_value to an address space qualifier.  */

  1165. static const char*
  1166. avr_address_class_type_flags_to_name (struct gdbarch *gdbarch, int type_flags)
  1167. {
  1168.   if (type_flags & AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH)
  1169.     return "flash";
  1170.   else
  1171.     return NULL;
  1172. }

  1173. /* Implementation of `address_class_name_to_type_flags' gdbarch method.

  1174.    Convert an address space qualifier to a type_instance_flag_value.  */

  1175. static int
  1176. avr_address_class_name_to_type_flags (struct gdbarch *gdbarch,
  1177.                                       const char* name,
  1178.                                       int *type_flags_ptr)
  1179. {
  1180.   if (strcmp (name, "flash") == 0)
  1181.     {
  1182.       *type_flags_ptr = AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH;
  1183.       return 1;
  1184.     }
  1185.   else
  1186.     return 0;
  1187. }

  1188. /* Initialize the gdbarch structure for the AVR's.  */

  1189. static struct gdbarch *
  1190. avr_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
  1191. {
  1192.   struct gdbarch *gdbarch;
  1193.   struct gdbarch_tdep *tdep;
  1194.   struct gdbarch_list *best_arch;
  1195.   int call_length;

  1196.   /* Avr-6 call instructions save 3 bytes.  */
  1197.   switch (info.bfd_arch_info->mach)
  1198.     {
  1199.     case bfd_mach_avr1:
  1200.     case bfd_mach_avrxmega1:
  1201.     case bfd_mach_avr2:
  1202.     case bfd_mach_avrxmega2:
  1203.     case bfd_mach_avr3:
  1204.     case bfd_mach_avrxmega3:
  1205.     case bfd_mach_avr4:
  1206.     case bfd_mach_avrxmega4:
  1207.     case bfd_mach_avr5:
  1208.     case bfd_mach_avrxmega5:
  1209.     default:
  1210.       call_length = 2;
  1211.       break;
  1212.     case bfd_mach_avr6:
  1213.     case bfd_mach_avrxmega6:
  1214.     case bfd_mach_avrxmega7:
  1215.       call_length = 3;
  1216.       break;
  1217.     }

  1218.   /* If there is already a candidate, use it.  */
  1219.   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
  1220.        best_arch != NULL;
  1221.        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
  1222.     {
  1223.       if (gdbarch_tdep (best_arch->gdbarch)->call_length == call_length)
  1224.         return best_arch->gdbarch;
  1225.     }

  1226.   /* None found, create a new architecture from the information provided.  */
  1227.   tdep = XNEW (struct gdbarch_tdep);
  1228.   gdbarch = gdbarch_alloc (&info, tdep);

  1229.   tdep->call_length = call_length;

  1230.   /* Create a type for PC.  We can't use builtin types here, as they may not
  1231.      be defined.  */
  1232.   tdep->void_type = arch_type (gdbarch, TYPE_CODE_VOID, 1, "void");
  1233.   tdep->func_void_type = make_function_type (tdep->void_type, NULL);
  1234.   tdep->pc_type = arch_type (gdbarch, TYPE_CODE_PTR, 4, NULL);
  1235.   TYPE_TARGET_TYPE (tdep->pc_type) = tdep->func_void_type;
  1236.   TYPE_UNSIGNED (tdep->pc_type) = 1;

  1237.   set_gdbarch_short_bit (gdbarch, 2 * TARGET_CHAR_BIT);
  1238.   set_gdbarch_int_bit (gdbarch, 2 * TARGET_CHAR_BIT);
  1239.   set_gdbarch_long_bit (gdbarch, 4 * TARGET_CHAR_BIT);
  1240.   set_gdbarch_long_long_bit (gdbarch, 8 * TARGET_CHAR_BIT);
  1241.   set_gdbarch_ptr_bit (gdbarch, 2 * TARGET_CHAR_BIT);
  1242.   set_gdbarch_addr_bit (gdbarch, 32);

  1243.   set_gdbarch_float_bit (gdbarch, 4 * TARGET_CHAR_BIT);
  1244.   set_gdbarch_double_bit (gdbarch, 4 * TARGET_CHAR_BIT);
  1245.   set_gdbarch_long_double_bit (gdbarch, 4 * TARGET_CHAR_BIT);

  1246.   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
  1247.   set_gdbarch_double_format (gdbarch, floatformats_ieee_single);
  1248.   set_gdbarch_long_double_format (gdbarch, floatformats_ieee_single);

  1249.   set_gdbarch_read_pc (gdbarch, avr_read_pc);
  1250.   set_gdbarch_write_pc (gdbarch, avr_write_pc);

  1251.   set_gdbarch_num_regs (gdbarch, AVR_NUM_REGS);

  1252.   set_gdbarch_sp_regnum (gdbarch, AVR_SP_REGNUM);
  1253.   set_gdbarch_pc_regnum (gdbarch, AVR_PC_REGNUM);

  1254.   set_gdbarch_register_name (gdbarch, avr_register_name);
  1255.   set_gdbarch_register_type (gdbarch, avr_register_type);

  1256.   set_gdbarch_num_pseudo_regs (gdbarch, AVR_NUM_PSEUDO_REGS);
  1257.   set_gdbarch_pseudo_register_read (gdbarch, avr_pseudo_register_read);
  1258.   set_gdbarch_pseudo_register_write (gdbarch, avr_pseudo_register_write);

  1259.   set_gdbarch_return_value (gdbarch, avr_return_value);
  1260.   set_gdbarch_print_insn (gdbarch, print_insn_avr);

  1261.   set_gdbarch_push_dummy_call (gdbarch, avr_push_dummy_call);

  1262.   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, avr_dwarf_reg_to_regnum);

  1263.   set_gdbarch_address_to_pointer (gdbarch, avr_address_to_pointer);
  1264.   set_gdbarch_pointer_to_address (gdbarch, avr_pointer_to_address);
  1265.   set_gdbarch_integer_to_address (gdbarch, avr_integer_to_address);

  1266.   set_gdbarch_skip_prologue (gdbarch, avr_skip_prologue);
  1267.   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);

  1268.   set_gdbarch_breakpoint_from_pc (gdbarch, avr_breakpoint_from_pc);

  1269.   frame_unwind_append_unwinder (gdbarch, &avr_frame_unwind);
  1270.   frame_base_set_default (gdbarch, &avr_frame_base);

  1271.   set_gdbarch_dummy_id (gdbarch, avr_dummy_id);

  1272.   set_gdbarch_unwind_pc (gdbarch, avr_unwind_pc);
  1273.   set_gdbarch_unwind_sp (gdbarch, avr_unwind_sp);

  1274.   set_gdbarch_address_class_type_flags (gdbarch, avr_address_class_type_flags);
  1275.   set_gdbarch_address_class_name_to_type_flags
  1276.     (gdbarch, avr_address_class_name_to_type_flags);
  1277.   set_gdbarch_address_class_type_flags_to_name
  1278.     (gdbarch, avr_address_class_type_flags_to_name);

  1279.   return gdbarch;
  1280. }

  1281. /* Send a query request to the avr remote target asking for values of the io
  1282.    registers.  If args parameter is not NULL, then the user has requested info
  1283.    on a specific io register [This still needs implemented and is ignored for
  1284.    now].  The query string should be one of these forms:

  1285.    "Ravr.io_reg" -> reply is "NN" number of io registers

  1286.    "Ravr.io_reg:addr,len" where addr is first register and len is number of
  1287.    registers to be read.  The reply should be "<NAME>,VV;" for each io register
  1288.    where, <NAME> is a string, and VV is the hex value of the register.

  1289.    All io registers are 8-bit.  */

  1290. static void
  1291. avr_io_reg_read_command (char *args, int from_tty)
  1292. {
  1293.   LONGEST bufsiz = 0;
  1294.   gdb_byte *buf;
  1295.   const char *bufstr;
  1296.   char query[400];
  1297.   const char *p;
  1298.   unsigned int nreg = 0;
  1299.   unsigned int val;
  1300.   int i, j, k, step;

  1301.   /* Find out how many io registers the target has.  */
  1302.   bufsiz = target_read_alloc (&current_target, TARGET_OBJECT_AVR,
  1303.                               "avr.io_reg", &buf);
  1304.   bufstr = (const char *) buf;

  1305.   if (bufsiz <= 0)
  1306.     {
  1307.       fprintf_unfiltered (gdb_stderr,
  1308.                           _("ERR: info io_registers NOT supported "
  1309.                             "by current target\n"));
  1310.       return;
  1311.     }

  1312.   if (sscanf (bufstr, "%x", &nreg) != 1)
  1313.     {
  1314.       fprintf_unfiltered (gdb_stderr,
  1315.                           _("Error fetching number of io registers\n"));
  1316.       xfree (buf);
  1317.       return;
  1318.     }

  1319.   xfree (buf);

  1320.   reinitialize_more_filter ();

  1321.   printf_unfiltered (_("Target has %u io registers:\n\n"), nreg);

  1322.   /* only fetch up to 8 registers at a time to keep the buffer small */
  1323.   step = 8;

  1324.   for (i = 0; i < nreg; i += step)
  1325.     {
  1326.       /* how many registers this round? */
  1327.       j = step;
  1328.       if ((i+j) >= nreg)
  1329.         j = nreg - i;           /* last block is less than 8 registers */

  1330.       snprintf (query, sizeof (query) - 1, "avr.io_reg:%x,%x", i, j);
  1331.       bufsiz = target_read_alloc (&current_target, TARGET_OBJECT_AVR,
  1332.                                   query, &buf);

  1333.       p = (const char *) buf;
  1334.       for (k = i; k < (i + j); k++)
  1335.         {
  1336.           if (sscanf (p, "%[^,],%x;", query, &val) == 2)
  1337.             {
  1338.               printf_filtered ("[%02x] %-15s : %02x\n", k, query, val);
  1339.               while ((*p != ';') && (*p != '\0'))
  1340.                 p++;
  1341.               p++;                /* skip over ';' */
  1342.               if (*p == '\0')
  1343.                 break;
  1344.             }
  1345.         }

  1346.       xfree (buf);
  1347.     }
  1348. }

  1349. extern initialize_file_ftype _initialize_avr_tdep; /* -Wmissing-prototypes */

  1350. void
  1351. _initialize_avr_tdep (void)
  1352. {
  1353.   register_gdbarch_init (bfd_arch_avr, avr_gdbarch_init);

  1354.   /* Add a new command to allow the user to query the avr remote target for
  1355.      the values of the io space registers in a saner way than just using
  1356.      `x/NNNb ADDR`.  */

  1357.   /* FIXME: TRoth/2002-02-18: This should probably be changed to 'info avr
  1358.      io_registers' to signify it is not available on other platforms.  */

  1359.   add_cmd ("io_registers", class_info, avr_io_reg_read_command,
  1360.            _("query remote avr target for io space register values"),
  1361.            &infolist);
  1362. }