gdb: Use std::min and std::max throughout
[external/binutils.git] / gdb / avr-tdep.c
1 /* Target-dependent code for Atmel AVR, for GDB.
2
3    Copyright (C) 1996-2016 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 /* Contributed by Theodore A. Roth, troth@openavr.org */
21
22 /* Portions of this file were taken from the original gdb-4.18 patch developed
23    by Denis Chertykov, denisc@overta.ru */
24
25 #include "defs.h"
26 #include "frame.h"
27 #include "frame-unwind.h"
28 #include "frame-base.h"
29 #include "trad-frame.h"
30 #include "gdbcmd.h"
31 #include "gdbcore.h"
32 #include "gdbtypes.h"
33 #include "inferior.h"
34 #include "symfile.h"
35 #include "arch-utils.h"
36 #include "regcache.h"
37 #include "dis-asm.h"
38 #include "objfiles.h"
39 #include <algorithm>
40
41 /* AVR Background:
42
43    (AVR micros are pure Harvard Architecture processors.)
44
45    The AVR family of microcontrollers have three distinctly different memory
46    spaces: flash, sram and eeprom.  The flash is 16 bits wide and is used for
47    the most part to store program instructions.  The sram is 8 bits wide and is
48    used for the stack and the heap.  Some devices lack sram and some can have
49    an additional external sram added on as a peripheral.
50
51    The eeprom is 8 bits wide and is used to store data when the device is
52    powered down.  Eeprom is not directly accessible, it can only be accessed
53    via io-registers using a special algorithm.  Accessing eeprom via gdb's
54    remote serial protocol ('m' or 'M' packets) looks difficult to do and is
55    not included at this time.
56
57    [The eeprom could be read manually via ``x/b <eaddr + AVR_EMEM_START>'' or
58    written using ``set {unsigned char}<eaddr + AVR_EMEM_START>''.  For this to
59    work, the remote target must be able to handle eeprom accesses and perform
60    the address translation.]
61
62    All three memory spaces have physical addresses beginning at 0x0.  In
63    addition, the flash is addressed by gcc/binutils/gdb with respect to 8 bit
64    bytes instead of the 16 bit wide words used by the real device for the
65    Program Counter.
66
67    In order for remote targets to work correctly, extra bits must be added to
68    addresses before they are send to the target or received from the target
69    via the remote serial protocol.  The extra bits are the MSBs and are used to
70    decode which memory space the address is referring to.  */
71
72 /* Constants: prefixed with AVR_ to avoid name space clashes */
73
74 /* Address space flags */
75
76 /* We are assigning the TYPE_INSTANCE_FLAG_ADDRESS_CLASS_1 to the flash address
77    space.  */
78
79 #define AVR_TYPE_ADDRESS_CLASS_FLASH TYPE_ADDRESS_CLASS_1
80 #define AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH  \
81   TYPE_INSTANCE_FLAG_ADDRESS_CLASS_1
82
83
84 enum
85 {
86   AVR_REG_W = 24,
87   AVR_REG_X = 26,
88   AVR_REG_Y = 28,
89   AVR_FP_REGNUM = 28,
90   AVR_REG_Z = 30,
91
92   AVR_SREG_REGNUM = 32,
93   AVR_SP_REGNUM = 33,
94   AVR_PC_REGNUM = 34,
95
96   AVR_NUM_REGS = 32 + 1 /*SREG*/ + 1 /*SP*/ + 1 /*PC*/,
97   AVR_NUM_REG_BYTES = 32 + 1 /*SREG*/ + 2 /*SP*/ + 4 /*PC*/,
98
99   /* Pseudo registers.  */
100   AVR_PSEUDO_PC_REGNUM = 35,
101   AVR_NUM_PSEUDO_REGS = 1,
102
103   AVR_PC_REG_INDEX = 35,        /* index into array of registers */
104
105   AVR_MAX_PROLOGUE_SIZE = 64,   /* bytes */
106
107   /* Count of pushed registers.  From r2 to r17 (inclusively), r28, r29 */
108   AVR_MAX_PUSHES = 18,
109
110   /* Number of the last pushed register.  r17 for current avr-gcc */
111   AVR_LAST_PUSHED_REGNUM = 17,
112
113   AVR_ARG1_REGNUM = 24,         /* Single byte argument */
114   AVR_ARGN_REGNUM = 25,         /* Multi byte argments */
115   AVR_LAST_ARG_REGNUM = 8,      /* Last argument register */
116
117   AVR_RET1_REGNUM = 24,         /* Single byte return value */
118   AVR_RETN_REGNUM = 25,         /* Multi byte return value */
119
120   /* FIXME: TRoth/2002-01-??: Can we shift all these memory masks left 8
121      bits?  Do these have to match the bfd vma values?  It sure would make
122      things easier in the future if they didn't need to match.
123
124      Note: I chose these values so as to be consistent with bfd vma
125      addresses.
126
127      TRoth/2002-04-08: There is already a conflict with very large programs
128      in the mega128.  The mega128 has 128K instruction bytes (64K words),
129      thus the Most Significant Bit is 0x10000 which gets masked off my
130      AVR_MEM_MASK.
131
132      The problem manifests itself when trying to set a breakpoint in a
133      function which resides in the upper half of the instruction space and
134      thus requires a 17-bit address.
135
136      For now, I've just removed the EEPROM mask and changed AVR_MEM_MASK
137      from 0x00ff0000 to 0x00f00000.  Eeprom is not accessible from gdb yet,
138      but could be for some remote targets by just adding the correct offset
139      to the address and letting the remote target handle the low-level
140      details of actually accessing the eeprom.  */
141
142   AVR_IMEM_START = 0x00000000,  /* INSN memory */
143   AVR_SMEM_START = 0x00800000,  /* SRAM memory */
144 #if 1
145   /* No eeprom mask defined */
146   AVR_MEM_MASK = 0x00f00000,    /* mask to determine memory space */
147 #else
148   AVR_EMEM_START = 0x00810000,  /* EEPROM memory */
149   AVR_MEM_MASK = 0x00ff0000,    /* mask to determine memory space */
150 #endif
151 };
152
153 /* Prologue types:
154
155    NORMAL and CALL are the typical types (the -mcall-prologues gcc option
156    causes the generation of the CALL type prologues).  */
157
158 enum {
159     AVR_PROLOGUE_NONE,              /* No prologue */
160     AVR_PROLOGUE_NORMAL,
161     AVR_PROLOGUE_CALL,              /* -mcall-prologues */
162     AVR_PROLOGUE_MAIN,
163     AVR_PROLOGUE_INTR,              /* interrupt handler */
164     AVR_PROLOGUE_SIG,               /* signal handler */
165 };
166
167 /* Any function with a frame looks like this
168    .......    <-SP POINTS HERE
169    LOCALS1    <-FP POINTS HERE
170    LOCALS0
171    SAVED FP
172    SAVED R3
173    SAVED R2
174    RET PC
175    FIRST ARG
176    SECOND ARG */
177
178 struct avr_unwind_cache
179 {
180   /* The previous frame's inner most stack address.  Used as this
181      frame ID's stack_addr.  */
182   CORE_ADDR prev_sp;
183   /* The frame's base, optionally used by the high-level debug info.  */
184   CORE_ADDR base;
185   int size;
186   int prologue_type;
187   /* Table indicating the location of each and every register.  */
188   struct trad_frame_saved_reg *saved_regs;
189 };
190
191 struct gdbarch_tdep
192 {
193   /* Number of bytes stored to the stack by call instructions.
194      2 bytes for avr1-5 and avrxmega1-5, 3 bytes for avr6 and avrxmega6-7.  */
195   int call_length;
196
197   /* Type for void.  */
198   struct type *void_type;
199   /* Type for a function returning void.  */
200   struct type *func_void_type;
201   /* Type for a pointer to a function.  Used for the type of PC.  */
202   struct type *pc_type;
203 };
204
205 /* Lookup the name of a register given it's number.  */
206
207 static const char *
208 avr_register_name (struct gdbarch *gdbarch, int regnum)
209 {
210   static const char * const register_names[] = {
211     "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
212     "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
213     "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
214     "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
215     "SREG", "SP", "PC2",
216     "pc"
217   };
218   if (regnum < 0)
219     return NULL;
220   if (regnum >= (sizeof (register_names) / sizeof (*register_names)))
221     return NULL;
222   return register_names[regnum];
223 }
224
225 /* Return the GDB type object for the "standard" data type
226    of data in register N.  */
227
228 static struct type *
229 avr_register_type (struct gdbarch *gdbarch, int reg_nr)
230 {
231   if (reg_nr == AVR_PC_REGNUM)
232     return builtin_type (gdbarch)->builtin_uint32;
233   if (reg_nr == AVR_PSEUDO_PC_REGNUM)
234     return gdbarch_tdep (gdbarch)->pc_type;
235   if (reg_nr == AVR_SP_REGNUM)
236     return builtin_type (gdbarch)->builtin_data_ptr;
237   return builtin_type (gdbarch)->builtin_uint8;
238 }
239
240 /* Instruction address checks and convertions.  */
241
242 static CORE_ADDR
243 avr_make_iaddr (CORE_ADDR x)
244 {
245   return ((x) | AVR_IMEM_START);
246 }
247
248 /* FIXME: TRoth: Really need to use a larger mask for instructions.  Some
249    devices are already up to 128KBytes of flash space.
250
251    TRoth/2002-04-8: See comment above where AVR_IMEM_START is defined.  */
252
253 static CORE_ADDR
254 avr_convert_iaddr_to_raw (CORE_ADDR x)
255 {
256   return ((x) & 0xffffffff);
257 }
258
259 /* SRAM address checks and convertions.  */
260
261 static CORE_ADDR
262 avr_make_saddr (CORE_ADDR x)
263 {
264   /* Return 0 for NULL.  */
265   if (x == 0)
266     return 0;
267
268   return ((x) | AVR_SMEM_START);
269 }
270
271 static CORE_ADDR
272 avr_convert_saddr_to_raw (CORE_ADDR x)
273 {
274   return ((x) & 0xffffffff);
275 }
276
277 /* EEPROM address checks and convertions.  I don't know if these will ever
278    actually be used, but I've added them just the same.  TRoth */
279
280 /* TRoth/2002-04-08: Commented out for now to allow fix for problem with large
281    programs in the mega128.  */
282
283 /*  static CORE_ADDR */
284 /*  avr_make_eaddr (CORE_ADDR x) */
285 /*  { */
286 /*    return ((x) | AVR_EMEM_START); */
287 /*  } */
288
289 /*  static int */
290 /*  avr_eaddr_p (CORE_ADDR x) */
291 /*  { */
292 /*    return (((x) & AVR_MEM_MASK) == AVR_EMEM_START); */
293 /*  } */
294
295 /*  static CORE_ADDR */
296 /*  avr_convert_eaddr_to_raw (CORE_ADDR x) */
297 /*  { */
298 /*    return ((x) & 0xffffffff); */
299 /*  } */
300
301 /* Convert from address to pointer and vice-versa.  */
302
303 static void
304 avr_address_to_pointer (struct gdbarch *gdbarch,
305                         struct type *type, gdb_byte *buf, CORE_ADDR addr)
306 {
307   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
308
309   /* Is it a data address in flash?  */
310   if (AVR_TYPE_ADDRESS_CLASS_FLASH (type))
311     {
312       /* A data pointer in flash is byte addressed.  */
313       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
314                               avr_convert_iaddr_to_raw (addr));
315     }
316   /* Is it a code address?  */
317   else if (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC
318            || TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_METHOD)
319     {
320       /* A code pointer is word (16 bits) addressed.  We shift the address down
321          by 1 bit to convert it to a pointer.  */
322       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
323                               avr_convert_iaddr_to_raw (addr >> 1));
324     }
325   else
326     {
327       /* Strip off any upper segment bits.  */
328       store_unsigned_integer (buf, TYPE_LENGTH (type), byte_order,
329                               avr_convert_saddr_to_raw (addr));
330     }
331 }
332
333 static CORE_ADDR
334 avr_pointer_to_address (struct gdbarch *gdbarch,
335                         struct type *type, const gdb_byte *buf)
336 {
337   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
338   CORE_ADDR addr
339     = extract_unsigned_integer (buf, TYPE_LENGTH (type), byte_order);
340
341   /* Is it a data address in flash?  */
342   if (AVR_TYPE_ADDRESS_CLASS_FLASH (type))
343     {
344       /* A data pointer in flash is already byte addressed.  */
345       return avr_make_iaddr (addr);
346     }
347   /* Is it a code address?  */
348   else if (TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_FUNC
349            || TYPE_CODE (TYPE_TARGET_TYPE (type)) == TYPE_CODE_METHOD
350            || TYPE_CODE_SPACE (TYPE_TARGET_TYPE (type)))
351     {
352       /* A code pointer is word (16 bits) addressed so we shift it up
353          by 1 bit to convert it to an address.  */
354       return avr_make_iaddr (addr << 1);
355     }
356   else
357     return avr_make_saddr (addr);
358 }
359
360 static CORE_ADDR
361 avr_integer_to_address (struct gdbarch *gdbarch,
362                         struct type *type, const gdb_byte *buf)
363 {
364   ULONGEST addr = unpack_long (type, buf);
365
366   return avr_make_saddr (addr);
367 }
368
369 static CORE_ADDR
370 avr_read_pc (struct regcache *regcache)
371 {
372   ULONGEST pc;
373   regcache_cooked_read_unsigned (regcache, AVR_PC_REGNUM, &pc);
374   return avr_make_iaddr (pc);
375 }
376
377 static void
378 avr_write_pc (struct regcache *regcache, CORE_ADDR val)
379 {
380   regcache_cooked_write_unsigned (regcache, AVR_PC_REGNUM,
381                                   avr_convert_iaddr_to_raw (val));
382 }
383
384 static enum register_status
385 avr_pseudo_register_read (struct gdbarch *gdbarch, struct regcache *regcache,
386                           int regnum, gdb_byte *buf)
387 {
388   ULONGEST val;
389   enum register_status status;
390
391   switch (regnum)
392     {
393     case AVR_PSEUDO_PC_REGNUM:
394       status = regcache_raw_read_unsigned (regcache, AVR_PC_REGNUM, &val);
395       if (status != REG_VALID)
396         return status;
397       val >>= 1;
398       store_unsigned_integer (buf, 4, gdbarch_byte_order (gdbarch), val);
399       return status;
400     default:
401       internal_error (__FILE__, __LINE__, _("invalid regnum"));
402     }
403 }
404
405 static void
406 avr_pseudo_register_write (struct gdbarch *gdbarch, struct regcache *regcache,
407                            int regnum, const gdb_byte *buf)
408 {
409   ULONGEST val;
410
411   switch (regnum)
412     {
413     case AVR_PSEUDO_PC_REGNUM:
414       val = extract_unsigned_integer (buf, 4, gdbarch_byte_order (gdbarch));
415       val <<= 1;
416       regcache_raw_write_unsigned (regcache, AVR_PC_REGNUM, val);
417       break;
418     default:
419       internal_error (__FILE__, __LINE__, _("invalid regnum"));
420     }
421 }
422
423 /* Function: avr_scan_prologue
424
425    This function decodes an AVR function prologue to determine:
426      1) the size of the stack frame
427      2) which registers are saved on it
428      3) the offsets of saved regs
429    This information is stored in the avr_unwind_cache structure.
430
431    Some devices lack the sbiw instruction, so on those replace this:
432         sbiw    r28, XX
433    with this:
434         subi    r28,lo8(XX)
435         sbci    r29,hi8(XX)
436
437    A typical AVR function prologue with a frame pointer might look like this:
438         push    rXX        ; saved regs
439         ...
440         push    r28
441         push    r29
442         in      r28,__SP_L__
443         in      r29,__SP_H__
444         sbiw    r28,<LOCALS_SIZE>
445         in      __tmp_reg__,__SREG__
446         cli
447         out     __SP_H__,r29
448         out     __SREG__,__tmp_reg__
449         out     __SP_L__,r28
450
451    A typical AVR function prologue without a frame pointer might look like
452    this:
453         push    rXX        ; saved regs
454         ...
455
456    A main function prologue looks like this:
457         ldi     r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>)
458         ldi     r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>)
459         out     __SP_H__,r29
460         out     __SP_L__,r28
461
462    A signal handler prologue looks like this:
463         push    __zero_reg__
464         push    __tmp_reg__
465         in      __tmp_reg__, __SREG__
466         push    __tmp_reg__
467         clr     __zero_reg__
468         push    rXX             ; save registers r18:r27, r30:r31
469         ...
470         push    r28             ; save frame pointer
471         push    r29
472         in      r28, __SP_L__
473         in      r29, __SP_H__
474         sbiw    r28, <LOCALS_SIZE>
475         out     __SP_H__, r29
476         out     __SP_L__, r28
477         
478    A interrupt handler prologue looks like this:
479         sei
480         push    __zero_reg__
481         push    __tmp_reg__
482         in      __tmp_reg__, __SREG__
483         push    __tmp_reg__
484         clr     __zero_reg__
485         push    rXX             ; save registers r18:r27, r30:r31
486         ...
487         push    r28             ; save frame pointer
488         push    r29
489         in      r28, __SP_L__
490         in      r29, __SP_H__
491         sbiw    r28, <LOCALS_SIZE>
492         cli
493         out     __SP_H__, r29
494         sei     
495         out     __SP_L__, r28
496
497    A `-mcall-prologues' prologue looks like this (Note that the megas use a
498    jmp instead of a rjmp, thus the prologue is one word larger since jmp is a
499    32 bit insn and rjmp is a 16 bit insn):
500         ldi     r26,lo8(<LOCALS_SIZE>)
501         ldi     r27,hi8(<LOCALS_SIZE>)
502         ldi     r30,pm_lo8(.L_foo_body)
503         ldi     r31,pm_hi8(.L_foo_body)
504         rjmp    __prologue_saves__+RRR
505         .L_foo_body:  */
506
507 /* Not really part of a prologue, but still need to scan for it, is when a
508    function prologue moves values passed via registers as arguments to new
509    registers.  In this case, all local variables live in registers, so there
510    may be some register saves.  This is what it looks like:
511         movw    rMM, rNN
512         ...
513
514    There could be multiple movw's.  If the target doesn't have a movw insn, it
515    will use two mov insns.  This could be done after any of the above prologue
516    types.  */
517
518 static CORE_ADDR
519 avr_scan_prologue (struct gdbarch *gdbarch, CORE_ADDR pc_beg, CORE_ADDR pc_end,
520                    struct avr_unwind_cache *info)
521 {
522   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
523   int i;
524   unsigned short insn;
525   int scan_stage = 0;
526   struct bound_minimal_symbol msymbol;
527   unsigned char prologue[AVR_MAX_PROLOGUE_SIZE];
528   int vpc = 0;
529   int len;
530
531   len = pc_end - pc_beg;
532   if (len > AVR_MAX_PROLOGUE_SIZE)
533     len = AVR_MAX_PROLOGUE_SIZE;
534
535   /* FIXME: TRoth/2003-06-11: This could be made more efficient by only
536      reading in the bytes of the prologue.  The problem is that the figuring
537      out where the end of the prologue is is a bit difficult.  The old code 
538      tried to do that, but failed quite often.  */
539   read_memory (pc_beg, prologue, len);
540
541   /* Scanning main()'s prologue
542      ldi r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>)
543      ldi r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>)
544      out __SP_H__,r29
545      out __SP_L__,r28 */
546
547   if (len >= 4)
548     {
549       CORE_ADDR locals;
550       static const unsigned char img[] = {
551         0xde, 0xbf,             /* out __SP_H__,r29 */
552         0xcd, 0xbf              /* out __SP_L__,r28 */
553       };
554
555       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
556       /* ldi r28,lo8(<RAM_ADDR> - <LOCALS_SIZE>) */
557       if ((insn & 0xf0f0) == 0xe0c0)
558         {
559           locals = (insn & 0xf) | ((insn & 0x0f00) >> 4);
560           insn = extract_unsigned_integer (&prologue[vpc + 2], 2, byte_order);
561           /* ldi r29,hi8(<RAM_ADDR> - <LOCALS_SIZE>) */
562           if ((insn & 0xf0f0) == 0xe0d0)
563             {
564               locals |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
565               if (vpc + 4 + sizeof (img) < len
566                   && memcmp (prologue + vpc + 4, img, sizeof (img)) == 0)
567                 {
568                   info->prologue_type = AVR_PROLOGUE_MAIN;
569                   info->base = locals;
570                   return pc_beg + 4;
571                 }
572             }
573         }
574     }
575
576   /* Scanning `-mcall-prologues' prologue
577      Classic prologue is 10 bytes, mega prologue is a 12 bytes long */
578
579   while (1)     /* Using a while to avoid many goto's */
580     {
581       int loc_size;
582       int body_addr;
583       unsigned num_pushes;
584       int pc_offset = 0;
585
586       /* At least the fifth instruction must have been executed to
587          modify frame shape.  */
588       if (len < 10)
589         break;
590
591       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
592       /* ldi r26,<LOCALS_SIZE> */
593       if ((insn & 0xf0f0) != 0xe0a0)
594         break;
595       loc_size = (insn & 0xf) | ((insn & 0x0f00) >> 4);
596       pc_offset += 2;
597
598       insn = extract_unsigned_integer (&prologue[vpc + 2], 2, byte_order);
599       /* ldi r27,<LOCALS_SIZE> / 256 */
600       if ((insn & 0xf0f0) != 0xe0b0)
601         break;
602       loc_size |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
603       pc_offset += 2;
604
605       insn = extract_unsigned_integer (&prologue[vpc + 4], 2, byte_order);
606       /* ldi r30,pm_lo8(.L_foo_body) */
607       if ((insn & 0xf0f0) != 0xe0e0)
608         break;
609       body_addr = (insn & 0xf) | ((insn & 0x0f00) >> 4);
610       pc_offset += 2;
611
612       insn = extract_unsigned_integer (&prologue[vpc + 6], 2, byte_order);
613       /* ldi r31,pm_hi8(.L_foo_body) */
614       if ((insn & 0xf0f0) != 0xe0f0)
615         break;
616       body_addr |= ((insn & 0xf) | ((insn & 0x0f00) >> 4)) << 8;
617       pc_offset += 2;
618
619       msymbol = lookup_minimal_symbol ("__prologue_saves__", NULL, NULL);
620       if (!msymbol.minsym)
621         break;
622
623       insn = extract_unsigned_integer (&prologue[vpc + 8], 2, byte_order);
624       /* rjmp __prologue_saves__+RRR */
625       if ((insn & 0xf000) == 0xc000)
626         {
627           /* Extract PC relative offset from RJMP */
628           i = (insn & 0xfff) | (insn & 0x800 ? (-1 ^ 0xfff) : 0);
629           /* Convert offset to byte addressable mode */
630           i *= 2;
631           /* Destination address */
632           i += pc_beg + 10;
633
634           if (body_addr != (pc_beg + 10)/2)
635             break;
636
637           pc_offset += 2;
638         }
639       else if ((insn & 0xfe0e) == 0x940c)
640         {
641           /* Extract absolute PC address from JMP */
642           i = (((insn & 0x1) | ((insn & 0x1f0) >> 3) << 16)
643                | (extract_unsigned_integer (&prologue[vpc + 10], 2, byte_order)
644                   & 0xffff));
645           /* Convert address to byte addressable mode */
646           i *= 2;
647
648           if (body_addr != (pc_beg + 12)/2)
649             break;
650
651           pc_offset += 4;
652         }
653       else
654         break;
655
656       /* Resolve offset (in words) from __prologue_saves__ symbol.
657          Which is a pushes count in `-mcall-prologues' mode */
658       num_pushes = AVR_MAX_PUSHES - (i - BMSYMBOL_VALUE_ADDRESS (msymbol)) / 2;
659
660       if (num_pushes > AVR_MAX_PUSHES)
661         {
662           fprintf_unfiltered (gdb_stderr, _("Num pushes too large: %d\n"),
663                               num_pushes);
664           num_pushes = 0;
665         }
666
667       if (num_pushes)
668         {
669           int from;
670
671           info->saved_regs[AVR_FP_REGNUM + 1].addr = num_pushes;
672           if (num_pushes >= 2)
673             info->saved_regs[AVR_FP_REGNUM].addr = num_pushes - 1;
674
675           i = 0;
676           for (from = AVR_LAST_PUSHED_REGNUM + 1 - (num_pushes - 2);
677                from <= AVR_LAST_PUSHED_REGNUM; ++from)
678             info->saved_regs [from].addr = ++i;
679         }
680       info->size = loc_size + num_pushes;
681       info->prologue_type = AVR_PROLOGUE_CALL;
682
683       return pc_beg + pc_offset;
684     }
685
686   /* Scan for the beginning of the prologue for an interrupt or signal
687      function.  Note that we have to set the prologue type here since the
688      third stage of the prologue may not be present (e.g. no saved registered
689      or changing of the SP register).  */
690
691   if (1)
692     {
693       static const unsigned char img[] = {
694         0x78, 0x94,             /* sei */
695         0x1f, 0x92,             /* push r1 */
696         0x0f, 0x92,             /* push r0 */
697         0x0f, 0xb6,             /* in r0,0x3f SREG */
698         0x0f, 0x92,             /* push r0 */
699         0x11, 0x24              /* clr r1 */
700       };
701       if (len >= sizeof (img)
702           && memcmp (prologue, img, sizeof (img)) == 0)
703         {
704           info->prologue_type = AVR_PROLOGUE_INTR;
705           vpc += sizeof (img);
706           info->saved_regs[AVR_SREG_REGNUM].addr = 3;
707           info->saved_regs[0].addr = 2;
708           info->saved_regs[1].addr = 1;
709           info->size += 3;
710         }
711       else if (len >= sizeof (img) - 2
712                && memcmp (img + 2, prologue, sizeof (img) - 2) == 0)
713         {
714           info->prologue_type = AVR_PROLOGUE_SIG;
715           vpc += sizeof (img) - 2;
716           info->saved_regs[AVR_SREG_REGNUM].addr = 3;
717           info->saved_regs[0].addr = 2;
718           info->saved_regs[1].addr = 1;
719           info->size += 2;
720         }
721     }
722
723   /* First stage of the prologue scanning.
724      Scan pushes (saved registers) */
725
726   for (; vpc < len; vpc += 2)
727     {
728       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
729       if ((insn & 0xfe0f) == 0x920f)    /* push rXX */
730         {
731           /* Bits 4-9 contain a mask for registers R0-R32.  */
732           int regno = (insn & 0x1f0) >> 4;
733           info->size++;
734           info->saved_regs[regno].addr = info->size;
735           scan_stage = 1;
736         }
737       else
738         break;
739     }
740
741   gdb_assert (vpc < AVR_MAX_PROLOGUE_SIZE);
742
743   /* Handle static small stack allocation using rcall or push.  */
744
745   while (scan_stage == 1 && vpc < len)
746     {
747       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
748       if (insn == 0xd000)       /* rcall .+0 */
749         {
750           info->size += gdbarch_tdep (gdbarch)->call_length;
751           vpc += 2;
752         }
753       else if (insn == 0x920f || insn == 0x921f)  /* push r0 or push r1 */
754         {
755           info->size += 1;
756           vpc += 2;
757         }
758       else
759         break;
760     }
761
762   /* Second stage of the prologue scanning.
763      Scan:
764      in r28,__SP_L__
765      in r29,__SP_H__ */
766
767   if (scan_stage == 1 && vpc < len)
768     {
769       static const unsigned char img[] = {
770         0xcd, 0xb7,             /* in r28,__SP_L__ */
771         0xde, 0xb7              /* in r29,__SP_H__ */
772       };
773
774       if (vpc + sizeof (img) < len
775           && memcmp (prologue + vpc, img, sizeof (img)) == 0)
776         {
777           vpc += 4;
778           scan_stage = 2;
779         }
780     }
781
782   /* Third stage of the prologue scanning.  (Really two stages).
783      Scan for:
784      sbiw r28,XX or subi r28,lo8(XX)
785                     sbci r29,hi8(XX)
786      in __tmp_reg__,__SREG__
787      cli
788      out __SP_H__,r29
789      out __SREG__,__tmp_reg__
790      out __SP_L__,r28 */
791
792   if (scan_stage == 2 && vpc < len)
793     {
794       int locals_size = 0;
795       static const unsigned char img[] = {
796         0x0f, 0xb6,             /* in r0,0x3f */
797         0xf8, 0x94,             /* cli */
798         0xde, 0xbf,             /* out 0x3e,r29 ; SPH */
799         0x0f, 0xbe,             /* out 0x3f,r0  ; SREG */
800         0xcd, 0xbf              /* out 0x3d,r28 ; SPL */
801       };
802       static const unsigned char img_sig[] = {
803         0xde, 0xbf,             /* out 0x3e,r29 ; SPH */
804         0xcd, 0xbf              /* out 0x3d,r28 ; SPL */
805       };
806       static const unsigned char img_int[] = {
807         0xf8, 0x94,             /* cli */
808         0xde, 0xbf,             /* out 0x3e,r29 ; SPH */
809         0x78, 0x94,             /* sei */
810         0xcd, 0xbf              /* out 0x3d,r28 ; SPL */
811       };
812
813       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
814       if ((insn & 0xff30) == 0x9720)    /* sbiw r28,XXX */
815         {
816           locals_size = (insn & 0xf) | ((insn & 0xc0) >> 2);
817           vpc += 2;
818         }
819       else if ((insn & 0xf0f0) == 0x50c0)       /* subi r28,lo8(XX) */
820         {
821           locals_size = (insn & 0xf) | ((insn & 0xf00) >> 4);
822           vpc += 2;
823           insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
824           vpc += 2;
825           locals_size += ((insn & 0xf) | ((insn & 0xf00) >> 4)) << 8;
826         }
827       else
828         return pc_beg + vpc;
829
830       /* Scan the last part of the prologue.  May not be present for interrupt
831          or signal handler functions, which is why we set the prologue type
832          when we saw the beginning of the prologue previously.  */
833
834       if (vpc + sizeof (img_sig) < len
835           && memcmp (prologue + vpc, img_sig, sizeof (img_sig)) == 0)
836         {
837           vpc += sizeof (img_sig);
838         }
839       else if (vpc + sizeof (img_int) < len 
840                && memcmp (prologue + vpc, img_int, sizeof (img_int)) == 0)
841         {
842           vpc += sizeof (img_int);
843         }
844       if (vpc + sizeof (img) < len
845           && memcmp (prologue + vpc, img, sizeof (img)) == 0)
846         {
847           info->prologue_type = AVR_PROLOGUE_NORMAL;
848           vpc += sizeof (img);
849         }
850
851       info->size += locals_size;
852
853       /* Fall through.  */
854     }
855
856   /* If we got this far, we could not scan the prologue, so just return the pc
857      of the frame plus an adjustment for argument move insns.  */
858
859   for (; vpc < len; vpc += 2)
860     {
861       insn = extract_unsigned_integer (&prologue[vpc], 2, byte_order);
862       if ((insn & 0xff00) == 0x0100)    /* movw rXX, rYY */
863         continue;
864       else if ((insn & 0xfc00) == 0x2c00) /* mov rXX, rYY */
865         continue;
866       else
867           break;
868     }
869     
870   return pc_beg + vpc;
871 }
872
873 static CORE_ADDR
874 avr_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR pc)
875 {
876   CORE_ADDR func_addr, func_end;
877   CORE_ADDR post_prologue_pc;
878
879   /* See what the symbol table says */
880
881   if (!find_pc_partial_function (pc, NULL, &func_addr, &func_end))
882     return pc;
883
884   post_prologue_pc = skip_prologue_using_sal (gdbarch, func_addr);
885   if (post_prologue_pc != 0)
886     return std::max (pc, post_prologue_pc);
887
888   {
889     CORE_ADDR prologue_end = pc;
890     struct avr_unwind_cache info = {0};
891     struct trad_frame_saved_reg saved_regs[AVR_NUM_REGS];
892
893     info.saved_regs = saved_regs;
894     
895     /* Need to run the prologue scanner to figure out if the function has a
896        prologue and possibly skip over moving arguments passed via registers
897        to other registers.  */
898     
899     prologue_end = avr_scan_prologue (gdbarch, func_addr, func_end, &info);
900     
901     if (info.prologue_type != AVR_PROLOGUE_NONE)
902       return prologue_end;
903   }
904
905   /* Either we didn't find the start of this function (nothing we can do),
906      or there's no line info, or the line after the prologue is after
907      the end of the function (there probably isn't a prologue).  */
908
909   return pc;
910 }
911
912 /* Not all avr devices support the BREAK insn.  Those that don't should treat
913    it as a NOP.  Thus, it should be ok.  Since the avr is currently a remote
914    only target, this shouldn't be a problem (I hope).  TRoth/2003-05-14  */
915
916 static const unsigned char *
917 avr_breakpoint_from_pc (struct gdbarch *gdbarch,
918                         CORE_ADDR *pcptr, int *lenptr)
919 {
920     static const unsigned char avr_break_insn [] = { 0x98, 0x95 };
921     *lenptr = sizeof (avr_break_insn);
922     return avr_break_insn;
923 }
924
925 /* Determine, for architecture GDBARCH, how a return value of TYPE
926    should be returned.  If it is supposed to be returned in registers,
927    and READBUF is non-zero, read the appropriate value from REGCACHE,
928    and copy it into READBUF.  If WRITEBUF is non-zero, write the value
929    from WRITEBUF into REGCACHE.  */
930
931 static enum return_value_convention
932 avr_return_value (struct gdbarch *gdbarch, struct value *function,
933                   struct type *valtype, struct regcache *regcache,
934                   gdb_byte *readbuf, const gdb_byte *writebuf)
935 {
936   int i;
937   /* Single byte are returned in r24.
938      Otherwise, the MSB of the return value is always in r25, calculate which
939      register holds the LSB.  */
940   int lsb_reg;
941
942   if ((TYPE_CODE (valtype) == TYPE_CODE_STRUCT
943        || TYPE_CODE (valtype) == TYPE_CODE_UNION
944        || TYPE_CODE (valtype) == TYPE_CODE_ARRAY)
945       && TYPE_LENGTH (valtype) > 8)
946     return RETURN_VALUE_STRUCT_CONVENTION;
947
948   if (TYPE_LENGTH (valtype) <= 2)
949     lsb_reg = 24;
950   else if (TYPE_LENGTH (valtype) <= 4)
951     lsb_reg = 22;
952   else if (TYPE_LENGTH (valtype) <= 8)
953     lsb_reg = 18;
954   else
955     gdb_assert_not_reached ("unexpected type length");
956
957   if (writebuf != NULL)
958     {
959       for (i = 0; i < TYPE_LENGTH (valtype); i++)
960         regcache_cooked_write (regcache, lsb_reg + i, writebuf + i);
961     }
962
963   if (readbuf != NULL)
964     {
965       for (i = 0; i < TYPE_LENGTH (valtype); i++)
966         regcache_cooked_read (regcache, lsb_reg + i, readbuf + i);
967     }
968
969   return RETURN_VALUE_REGISTER_CONVENTION;
970 }
971
972
973 /* Put here the code to store, into fi->saved_regs, the addresses of
974    the saved registers of frame described by FRAME_INFO.  This
975    includes special registers such as pc and fp saved in special ways
976    in the stack frame.  sp is even more special: the address we return
977    for it IS the sp for the next frame.  */
978
979 static struct avr_unwind_cache *
980 avr_frame_unwind_cache (struct frame_info *this_frame,
981                         void **this_prologue_cache)
982 {
983   CORE_ADDR start_pc, current_pc;
984   ULONGEST prev_sp;
985   ULONGEST this_base;
986   struct avr_unwind_cache *info;
987   struct gdbarch *gdbarch;
988   struct gdbarch_tdep *tdep;
989   int i;
990
991   if (*this_prologue_cache)
992     return (struct avr_unwind_cache *) *this_prologue_cache;
993
994   info = FRAME_OBSTACK_ZALLOC (struct avr_unwind_cache);
995   *this_prologue_cache = info;
996   info->saved_regs = trad_frame_alloc_saved_regs (this_frame);
997
998   info->size = 0;
999   info->prologue_type = AVR_PROLOGUE_NONE;
1000
1001   start_pc = get_frame_func (this_frame);
1002   current_pc = get_frame_pc (this_frame);
1003   if ((start_pc > 0) && (start_pc <= current_pc))
1004     avr_scan_prologue (get_frame_arch (this_frame),
1005                        start_pc, current_pc, info);
1006
1007   if ((info->prologue_type != AVR_PROLOGUE_NONE)
1008       && (info->prologue_type != AVR_PROLOGUE_MAIN))
1009     {
1010       ULONGEST high_base;       /* High byte of FP */
1011
1012       /* The SP was moved to the FP.  This indicates that a new frame
1013          was created.  Get THIS frame's FP value by unwinding it from
1014          the next frame.  */
1015       this_base = get_frame_register_unsigned (this_frame, AVR_FP_REGNUM);
1016       high_base = get_frame_register_unsigned (this_frame, AVR_FP_REGNUM + 1);
1017       this_base += (high_base << 8);
1018       
1019       /* The FP points at the last saved register.  Adjust the FP back
1020          to before the first saved register giving the SP.  */
1021       prev_sp = this_base + info->size; 
1022    }
1023   else
1024     {
1025       /* Assume that the FP is this frame's SP but with that pushed
1026          stack space added back.  */
1027       this_base = get_frame_register_unsigned (this_frame, AVR_SP_REGNUM);
1028       prev_sp = this_base + info->size;
1029     }
1030
1031   /* Add 1 here to adjust for the post-decrement nature of the push
1032      instruction.*/
1033   info->prev_sp = avr_make_saddr (prev_sp + 1);
1034   info->base = avr_make_saddr (this_base);
1035
1036   gdbarch = get_frame_arch (this_frame);
1037
1038   /* Adjust all the saved registers so that they contain addresses and not
1039      offsets.  */
1040   for (i = 0; i < gdbarch_num_regs (gdbarch) - 1; i++)
1041     if (info->saved_regs[i].addr > 0)
1042       info->saved_regs[i].addr = info->prev_sp - info->saved_regs[i].addr;
1043
1044   /* Except for the main and startup code, the return PC is always saved on
1045      the stack and is at the base of the frame.  */
1046
1047   if (info->prologue_type != AVR_PROLOGUE_MAIN)
1048     info->saved_regs[AVR_PC_REGNUM].addr = info->prev_sp;
1049
1050   /* The previous frame's SP needed to be computed.  Save the computed
1051      value.  */
1052   tdep = gdbarch_tdep (gdbarch);
1053   trad_frame_set_value (info->saved_regs, AVR_SP_REGNUM,
1054                         info->prev_sp - 1 + tdep->call_length);
1055
1056   return info;
1057 }
1058
1059 static CORE_ADDR
1060 avr_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
1061 {
1062   ULONGEST pc;
1063
1064   pc = frame_unwind_register_unsigned (next_frame, AVR_PC_REGNUM);
1065
1066   return avr_make_iaddr (pc);
1067 }
1068
1069 static CORE_ADDR
1070 avr_unwind_sp (struct gdbarch *gdbarch, struct frame_info *next_frame)
1071 {
1072   ULONGEST sp;
1073
1074   sp = frame_unwind_register_unsigned (next_frame, AVR_SP_REGNUM);
1075
1076   return avr_make_saddr (sp);
1077 }
1078
1079 /* Given a GDB frame, determine the address of the calling function's
1080    frame.  This will be used to create a new GDB frame struct.  */
1081
1082 static void
1083 avr_frame_this_id (struct frame_info *this_frame,
1084                    void **this_prologue_cache,
1085                    struct frame_id *this_id)
1086 {
1087   struct avr_unwind_cache *info
1088     = avr_frame_unwind_cache (this_frame, this_prologue_cache);
1089   CORE_ADDR base;
1090   CORE_ADDR func;
1091   struct frame_id id;
1092
1093   /* The FUNC is easy.  */
1094   func = get_frame_func (this_frame);
1095
1096   /* Hopefully the prologue analysis either correctly determined the
1097      frame's base (which is the SP from the previous frame), or set
1098      that base to "NULL".  */
1099   base = info->prev_sp;
1100   if (base == 0)
1101     return;
1102
1103   id = frame_id_build (base, func);
1104   (*this_id) = id;
1105 }
1106
1107 static struct value *
1108 avr_frame_prev_register (struct frame_info *this_frame,
1109                          void **this_prologue_cache, int regnum)
1110 {
1111   struct avr_unwind_cache *info
1112     = avr_frame_unwind_cache (this_frame, this_prologue_cache);
1113
1114   if (regnum == AVR_PC_REGNUM || regnum == AVR_PSEUDO_PC_REGNUM)
1115     {
1116       if (trad_frame_addr_p (info->saved_regs, AVR_PC_REGNUM))
1117         {
1118           /* Reading the return PC from the PC register is slightly
1119              abnormal.  register_size(AVR_PC_REGNUM) says it is 4 bytes,
1120              but in reality, only two bytes (3 in upcoming mega256) are
1121              stored on the stack.
1122
1123              Also, note that the value on the stack is an addr to a word
1124              not a byte, so we will need to multiply it by two at some
1125              point. 
1126
1127              And to confuse matters even more, the return address stored
1128              on the stack is in big endian byte order, even though most
1129              everything else about the avr is little endian.  Ick!  */
1130           ULONGEST pc;
1131           int i;
1132           gdb_byte buf[3];
1133           struct gdbarch *gdbarch = get_frame_arch (this_frame);
1134           struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1135
1136           read_memory (info->saved_regs[AVR_PC_REGNUM].addr,
1137                        buf, tdep->call_length);
1138
1139           /* Extract the PC read from memory as a big-endian.  */
1140           pc = 0;
1141           for (i = 0; i < tdep->call_length; i++)
1142             pc = (pc << 8) | buf[i];
1143
1144           if (regnum == AVR_PC_REGNUM)
1145             pc <<= 1;
1146
1147           return frame_unwind_got_constant (this_frame, regnum, pc);
1148         }
1149
1150       return frame_unwind_got_optimized (this_frame, regnum);
1151     }
1152
1153   return trad_frame_get_prev_register (this_frame, info->saved_regs, regnum);
1154 }
1155
1156 static const struct frame_unwind avr_frame_unwind = {
1157   NORMAL_FRAME,
1158   default_frame_unwind_stop_reason,
1159   avr_frame_this_id,
1160   avr_frame_prev_register,
1161   NULL,
1162   default_frame_sniffer
1163 };
1164
1165 static CORE_ADDR
1166 avr_frame_base_address (struct frame_info *this_frame, void **this_cache)
1167 {
1168   struct avr_unwind_cache *info
1169     = avr_frame_unwind_cache (this_frame, this_cache);
1170
1171   return info->base;
1172 }
1173
1174 static const struct frame_base avr_frame_base = {
1175   &avr_frame_unwind,
1176   avr_frame_base_address,
1177   avr_frame_base_address,
1178   avr_frame_base_address
1179 };
1180
1181 /* Assuming THIS_FRAME is a dummy, return the frame ID of that dummy
1182    frame.  The frame ID's base needs to match the TOS value saved by
1183    save_dummy_frame_tos(), and the PC match the dummy frame's breakpoint.  */
1184
1185 static struct frame_id
1186 avr_dummy_id (struct gdbarch *gdbarch, struct frame_info *this_frame)
1187 {
1188   ULONGEST base;
1189
1190   base = get_frame_register_unsigned (this_frame, AVR_SP_REGNUM);
1191   return frame_id_build (avr_make_saddr (base), get_frame_pc (this_frame));
1192 }
1193
1194 /* When arguments must be pushed onto the stack, they go on in reverse
1195    order.  The below implements a FILO (stack) to do this.  */
1196
1197 struct stack_item
1198 {
1199   int len;
1200   struct stack_item *prev;
1201   gdb_byte *data;
1202 };
1203
1204 static struct stack_item *
1205 push_stack_item (struct stack_item *prev, const bfd_byte *contents, int len)
1206 {
1207   struct stack_item *si;
1208   si = XNEW (struct stack_item);
1209   si->data = (gdb_byte *) xmalloc (len);
1210   si->len = len;
1211   si->prev = prev;
1212   memcpy (si->data, contents, len);
1213   return si;
1214 }
1215
1216 static struct stack_item *pop_stack_item (struct stack_item *si);
1217 static struct stack_item *
1218 pop_stack_item (struct stack_item *si)
1219 {
1220   struct stack_item *dead = si;
1221   si = si->prev;
1222   xfree (dead->data);
1223   xfree (dead);
1224   return si;
1225 }
1226
1227 /* Setup the function arguments for calling a function in the inferior.
1228
1229    On the AVR architecture, there are 18 registers (R25 to R8) which are
1230    dedicated for passing function arguments.  Up to the first 18 arguments
1231    (depending on size) may go into these registers.  The rest go on the stack.
1232
1233    All arguments are aligned to start in even-numbered registers (odd-sized
1234    arguments, including char, have one free register above them).  For example,
1235    an int in arg1 and a char in arg2 would be passed as such:
1236
1237       arg1 -> r25:r24
1238       arg2 -> r22
1239
1240    Arguments that are larger than 2 bytes will be split between two or more
1241    registers as available, but will NOT be split between a register and the
1242    stack.  Arguments that go onto the stack are pushed last arg first (this is
1243    similar to the d10v).  */
1244
1245 /* NOTE: TRoth/2003-06-17: The rest of this comment is old looks to be
1246    inaccurate.
1247
1248    An exceptional case exists for struct arguments (and possibly other
1249    aggregates such as arrays) -- if the size is larger than WORDSIZE bytes but
1250    not a multiple of WORDSIZE bytes.  In this case the argument is never split
1251    between the registers and the stack, but instead is copied in its entirety
1252    onto the stack, AND also copied into as many registers as there is room
1253    for.  In other words, space in registers permitting, two copies of the same
1254    argument are passed in.  As far as I can tell, only the one on the stack is
1255    used, although that may be a function of the level of compiler
1256    optimization.  I suspect this is a compiler bug.  Arguments of these odd
1257    sizes are left-justified within the word (as opposed to arguments smaller
1258    than WORDSIZE bytes, which are right-justified).
1259  
1260    If the function is to return an aggregate type such as a struct, the caller
1261    must allocate space into which the callee will copy the return value.  In
1262    this case, a pointer to the return value location is passed into the callee
1263    in register R0, which displaces one of the other arguments passed in via
1264    registers R0 to R2.  */
1265
1266 static CORE_ADDR
1267 avr_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
1268                      struct regcache *regcache, CORE_ADDR bp_addr,
1269                      int nargs, struct value **args, CORE_ADDR sp,
1270                      int struct_return, CORE_ADDR struct_addr)
1271 {
1272   int i;
1273   gdb_byte buf[3];
1274   int call_length = gdbarch_tdep (gdbarch)->call_length;
1275   CORE_ADDR return_pc = avr_convert_iaddr_to_raw (bp_addr);
1276   int regnum = AVR_ARGN_REGNUM;
1277   struct stack_item *si = NULL;
1278
1279   if (struct_return)
1280     {
1281       regcache_cooked_write_unsigned
1282         (regcache, regnum--, (struct_addr >> 8) & 0xff);
1283       regcache_cooked_write_unsigned
1284         (regcache, regnum--, struct_addr & 0xff);
1285       /* SP being post decremented, we need to reserve one byte so that the
1286          return address won't overwrite the result (or vice-versa).  */
1287       if (sp == struct_addr)
1288         sp--;
1289     }
1290
1291   for (i = 0; i < nargs; i++)
1292     {
1293       int last_regnum;
1294       int j;
1295       struct value *arg = args[i];
1296       struct type *type = check_typedef (value_type (arg));
1297       const bfd_byte *contents = value_contents (arg);
1298       int len = TYPE_LENGTH (type);
1299
1300       /* Calculate the potential last register needed.
1301          E.g. For length 2, registers regnum and regnum-1 (say 25 and 24)
1302          shall be used. So, last needed register will be regnum-1(24).  */
1303       last_regnum = regnum - (len + (len & 1)) + 1;
1304
1305       /* If there are registers available, use them.  Once we start putting
1306          stuff on the stack, all subsequent args go on stack.  */
1307       if ((si == NULL) && (last_regnum >= AVR_LAST_ARG_REGNUM))
1308         {
1309           /* Skip a register for odd length args.  */
1310           if (len & 1)
1311             regnum--;
1312
1313           /* Write MSB of argument into register and subsequent bytes in
1314              decreasing register numbers.  */
1315           for (j = 0; j < len; j++)
1316             regcache_cooked_write_unsigned
1317               (regcache, regnum--, contents[len - j - 1]);
1318         }
1319       /* No registers available, push the args onto the stack.  */
1320       else
1321         {
1322           /* From here on, we don't care about regnum.  */
1323           si = push_stack_item (si, contents, len);
1324         }
1325     }
1326
1327   /* Push args onto the stack.  */
1328   while (si)
1329     {
1330       sp -= si->len;
1331       /* Add 1 to sp here to account for post decr nature of pushes.  */
1332       write_memory (sp + 1, si->data, si->len);
1333       si = pop_stack_item (si);
1334     }
1335
1336   /* Set the return address.  For the avr, the return address is the BP_ADDR.
1337      Need to push the return address onto the stack noting that it needs to be
1338      in big-endian order on the stack.  */
1339   for (i = 1; i <= call_length; i++)
1340     {
1341       buf[call_length - i] = return_pc & 0xff;
1342       return_pc >>= 8;
1343     }
1344
1345   sp -= call_length;
1346   /* Use 'sp + 1' since pushes are post decr ops.  */
1347   write_memory (sp + 1, buf, call_length);
1348
1349   /* Finally, update the SP register.  */
1350   regcache_cooked_write_unsigned (regcache, AVR_SP_REGNUM,
1351                                   avr_convert_saddr_to_raw (sp));
1352
1353   /* Return SP value for the dummy frame, where the return address hasn't been
1354      pushed.  */
1355   return sp + call_length;
1356 }
1357
1358 /* Unfortunately dwarf2 register for SP is 32.  */
1359
1360 static int
1361 avr_dwarf_reg_to_regnum (struct gdbarch *gdbarch, int reg)
1362 {
1363   if (reg >= 0 && reg < 32)
1364     return reg;
1365   if (reg == 32)
1366     return AVR_SP_REGNUM;
1367   return -1;
1368 }
1369
1370 /* Implementation of `address_class_type_flags' gdbarch method.
1371
1372    This method maps DW_AT_address_class attributes to a
1373    type_instance_flag_value.  */
1374
1375 static int
1376 avr_address_class_type_flags (int byte_size, int dwarf2_addr_class)
1377 {
1378   /* The value 1 of the DW_AT_address_class attribute corresponds to the
1379      __flash qualifier.  Note that this attribute is only valid with
1380      pointer types and therefore the flag is set to the pointer type and
1381      not its target type.  */
1382   if (dwarf2_addr_class == 1 && byte_size == 2)
1383     return AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH;
1384   return 0;
1385 }
1386
1387 /* Implementation of `address_class_type_flags_to_name' gdbarch method.
1388
1389    Convert a type_instance_flag_value to an address space qualifier.  */
1390
1391 static const char*
1392 avr_address_class_type_flags_to_name (struct gdbarch *gdbarch, int type_flags)
1393 {
1394   if (type_flags & AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH)
1395     return "flash";
1396   else
1397     return NULL;
1398 }
1399
1400 /* Implementation of `address_class_name_to_type_flags' gdbarch method.
1401
1402    Convert an address space qualifier to a type_instance_flag_value.  */
1403
1404 static int
1405 avr_address_class_name_to_type_flags (struct gdbarch *gdbarch,
1406                                       const char* name,
1407                                       int *type_flags_ptr)
1408 {
1409   if (strcmp (name, "flash") == 0)
1410     {
1411       *type_flags_ptr = AVR_TYPE_INSTANCE_FLAG_ADDRESS_CLASS_FLASH;
1412       return 1;
1413     }
1414   else
1415     return 0;
1416 }
1417
1418 /* Initialize the gdbarch structure for the AVR's.  */
1419
1420 static struct gdbarch *
1421 avr_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
1422 {
1423   struct gdbarch *gdbarch;
1424   struct gdbarch_tdep *tdep;
1425   struct gdbarch_list *best_arch;
1426   int call_length;
1427
1428   /* Avr-6 call instructions save 3 bytes.  */
1429   switch (info.bfd_arch_info->mach)
1430     {
1431     case bfd_mach_avr1:
1432     case bfd_mach_avrxmega1:
1433     case bfd_mach_avr2:
1434     case bfd_mach_avrxmega2:
1435     case bfd_mach_avr3:
1436     case bfd_mach_avrxmega3:
1437     case bfd_mach_avr4:
1438     case bfd_mach_avrxmega4:
1439     case bfd_mach_avr5:
1440     case bfd_mach_avrxmega5:
1441     default:
1442       call_length = 2;
1443       break;
1444     case bfd_mach_avr6:
1445     case bfd_mach_avrxmega6:
1446     case bfd_mach_avrxmega7:
1447       call_length = 3;
1448       break;
1449     }
1450
1451   /* If there is already a candidate, use it.  */
1452   for (best_arch = gdbarch_list_lookup_by_info (arches, &info);
1453        best_arch != NULL;
1454        best_arch = gdbarch_list_lookup_by_info (best_arch->next, &info))
1455     {
1456       if (gdbarch_tdep (best_arch->gdbarch)->call_length == call_length)
1457         return best_arch->gdbarch;
1458     }
1459
1460   /* None found, create a new architecture from the information provided.  */
1461   tdep = XNEW (struct gdbarch_tdep);
1462   gdbarch = gdbarch_alloc (&info, tdep);
1463   
1464   tdep->call_length = call_length;
1465
1466   /* Create a type for PC.  We can't use builtin types here, as they may not
1467      be defined.  */
1468   tdep->void_type = arch_type (gdbarch, TYPE_CODE_VOID, 1, "void");
1469   tdep->func_void_type = make_function_type (tdep->void_type, NULL);
1470   tdep->pc_type = arch_pointer_type (gdbarch, 4 * TARGET_CHAR_BIT, NULL,
1471                                      tdep->func_void_type);
1472
1473   set_gdbarch_short_bit (gdbarch, 2 * TARGET_CHAR_BIT);
1474   set_gdbarch_int_bit (gdbarch, 2 * TARGET_CHAR_BIT);
1475   set_gdbarch_long_bit (gdbarch, 4 * TARGET_CHAR_BIT);
1476   set_gdbarch_long_long_bit (gdbarch, 8 * TARGET_CHAR_BIT);
1477   set_gdbarch_ptr_bit (gdbarch, 2 * TARGET_CHAR_BIT);
1478   set_gdbarch_addr_bit (gdbarch, 32);
1479
1480   set_gdbarch_float_bit (gdbarch, 4 * TARGET_CHAR_BIT);
1481   set_gdbarch_double_bit (gdbarch, 4 * TARGET_CHAR_BIT);
1482   set_gdbarch_long_double_bit (gdbarch, 4 * TARGET_CHAR_BIT);
1483
1484   set_gdbarch_float_format (gdbarch, floatformats_ieee_single);
1485   set_gdbarch_double_format (gdbarch, floatformats_ieee_single);
1486   set_gdbarch_long_double_format (gdbarch, floatformats_ieee_single);
1487
1488   set_gdbarch_read_pc (gdbarch, avr_read_pc);
1489   set_gdbarch_write_pc (gdbarch, avr_write_pc);
1490
1491   set_gdbarch_num_regs (gdbarch, AVR_NUM_REGS);
1492
1493   set_gdbarch_sp_regnum (gdbarch, AVR_SP_REGNUM);
1494   set_gdbarch_pc_regnum (gdbarch, AVR_PC_REGNUM);
1495
1496   set_gdbarch_register_name (gdbarch, avr_register_name);
1497   set_gdbarch_register_type (gdbarch, avr_register_type);
1498
1499   set_gdbarch_num_pseudo_regs (gdbarch, AVR_NUM_PSEUDO_REGS);
1500   set_gdbarch_pseudo_register_read (gdbarch, avr_pseudo_register_read);
1501   set_gdbarch_pseudo_register_write (gdbarch, avr_pseudo_register_write);
1502
1503   set_gdbarch_return_value (gdbarch, avr_return_value);
1504   set_gdbarch_print_insn (gdbarch, print_insn_avr);
1505
1506   set_gdbarch_push_dummy_call (gdbarch, avr_push_dummy_call);
1507
1508   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, avr_dwarf_reg_to_regnum);
1509
1510   set_gdbarch_address_to_pointer (gdbarch, avr_address_to_pointer);
1511   set_gdbarch_pointer_to_address (gdbarch, avr_pointer_to_address);
1512   set_gdbarch_integer_to_address (gdbarch, avr_integer_to_address);
1513
1514   set_gdbarch_skip_prologue (gdbarch, avr_skip_prologue);
1515   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
1516
1517   set_gdbarch_breakpoint_from_pc (gdbarch, avr_breakpoint_from_pc);
1518
1519   frame_unwind_append_unwinder (gdbarch, &avr_frame_unwind);
1520   frame_base_set_default (gdbarch, &avr_frame_base);
1521
1522   set_gdbarch_dummy_id (gdbarch, avr_dummy_id);
1523
1524   set_gdbarch_unwind_pc (gdbarch, avr_unwind_pc);
1525   set_gdbarch_unwind_sp (gdbarch, avr_unwind_sp);
1526
1527   set_gdbarch_address_class_type_flags (gdbarch, avr_address_class_type_flags);
1528   set_gdbarch_address_class_name_to_type_flags
1529     (gdbarch, avr_address_class_name_to_type_flags);
1530   set_gdbarch_address_class_type_flags_to_name
1531     (gdbarch, avr_address_class_type_flags_to_name);
1532
1533   return gdbarch;
1534 }
1535
1536 /* Send a query request to the avr remote target asking for values of the io
1537    registers.  If args parameter is not NULL, then the user has requested info
1538    on a specific io register [This still needs implemented and is ignored for
1539    now].  The query string should be one of these forms:
1540
1541    "Ravr.io_reg" -> reply is "NN" number of io registers
1542
1543    "Ravr.io_reg:addr,len" where addr is first register and len is number of
1544    registers to be read.  The reply should be "<NAME>,VV;" for each io register
1545    where, <NAME> is a string, and VV is the hex value of the register.
1546
1547    All io registers are 8-bit.  */
1548
1549 static void
1550 avr_io_reg_read_command (char *args, int from_tty)
1551 {
1552   LONGEST bufsiz = 0;
1553   gdb_byte *buf;
1554   const char *bufstr;
1555   char query[400];
1556   const char *p;
1557   unsigned int nreg = 0;
1558   unsigned int val;
1559   int i, j, k, step;
1560
1561   /* Find out how many io registers the target has.  */
1562   bufsiz = target_read_alloc (&current_target, TARGET_OBJECT_AVR,
1563                               "avr.io_reg", &buf);
1564   bufstr = (const char *) buf;
1565
1566   if (bufsiz <= 0)
1567     {
1568       fprintf_unfiltered (gdb_stderr,
1569                           _("ERR: info io_registers NOT supported "
1570                             "by current target\n"));
1571       return;
1572     }
1573
1574   if (sscanf (bufstr, "%x", &nreg) != 1)
1575     {
1576       fprintf_unfiltered (gdb_stderr,
1577                           _("Error fetching number of io registers\n"));
1578       xfree (buf);
1579       return;
1580     }
1581
1582   xfree (buf);
1583
1584   reinitialize_more_filter ();
1585
1586   printf_unfiltered (_("Target has %u io registers:\n\n"), nreg);
1587
1588   /* only fetch up to 8 registers at a time to keep the buffer small */
1589   step = 8;
1590
1591   for (i = 0; i < nreg; i += step)
1592     {
1593       /* how many registers this round? */
1594       j = step;
1595       if ((i+j) >= nreg)
1596         j = nreg - i;           /* last block is less than 8 registers */
1597
1598       snprintf (query, sizeof (query) - 1, "avr.io_reg:%x,%x", i, j);
1599       bufsiz = target_read_alloc (&current_target, TARGET_OBJECT_AVR,
1600                                   query, &buf);
1601
1602       p = (const char *) buf;
1603       for (k = i; k < (i + j); k++)
1604         {
1605           if (sscanf (p, "%[^,],%x;", query, &val) == 2)
1606             {
1607               printf_filtered ("[%02x] %-15s : %02x\n", k, query, val);
1608               while ((*p != ';') && (*p != '\0'))
1609                 p++;
1610               p++;              /* skip over ';' */
1611               if (*p == '\0')
1612                 break;
1613             }
1614         }
1615
1616       xfree (buf);
1617     }
1618 }
1619
1620 extern initialize_file_ftype _initialize_avr_tdep; /* -Wmissing-prototypes */
1621
1622 void
1623 _initialize_avr_tdep (void)
1624 {
1625   register_gdbarch_init (bfd_arch_avr, avr_gdbarch_init);
1626
1627   /* Add a new command to allow the user to query the avr remote target for
1628      the values of the io space registers in a saner way than just using
1629      `x/NNNb ADDR`.  */
1630
1631   /* FIXME: TRoth/2002-02-18: This should probably be changed to 'info avr
1632      io_registers' to signify it is not available on other platforms.  */
1633
1634   add_info ("io_registers", avr_io_reg_read_command,
1635             _("query remote avr target for io space register values"));
1636 }