* i386-tdep.c (i386_skip_noop): New function.
[platform/upstream/binutils.git] / gdb / i386-tdep.c
1 /* Intel 386 target-dependent stuff.
2
3    Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
4    1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
5    Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "arch-utils.h"
24 #include "command.h"
25 #include "dummy-frame.h"
26 #include "dwarf2-frame.h"
27 #include "doublest.h"
28 #include "frame.h"
29 #include "frame-base.h"
30 #include "frame-unwind.h"
31 #include "inferior.h"
32 #include "gdbcmd.h"
33 #include "gdbcore.h"
34 #include "gdbtypes.h"
35 #include "objfiles.h"
36 #include "osabi.h"
37 #include "regcache.h"
38 #include "reggroups.h"
39 #include "regset.h"
40 #include "symfile.h"
41 #include "symtab.h"
42 #include "target.h"
43 #include "value.h"
44 #include "dis-asm.h"
45
46 #include "gdb_assert.h"
47 #include "gdb_string.h"
48
49 #include "i386-tdep.h"
50 #include "i387-tdep.h"
51
52 /* Register names.  */
53
54 static char *i386_register_names[] =
55 {
56   "eax",   "ecx",    "edx",   "ebx",
57   "esp",   "ebp",    "esi",   "edi",
58   "eip",   "eflags", "cs",    "ss",
59   "ds",    "es",     "fs",    "gs",
60   "st0",   "st1",    "st2",   "st3",
61   "st4",   "st5",    "st6",   "st7",
62   "fctrl", "fstat",  "ftag",  "fiseg",
63   "fioff", "foseg",  "fooff", "fop",
64   "xmm0",  "xmm1",   "xmm2",  "xmm3",
65   "xmm4",  "xmm5",   "xmm6",  "xmm7",
66   "mxcsr"
67 };
68
69 static const int i386_num_register_names = ARRAY_SIZE (i386_register_names);
70
71 /* Register names for MMX pseudo-registers.  */
72
73 static char *i386_mmx_names[] =
74 {
75   "mm0", "mm1", "mm2", "mm3",
76   "mm4", "mm5", "mm6", "mm7"
77 };
78
79 static const int i386_num_mmx_regs = ARRAY_SIZE (i386_mmx_names);
80
81 static int
82 i386_mmx_regnum_p (struct gdbarch *gdbarch, int regnum)
83 {
84   int mm0_regnum = gdbarch_tdep (gdbarch)->mm0_regnum;
85
86   if (mm0_regnum < 0)
87     return 0;
88
89   return (regnum >= mm0_regnum && regnum < mm0_regnum + i386_num_mmx_regs);
90 }
91
92 /* SSE register?  */
93
94 static int
95 i386_sse_regnum_p (struct gdbarch *gdbarch, int regnum)
96 {
97   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
98
99 #define I387_ST0_REGNUM tdep->st0_regnum
100 #define I387_NUM_XMM_REGS tdep->num_xmm_regs
101
102   if (I387_NUM_XMM_REGS == 0)
103     return 0;
104
105   return (I387_XMM0_REGNUM <= regnum && regnum < I387_MXCSR_REGNUM);
106
107 #undef I387_ST0_REGNUM
108 #undef I387_NUM_XMM_REGS
109 }
110
111 static int
112 i386_mxcsr_regnum_p (struct gdbarch *gdbarch, int regnum)
113 {
114   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
115
116 #define I387_ST0_REGNUM tdep->st0_regnum
117 #define I387_NUM_XMM_REGS tdep->num_xmm_regs
118
119   if (I387_NUM_XMM_REGS == 0)
120     return 0;
121
122   return (regnum == I387_MXCSR_REGNUM);
123
124 #undef I387_ST0_REGNUM
125 #undef I387_NUM_XMM_REGS
126 }
127
128 #define I387_ST0_REGNUM (gdbarch_tdep (current_gdbarch)->st0_regnum)
129 #define I387_MM0_REGNUM (gdbarch_tdep (current_gdbarch)->mm0_regnum)
130 #define I387_NUM_XMM_REGS (gdbarch_tdep (current_gdbarch)->num_xmm_regs)
131
132 /* FP register?  */
133
134 int
135 i386_fp_regnum_p (int regnum)
136 {
137   if (I387_ST0_REGNUM < 0)
138     return 0;
139
140   return (I387_ST0_REGNUM <= regnum && regnum < I387_FCTRL_REGNUM);
141 }
142
143 int
144 i386_fpc_regnum_p (int regnum)
145 {
146   if (I387_ST0_REGNUM < 0)
147     return 0;
148
149   return (I387_FCTRL_REGNUM <= regnum && regnum < I387_XMM0_REGNUM);
150 }
151
152 /* Return the name of register REGNUM.  */
153
154 const char *
155 i386_register_name (struct gdbarch *gdbarch, int regnum)
156 {
157   if (i386_mmx_regnum_p (gdbarch, regnum))
158     return i386_mmx_names[regnum - I387_MM0_REGNUM];
159
160   if (regnum >= 0 && regnum < i386_num_register_names)
161     return i386_register_names[regnum];
162
163   return NULL;
164 }
165
166 /* Convert a dbx register number REG to the appropriate register
167    number used by GDB.  */
168
169 static int
170 i386_dbx_reg_to_regnum (struct gdbarch *gdbarch, int reg)
171 {
172   /* This implements what GCC calls the "default" register map
173      (dbx_register_map[]).  */
174
175   if (reg >= 0 && reg <= 7)
176     {
177       /* General-purpose registers.  The debug info calls %ebp
178          register 4, and %esp register 5.  */
179       if (reg == 4)
180         return 5;
181       else if (reg == 5)
182         return 4;
183       else return reg;
184     }
185   else if (reg >= 12 && reg <= 19)
186     {
187       /* Floating-point registers.  */
188       return reg - 12 + I387_ST0_REGNUM;
189     }
190   else if (reg >= 21 && reg <= 28)
191     {
192       /* SSE registers.  */
193       return reg - 21 + I387_XMM0_REGNUM;
194     }
195   else if (reg >= 29 && reg <= 36)
196     {
197       /* MMX registers.  */
198       return reg - 29 + I387_MM0_REGNUM;
199     }
200
201   /* This will hopefully provoke a warning.  */
202   return gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
203 }
204
205 /* Convert SVR4 register number REG to the appropriate register number
206    used by GDB.  */
207
208 static int
209 i386_svr4_reg_to_regnum (struct gdbarch *gdbarch, int reg)
210 {
211   /* This implements the GCC register map that tries to be compatible
212      with the SVR4 C compiler for DWARF (svr4_dbx_register_map[]).  */
213
214   /* The SVR4 register numbering includes %eip and %eflags, and
215      numbers the floating point registers differently.  */
216   if (reg >= 0 && reg <= 9)
217     {
218       /* General-purpose registers.  */
219       return reg;
220     }
221   else if (reg >= 11 && reg <= 18)
222     {
223       /* Floating-point registers.  */
224       return reg - 11 + I387_ST0_REGNUM;
225     }
226   else if (reg >= 21 && reg <= 36)
227     {
228       /* The SSE and MMX registers have the same numbers as with dbx.  */
229       return i386_dbx_reg_to_regnum (gdbarch, reg);
230     }
231
232   switch (reg)
233     {
234     case 37: return I387_FCTRL_REGNUM;
235     case 38: return I387_FSTAT_REGNUM;
236     case 39: return I387_MXCSR_REGNUM;
237     case 40: return I386_ES_REGNUM;
238     case 41: return I386_CS_REGNUM;
239     case 42: return I386_SS_REGNUM;
240     case 43: return I386_DS_REGNUM;
241     case 44: return I386_FS_REGNUM;
242     case 45: return I386_GS_REGNUM;
243     }
244
245   /* This will hopefully provoke a warning.  */
246   return gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
247 }
248
249 #undef I387_ST0_REGNUM
250 #undef I387_MM0_REGNUM
251 #undef I387_NUM_XMM_REGS
252 \f
253
254 /* This is the variable that is set with "set disassembly-flavor", and
255    its legitimate values.  */
256 static const char att_flavor[] = "att";
257 static const char intel_flavor[] = "intel";
258 static const char *valid_flavors[] =
259 {
260   att_flavor,
261   intel_flavor,
262   NULL
263 };
264 static const char *disassembly_flavor = att_flavor;
265 \f
266
267 /* Use the program counter to determine the contents and size of a
268    breakpoint instruction.  Return a pointer to a string of bytes that
269    encode a breakpoint instruction, store the length of the string in
270    *LEN and optionally adjust *PC to point to the correct memory
271    location for inserting the breakpoint.
272
273    On the i386 we have a single breakpoint that fits in a single byte
274    and can be inserted anywhere.
275
276    This function is 64-bit safe.  */
277
278 static const gdb_byte *
279 i386_breakpoint_from_pc (struct gdbarch *gdbarch, CORE_ADDR *pc, int *len)
280 {
281   static gdb_byte break_insn[] = { 0xcc }; /* int 3 */
282
283   *len = sizeof (break_insn);
284   return break_insn;
285 }
286 \f
287 #ifdef I386_REGNO_TO_SYMMETRY
288 #error "The Sequent Symmetry is no longer supported."
289 #endif
290
291 /* According to the System V ABI, the registers %ebp, %ebx, %edi, %esi
292    and %esp "belong" to the calling function.  Therefore these
293    registers should be saved if they're going to be modified.  */
294
295 /* The maximum number of saved registers.  This should include all
296    registers mentioned above, and %eip.  */
297 #define I386_NUM_SAVED_REGS     I386_NUM_GREGS
298
299 struct i386_frame_cache
300 {
301   /* Base address.  */
302   CORE_ADDR base;
303   LONGEST sp_offset;
304   CORE_ADDR pc;
305
306   /* Saved registers.  */
307   CORE_ADDR saved_regs[I386_NUM_SAVED_REGS];
308   CORE_ADDR saved_sp;
309   int stack_align;
310   int pc_in_eax;
311
312   /* Stack space reserved for local variables.  */
313   long locals;
314 };
315
316 /* Allocate and initialize a frame cache.  */
317
318 static struct i386_frame_cache *
319 i386_alloc_frame_cache (void)
320 {
321   struct i386_frame_cache *cache;
322   int i;
323
324   cache = FRAME_OBSTACK_ZALLOC (struct i386_frame_cache);
325
326   /* Base address.  */
327   cache->base = 0;
328   cache->sp_offset = -4;
329   cache->pc = 0;
330
331   /* Saved registers.  We initialize these to -1 since zero is a valid
332      offset (that's where %ebp is supposed to be stored).  */
333   for (i = 0; i < I386_NUM_SAVED_REGS; i++)
334     cache->saved_regs[i] = -1;
335   cache->saved_sp = 0;
336   cache->stack_align = 0;
337   cache->pc_in_eax = 0;
338
339   /* Frameless until proven otherwise.  */
340   cache->locals = -1;
341
342   return cache;
343 }
344
345 /* If the instruction at PC is a jump, return the address of its
346    target.  Otherwise, return PC.  */
347
348 static CORE_ADDR
349 i386_follow_jump (CORE_ADDR pc)
350 {
351   gdb_byte op;
352   long delta = 0;
353   int data16 = 0;
354
355   read_memory_nobpt (pc, &op, 1);
356   if (op == 0x66)
357     {
358       data16 = 1;
359       op = read_memory_unsigned_integer (pc + 1, 1);
360     }
361
362   switch (op)
363     {
364     case 0xe9:
365       /* Relative jump: if data16 == 0, disp32, else disp16.  */
366       if (data16)
367         {
368           delta = read_memory_integer (pc + 2, 2);
369
370           /* Include the size of the jmp instruction (including the
371              0x66 prefix).  */
372           delta += 4;
373         }
374       else
375         {
376           delta = read_memory_integer (pc + 1, 4);
377
378           /* Include the size of the jmp instruction.  */
379           delta += 5;
380         }
381       break;
382     case 0xeb:
383       /* Relative jump, disp8 (ignore data16).  */
384       delta = read_memory_integer (pc + data16 + 1, 1);
385
386       delta += data16 + 2;
387       break;
388     }
389
390   return pc + delta;
391 }
392
393 /* Check whether PC points at a prologue for a function returning a
394    structure or union.  If so, it updates CACHE and returns the
395    address of the first instruction after the code sequence that
396    removes the "hidden" argument from the stack or CURRENT_PC,
397    whichever is smaller.  Otherwise, return PC.  */
398
399 static CORE_ADDR
400 i386_analyze_struct_return (CORE_ADDR pc, CORE_ADDR current_pc,
401                             struct i386_frame_cache *cache)
402 {
403   /* Functions that return a structure or union start with:
404
405         popl %eax             0x58
406         xchgl %eax, (%esp)    0x87 0x04 0x24
407      or xchgl %eax, 0(%esp)   0x87 0x44 0x24 0x00
408
409      (the System V compiler puts out the second `xchg' instruction,
410      and the assembler doesn't try to optimize it, so the 'sib' form
411      gets generated).  This sequence is used to get the address of the
412      return buffer for a function that returns a structure.  */
413   static gdb_byte proto1[3] = { 0x87, 0x04, 0x24 };
414   static gdb_byte proto2[4] = { 0x87, 0x44, 0x24, 0x00 };
415   gdb_byte buf[4];
416   gdb_byte op;
417
418   if (current_pc <= pc)
419     return pc;
420
421   read_memory_nobpt (pc, &op, 1);
422
423   if (op != 0x58)               /* popl %eax */
424     return pc;
425
426   read_memory_nobpt (pc + 1, buf, 4);
427   if (memcmp (buf, proto1, 3) != 0 && memcmp (buf, proto2, 4) != 0)
428     return pc;
429
430   if (current_pc == pc)
431     {
432       cache->sp_offset += 4;
433       return current_pc;
434     }
435
436   if (current_pc == pc + 1)
437     {
438       cache->pc_in_eax = 1;
439       return current_pc;
440     }
441   
442   if (buf[1] == proto1[1])
443     return pc + 4;
444   else
445     return pc + 5;
446 }
447
448 static CORE_ADDR
449 i386_skip_probe (CORE_ADDR pc)
450 {
451   /* A function may start with
452
453         pushl constant
454         call _probe
455         addl $4, %esp
456            
457      followed by
458
459         pushl %ebp
460
461      etc.  */
462   gdb_byte buf[8];
463   gdb_byte op;
464
465   read_memory_nobpt (pc, &op, 1);
466
467   if (op == 0x68 || op == 0x6a)
468     {
469       int delta;
470
471       /* Skip past the `pushl' instruction; it has either a one-byte or a
472          four-byte operand, depending on the opcode.  */
473       if (op == 0x68)
474         delta = 5;
475       else
476         delta = 2;
477
478       /* Read the following 8 bytes, which should be `call _probe' (6
479          bytes) followed by `addl $4,%esp' (2 bytes).  */
480       read_memory (pc + delta, buf, sizeof (buf));
481       if (buf[0] == 0xe8 && buf[6] == 0xc4 && buf[7] == 0x4)
482         pc += delta + sizeof (buf);
483     }
484
485   return pc;
486 }
487
488 /* GCC 4.1 and later, can put code in the prologue to realign the
489    stack pointer.  Check whether PC points to such code, and update
490    CACHE accordingly.  Return the first instruction after the code
491    sequence or CURRENT_PC, whichever is smaller.  If we don't
492    recognize the code, return PC.  */
493
494 static CORE_ADDR
495 i386_analyze_stack_align (CORE_ADDR pc, CORE_ADDR current_pc,
496                           struct i386_frame_cache *cache)
497 {
498   /* The register used by the compiler to perform the stack re-alignment 
499      is, in order of preference, either %ecx, %edx, or %eax.  GCC should
500      never use %ebx as it always treats it as callee-saved, whereas
501      the compiler can only use caller-saved registers.  */
502   static const gdb_byte insns_ecx[10] = { 
503     0x8d, 0x4c, 0x24, 0x04,     /* leal  4(%esp), %ecx */
504     0x83, 0xe4, 0xf0,           /* andl  $-16, %esp */
505     0xff, 0x71, 0xfc            /* pushl -4(%ecx) */
506   };
507   static const gdb_byte insns_edx[10] = { 
508     0x8d, 0x54, 0x24, 0x04,     /* leal  4(%esp), %edx */
509     0x83, 0xe4, 0xf0,           /* andl  $-16, %esp */
510     0xff, 0x72, 0xfc            /* pushl -4(%edx) */
511   };
512   static const gdb_byte insns_eax[10] = { 
513     0x8d, 0x44, 0x24, 0x04,     /* leal  4(%esp), %eax */
514     0x83, 0xe4, 0xf0,           /* andl  $-16, %esp */
515     0xff, 0x70, 0xfc            /* pushl -4(%eax) */
516   };
517   gdb_byte buf[10];
518
519   if (target_read_memory (pc, buf, sizeof buf)
520       || (memcmp (buf, insns_ecx, sizeof buf) != 0
521           && memcmp (buf, insns_edx, sizeof buf) != 0
522           && memcmp (buf, insns_eax, sizeof buf) != 0))
523     return pc;
524
525   if (current_pc > pc + 4)
526     cache->stack_align = 1;
527
528   return min (pc + 10, current_pc);
529 }
530
531 /* Maximum instruction length we need to handle.  */
532 #define I386_MAX_INSN_LEN       6
533
534 /* Instruction description.  */
535 struct i386_insn
536 {
537   size_t len;
538   gdb_byte insn[I386_MAX_INSN_LEN];
539   gdb_byte mask[I386_MAX_INSN_LEN];
540 };
541
542 /* Search for the instruction at PC in the list SKIP_INSNS.  Return
543    the first instruction description that matches.  Otherwise, return
544    NULL.  */
545
546 static struct i386_insn *
547 i386_match_insn (CORE_ADDR pc, struct i386_insn *skip_insns)
548 {
549   struct i386_insn *insn;
550   gdb_byte op;
551
552   read_memory_nobpt (pc, &op, 1);
553
554   for (insn = skip_insns; insn->len > 0; insn++)
555     {
556       if ((op & insn->mask[0]) == insn->insn[0])
557         {
558           gdb_byte buf[I386_MAX_INSN_LEN - 1];
559           int insn_matched = 1;
560           size_t i;
561
562           gdb_assert (insn->len > 1);
563           gdb_assert (insn->len <= I386_MAX_INSN_LEN);
564
565           read_memory_nobpt (pc + 1, buf, insn->len - 1);
566           for (i = 1; i < insn->len; i++)
567             {
568               if ((buf[i - 1] & insn->mask[i]) != insn->insn[i])
569                 insn_matched = 0;
570             }
571
572           if (insn_matched)
573             return insn;
574         }
575     }
576
577   return NULL;
578 }
579
580 /* Some special instructions that might be migrated by GCC into the
581    part of the prologue that sets up the new stack frame.  Because the
582    stack frame hasn't been setup yet, no registers have been saved
583    yet, and only the scratch registers %eax, %ecx and %edx can be
584    touched.  */
585
586 struct i386_insn i386_frame_setup_skip_insns[] =
587 {
588   /* Check for `movb imm8, r' and `movl imm32, r'. 
589     
590      ??? Should we handle 16-bit operand-sizes here?  */
591
592   /* `movb imm8, %al' and `movb imm8, %ah' */
593   /* `movb imm8, %cl' and `movb imm8, %ch' */
594   { 2, { 0xb0, 0x00 }, { 0xfa, 0x00 } },
595   /* `movb imm8, %dl' and `movb imm8, %dh' */
596   { 2, { 0xb2, 0x00 }, { 0xfb, 0x00 } },
597   /* `movl imm32, %eax' and `movl imm32, %ecx' */
598   { 5, { 0xb8 }, { 0xfe } },
599   /* `movl imm32, %edx' */
600   { 5, { 0xba }, { 0xff } },
601
602   /* Check for `mov imm32, r32'.  Note that there is an alternative
603      encoding for `mov m32, %eax'.
604
605      ??? Should we handle SIB adressing here?
606      ??? Should we handle 16-bit operand-sizes here?  */
607
608   /* `movl m32, %eax' */
609   { 5, { 0xa1 }, { 0xff } },
610   /* `movl m32, %eax' and `mov; m32, %ecx' */
611   { 6, { 0x89, 0x05 }, {0xff, 0xf7 } },
612   /* `movl m32, %edx' */
613   { 6, { 0x89, 0x15 }, {0xff, 0xff } },
614
615   /* Check for `xorl r32, r32' and the equivalent `subl r32, r32'.
616      Because of the symmetry, there are actually two ways to encode
617      these instructions; opcode bytes 0x29 and 0x2b for `subl' and
618      opcode bytes 0x31 and 0x33 for `xorl'.  */
619
620   /* `subl %eax, %eax' */
621   { 2, { 0x29, 0xc0 }, { 0xfd, 0xff } },
622   /* `subl %ecx, %ecx' */
623   { 2, { 0x29, 0xc9 }, { 0xfd, 0xff } },
624   /* `subl %edx, %edx' */
625   { 2, { 0x29, 0xd2 }, { 0xfd, 0xff } },
626   /* `xorl %eax, %eax' */
627   { 2, { 0x31, 0xc0 }, { 0xfd, 0xff } },
628   /* `xorl %ecx, %ecx' */
629   { 2, { 0x31, 0xc9 }, { 0xfd, 0xff } },
630   /* `xorl %edx, %edx' */
631   { 2, { 0x31, 0xd2 }, { 0xfd, 0xff } },
632   { 0 }
633 };
634
635
636 /* Check whether PC points to a no-op instruction.  */
637 static CORE_ADDR
638 i386_skip_noop (CORE_ADDR pc)
639 {
640   gdb_byte op;
641   int check = 1;
642
643   read_memory_nobpt (pc, &op, 1);
644
645   while (check) 
646     {
647       check = 0;
648       /* Ignore `nop' instruction.  */
649       if (op == 0x90) 
650         {
651           pc += 1;
652           read_memory_nobpt (pc, &op, 1);
653           check = 1;
654         }
655       /* Ignore no-op instruction `mov %edi, %edi'.
656          Microsoft system dlls often start with
657          a `mov %edi,%edi' instruction.
658          The 5 bytes before the function start are
659          filled with `nop' instructions.
660          This pattern can be used for hot-patching:
661          The `mov %edi, %edi' instruction can be replaced by a
662          near jump to the location of the 5 `nop' instructions
663          which can be replaced by a 32-bit jump to anywhere
664          in the 32-bit address space.  */
665
666       else if (op == 0x8b)
667         {
668           read_memory_nobpt (pc + 1, &op, 1);
669           if (op == 0xff)
670             {
671               pc += 2;
672               read_memory_nobpt (pc, &op, 1);
673               check = 1;
674             }
675         }
676     }
677   return pc; 
678 }
679
680 /* Check whether PC points at a code that sets up a new stack frame.
681    If so, it updates CACHE and returns the address of the first
682    instruction after the sequence that sets up the frame or LIMIT,
683    whichever is smaller.  If we don't recognize the code, return PC.  */
684
685 static CORE_ADDR
686 i386_analyze_frame_setup (CORE_ADDR pc, CORE_ADDR limit,
687                           struct i386_frame_cache *cache)
688 {
689   struct i386_insn *insn;
690   gdb_byte op;
691   int skip = 0;
692
693   if (limit <= pc)
694     return limit;
695
696   read_memory_nobpt (pc, &op, 1);
697
698   if (op == 0x55)               /* pushl %ebp */
699     {
700       /* Take into account that we've executed the `pushl %ebp' that
701          starts this instruction sequence.  */
702       cache->saved_regs[I386_EBP_REGNUM] = 0;
703       cache->sp_offset += 4;
704       pc++;
705
706       /* If that's all, return now.  */
707       if (limit <= pc)
708         return limit;
709
710       /* Check for some special instructions that might be migrated by
711          GCC into the prologue and skip them.  At this point in the
712          prologue, code should only touch the scratch registers %eax,
713          %ecx and %edx, so while the number of posibilities is sheer,
714          it is limited.
715
716          Make sure we only skip these instructions if we later see the
717          `movl %esp, %ebp' that actually sets up the frame.  */
718       while (pc + skip < limit)
719         {
720           insn = i386_match_insn (pc + skip, i386_frame_setup_skip_insns);
721           if (insn == NULL)
722             break;
723
724           skip += insn->len;
725         }
726
727       /* If that's all, return now.  */
728       if (limit <= pc + skip)
729         return limit;
730
731       read_memory_nobpt (pc + skip, &op, 1);
732
733       /* Check for `movl %esp, %ebp' -- can be written in two ways.  */
734       switch (op)
735         {
736         case 0x8b:
737           if (read_memory_unsigned_integer (pc + skip + 1, 1) != 0xec)
738             return pc;
739           break;
740         case 0x89:
741           if (read_memory_unsigned_integer (pc + skip + 1, 1) != 0xe5)
742             return pc;
743           break;
744         default:
745           return pc;
746         }
747
748       /* OK, we actually have a frame.  We just don't know how large
749          it is yet.  Set its size to zero.  We'll adjust it if
750          necessary.  We also now commit to skipping the special
751          instructions mentioned before.  */
752       cache->locals = 0;
753       pc += (skip + 2);
754
755       /* If that's all, return now.  */
756       if (limit <= pc)
757         return limit;
758
759       /* Check for stack adjustment 
760
761             subl $XXX, %esp
762
763          NOTE: You can't subtract a 16-bit immediate from a 32-bit
764          reg, so we don't have to worry about a data16 prefix.  */
765       read_memory_nobpt (pc, &op, 1);
766       if (op == 0x83)
767         {
768           /* `subl' with 8-bit immediate.  */
769           if (read_memory_unsigned_integer (pc + 1, 1) != 0xec)
770             /* Some instruction starting with 0x83 other than `subl'.  */
771             return pc;
772
773           /* `subl' with signed 8-bit immediate (though it wouldn't
774              make sense to be negative).  */
775           cache->locals = read_memory_integer (pc + 2, 1);
776           return pc + 3;
777         }
778       else if (op == 0x81)
779         {
780           /* Maybe it is `subl' with a 32-bit immediate.  */
781           if (read_memory_unsigned_integer (pc + 1, 1) != 0xec)
782             /* Some instruction starting with 0x81 other than `subl'.  */
783             return pc;
784
785           /* It is `subl' with a 32-bit immediate.  */
786           cache->locals = read_memory_integer (pc + 2, 4);
787           return pc + 6;
788         }
789       else
790         {
791           /* Some instruction other than `subl'.  */
792           return pc;
793         }
794     }
795   else if (op == 0xc8)          /* enter */
796     {
797       cache->locals = read_memory_unsigned_integer (pc + 1, 2);
798       return pc + 4;
799     }
800
801   return pc;
802 }
803
804 /* Check whether PC points at code that saves registers on the stack.
805    If so, it updates CACHE and returns the address of the first
806    instruction after the register saves or CURRENT_PC, whichever is
807    smaller.  Otherwise, return PC.  */
808
809 static CORE_ADDR
810 i386_analyze_register_saves (CORE_ADDR pc, CORE_ADDR current_pc,
811                              struct i386_frame_cache *cache)
812 {
813   CORE_ADDR offset = 0;
814   gdb_byte op;
815   int i;
816
817   if (cache->locals > 0)
818     offset -= cache->locals;
819   for (i = 0; i < 8 && pc < current_pc; i++)
820     {
821       read_memory_nobpt (pc, &op, 1);
822       if (op < 0x50 || op > 0x57)
823         break;
824
825       offset -= 4;
826       cache->saved_regs[op - 0x50] = offset;
827       cache->sp_offset += 4;
828       pc++;
829     }
830
831   return pc;
832 }
833
834 /* Do a full analysis of the prologue at PC and update CACHE
835    accordingly.  Bail out early if CURRENT_PC is reached.  Return the
836    address where the analysis stopped.
837
838    We handle these cases:
839
840    The startup sequence can be at the start of the function, or the
841    function can start with a branch to startup code at the end.
842
843    %ebp can be set up with either the 'enter' instruction, or "pushl
844    %ebp, movl %esp, %ebp" (`enter' is too slow to be useful, but was
845    once used in the System V compiler).
846
847    Local space is allocated just below the saved %ebp by either the
848    'enter' instruction, or by "subl $<size>, %esp".  'enter' has a
849    16-bit unsigned argument for space to allocate, and the 'addl'
850    instruction could have either a signed byte, or 32-bit immediate.
851
852    Next, the registers used by this function are pushed.  With the
853    System V compiler they will always be in the order: %edi, %esi,
854    %ebx (and sometimes a harmless bug causes it to also save but not
855    restore %eax); however, the code below is willing to see the pushes
856    in any order, and will handle up to 8 of them.
857  
858    If the setup sequence is at the end of the function, then the next
859    instruction will be a branch back to the start.  */
860
861 static CORE_ADDR
862 i386_analyze_prologue (CORE_ADDR pc, CORE_ADDR current_pc,
863                        struct i386_frame_cache *cache)
864 {
865   pc = i386_skip_noop (pc);
866   pc = i386_follow_jump (pc);
867   pc = i386_analyze_struct_return (pc, current_pc, cache);
868   pc = i386_skip_probe (pc);
869   pc = i386_analyze_stack_align (pc, current_pc, cache);
870   pc = i386_analyze_frame_setup (pc, current_pc, cache);
871   return i386_analyze_register_saves (pc, current_pc, cache);
872 }
873
874 /* Return PC of first real instruction.  */
875
876 static CORE_ADDR
877 i386_skip_prologue (struct gdbarch *gdbarch, CORE_ADDR start_pc)
878 {
879   static gdb_byte pic_pat[6] =
880   {
881     0xe8, 0, 0, 0, 0,           /* call 0x0 */
882     0x5b,                       /* popl %ebx */
883   };
884   struct i386_frame_cache cache;
885   CORE_ADDR pc;
886   gdb_byte op;
887   int i;
888
889   cache.locals = -1;
890   pc = i386_analyze_prologue (start_pc, 0xffffffff, &cache);
891   if (cache.locals < 0)
892     return start_pc;
893
894   /* Found valid frame setup.  */
895
896   /* The native cc on SVR4 in -K PIC mode inserts the following code
897      to get the address of the global offset table (GOT) into register
898      %ebx:
899
900         call    0x0
901         popl    %ebx
902         movl    %ebx,x(%ebp)    (optional)
903         addl    y,%ebx
904
905      This code is with the rest of the prologue (at the end of the
906      function), so we have to skip it to get to the first real
907      instruction at the start of the function.  */
908
909   for (i = 0; i < 6; i++)
910     {
911       read_memory_nobpt (pc + i, &op, 1);
912       if (pic_pat[i] != op)
913         break;
914     }
915   if (i == 6)
916     {
917       int delta = 6;
918
919       read_memory_nobpt (pc + delta, &op, 1);
920
921       if (op == 0x89)           /* movl %ebx, x(%ebp) */
922         {
923           op = read_memory_unsigned_integer (pc + delta + 1, 1);
924
925           if (op == 0x5d)       /* One byte offset from %ebp.  */
926             delta += 3;
927           else if (op == 0x9d)  /* Four byte offset from %ebp.  */
928             delta += 6;
929           else                  /* Unexpected instruction.  */
930             delta = 0;
931
932           read_memory_nobpt (pc + delta, &op, 1);
933         }
934
935       /* addl y,%ebx */
936       if (delta > 0 && op == 0x81
937           && read_memory_unsigned_integer (pc + delta + 1, 1) == 0xc3)
938         {
939           pc += delta + 6;
940         }
941     }
942
943   /* If the function starts with a branch (to startup code at the end)
944      the last instruction should bring us back to the first
945      instruction of the real code.  */
946   if (i386_follow_jump (start_pc) != start_pc)
947     pc = i386_follow_jump (pc);
948
949   return pc;
950 }
951
952 /* This function is 64-bit safe.  */
953
954 static CORE_ADDR
955 i386_unwind_pc (struct gdbarch *gdbarch, struct frame_info *next_frame)
956 {
957   gdb_byte buf[8];
958
959   frame_unwind_register (next_frame, gdbarch_pc_regnum (gdbarch), buf);
960   return extract_typed_address (buf, builtin_type_void_func_ptr);
961 }
962 \f
963
964 /* Normal frames.  */
965
966 static struct i386_frame_cache *
967 i386_frame_cache (struct frame_info *next_frame, void **this_cache)
968 {
969   struct i386_frame_cache *cache;
970   gdb_byte buf[4];
971   int i;
972
973   if (*this_cache)
974     return *this_cache;
975
976   cache = i386_alloc_frame_cache ();
977   *this_cache = cache;
978
979   /* In principle, for normal frames, %ebp holds the frame pointer,
980      which holds the base address for the current stack frame.
981      However, for functions that don't need it, the frame pointer is
982      optional.  For these "frameless" functions the frame pointer is
983      actually the frame pointer of the calling frame.  Signal
984      trampolines are just a special case of a "frameless" function.
985      They (usually) share their frame pointer with the frame that was
986      in progress when the signal occurred.  */
987
988   frame_unwind_register (next_frame, I386_EBP_REGNUM, buf);
989   cache->base = extract_unsigned_integer (buf, 4);
990   if (cache->base == 0)
991     return cache;
992
993   /* For normal frames, %eip is stored at 4(%ebp).  */
994   cache->saved_regs[I386_EIP_REGNUM] = 4;
995
996   cache->pc = frame_func_unwind (next_frame, NORMAL_FRAME);
997   if (cache->pc != 0)
998     i386_analyze_prologue (cache->pc, frame_pc_unwind (next_frame), cache);
999
1000   if (cache->stack_align)
1001     {
1002       /* Saved stack pointer has been saved in %ecx.  */
1003       frame_unwind_register (next_frame, I386_ECX_REGNUM, buf);
1004       cache->saved_sp = extract_unsigned_integer(buf, 4);
1005     }
1006
1007   if (cache->locals < 0)
1008     {
1009       /* We didn't find a valid frame, which means that CACHE->base
1010          currently holds the frame pointer for our calling frame.  If
1011          we're at the start of a function, or somewhere half-way its
1012          prologue, the function's frame probably hasn't been fully
1013          setup yet.  Try to reconstruct the base address for the stack
1014          frame by looking at the stack pointer.  For truly "frameless"
1015          functions this might work too.  */
1016
1017       if (cache->stack_align)
1018         {
1019           /* We're halfway aligning the stack.  */
1020           cache->base = ((cache->saved_sp - 4) & 0xfffffff0) - 4;
1021           cache->saved_regs[I386_EIP_REGNUM] = cache->saved_sp - 4;
1022
1023           /* This will be added back below.  */
1024           cache->saved_regs[I386_EIP_REGNUM] -= cache->base;
1025         }
1026       else
1027         {
1028           frame_unwind_register (next_frame, I386_ESP_REGNUM, buf);
1029           cache->base = extract_unsigned_integer (buf, 4) + cache->sp_offset;
1030         }
1031     }
1032
1033   /* Now that we have the base address for the stack frame we can
1034      calculate the value of %esp in the calling frame.  */
1035   if (cache->saved_sp == 0)
1036     cache->saved_sp = cache->base + 8;
1037
1038   /* Adjust all the saved registers such that they contain addresses
1039      instead of offsets.  */
1040   for (i = 0; i < I386_NUM_SAVED_REGS; i++)
1041     if (cache->saved_regs[i] != -1)
1042       cache->saved_regs[i] += cache->base;
1043
1044   return cache;
1045 }
1046
1047 static void
1048 i386_frame_this_id (struct frame_info *next_frame, void **this_cache,
1049                     struct frame_id *this_id)
1050 {
1051   struct i386_frame_cache *cache = i386_frame_cache (next_frame, this_cache);
1052
1053   /* This marks the outermost frame.  */
1054   if (cache->base == 0)
1055     return;
1056
1057   /* See the end of i386_push_dummy_call.  */
1058   (*this_id) = frame_id_build (cache->base + 8, cache->pc);
1059 }
1060
1061 static void
1062 i386_frame_prev_register (struct frame_info *next_frame, void **this_cache,
1063                           int regnum, int *optimizedp,
1064                           enum lval_type *lvalp, CORE_ADDR *addrp,
1065                           int *realnump, gdb_byte *valuep)
1066 {
1067   struct i386_frame_cache *cache = i386_frame_cache (next_frame, this_cache);
1068
1069   gdb_assert (regnum >= 0);
1070
1071   /* The System V ABI says that:
1072
1073      "The flags register contains the system flags, such as the
1074      direction flag and the carry flag.  The direction flag must be
1075      set to the forward (that is, zero) direction before entry and
1076      upon exit from a function.  Other user flags have no specified
1077      role in the standard calling sequence and are not preserved."
1078
1079      To guarantee the "upon exit" part of that statement we fake a
1080      saved flags register that has its direction flag cleared.
1081
1082      Note that GCC doesn't seem to rely on the fact that the direction
1083      flag is cleared after a function return; it always explicitly
1084      clears the flag before operations where it matters.
1085
1086      FIXME: kettenis/20030316: I'm not quite sure whether this is the
1087      right thing to do.  The way we fake the flags register here makes
1088      it impossible to change it.  */
1089
1090   if (regnum == I386_EFLAGS_REGNUM)
1091     {
1092       *optimizedp = 0;
1093       *lvalp = not_lval;
1094       *addrp = 0;
1095       *realnump = -1;
1096       if (valuep)
1097         {
1098           ULONGEST val;
1099
1100           /* Clear the direction flag.  */
1101           val = frame_unwind_register_unsigned (next_frame,
1102                                                 I386_EFLAGS_REGNUM);
1103           val &= ~(1 << 10);
1104           store_unsigned_integer (valuep, 4, val);
1105         }
1106
1107       return;
1108     }
1109
1110   if (regnum == I386_EIP_REGNUM && cache->pc_in_eax)
1111     {
1112       *optimizedp = 0;
1113       *lvalp = lval_register;
1114       *addrp = 0;
1115       *realnump = I386_EAX_REGNUM;
1116       if (valuep)
1117         frame_unwind_register (next_frame, (*realnump), valuep);
1118       return;
1119     }
1120
1121   if (regnum == I386_ESP_REGNUM && cache->saved_sp)
1122     {
1123       *optimizedp = 0;
1124       *lvalp = not_lval;
1125       *addrp = 0;
1126       *realnump = -1;
1127       if (valuep)
1128         {
1129           /* Store the value.  */
1130           store_unsigned_integer (valuep, 4, cache->saved_sp);
1131         }
1132       return;
1133     }
1134
1135   if (regnum < I386_NUM_SAVED_REGS && cache->saved_regs[regnum] != -1)
1136     {
1137       *optimizedp = 0;
1138       *lvalp = lval_memory;
1139       *addrp = cache->saved_regs[regnum];
1140       *realnump = -1;
1141       if (valuep)
1142         {
1143           /* Read the value in from memory.  */
1144           read_memory (*addrp, valuep,
1145                        register_size (get_frame_arch (next_frame), regnum));
1146         }
1147       return;
1148     }
1149
1150   *optimizedp = 0;
1151   *lvalp = lval_register;
1152   *addrp = 0;
1153   *realnump = regnum;
1154   if (valuep)
1155     frame_unwind_register (next_frame, (*realnump), valuep);
1156 }
1157
1158 static const struct frame_unwind i386_frame_unwind =
1159 {
1160   NORMAL_FRAME,
1161   i386_frame_this_id,
1162   i386_frame_prev_register
1163 };
1164
1165 static const struct frame_unwind *
1166 i386_frame_sniffer (struct frame_info *next_frame)
1167 {
1168   return &i386_frame_unwind;
1169 }
1170 \f
1171
1172 /* Signal trampolines.  */
1173
1174 static struct i386_frame_cache *
1175 i386_sigtramp_frame_cache (struct frame_info *next_frame, void **this_cache)
1176 {
1177   struct i386_frame_cache *cache;
1178   struct gdbarch_tdep *tdep = gdbarch_tdep (get_frame_arch (next_frame));
1179   CORE_ADDR addr;
1180   gdb_byte buf[4];
1181
1182   if (*this_cache)
1183     return *this_cache;
1184
1185   cache = i386_alloc_frame_cache ();
1186
1187   frame_unwind_register (next_frame, I386_ESP_REGNUM, buf);
1188   cache->base = extract_unsigned_integer (buf, 4) - 4;
1189
1190   addr = tdep->sigcontext_addr (next_frame);
1191   if (tdep->sc_reg_offset)
1192     {
1193       int i;
1194
1195       gdb_assert (tdep->sc_num_regs <= I386_NUM_SAVED_REGS);
1196
1197       for (i = 0; i < tdep->sc_num_regs; i++)
1198         if (tdep->sc_reg_offset[i] != -1)
1199           cache->saved_regs[i] = addr + tdep->sc_reg_offset[i];
1200     }
1201   else
1202     {
1203       cache->saved_regs[I386_EIP_REGNUM] = addr + tdep->sc_pc_offset;
1204       cache->saved_regs[I386_ESP_REGNUM] = addr + tdep->sc_sp_offset;
1205     }
1206
1207   *this_cache = cache;
1208   return cache;
1209 }
1210
1211 static void
1212 i386_sigtramp_frame_this_id (struct frame_info *next_frame, void **this_cache,
1213                              struct frame_id *this_id)
1214 {
1215   struct i386_frame_cache *cache =
1216     i386_sigtramp_frame_cache (next_frame, this_cache);
1217
1218   /* See the end of i386_push_dummy_call.  */
1219   (*this_id) = frame_id_build (cache->base + 8, frame_pc_unwind (next_frame));
1220 }
1221
1222 static void
1223 i386_sigtramp_frame_prev_register (struct frame_info *next_frame,
1224                                    void **this_cache,
1225                                    int regnum, int *optimizedp,
1226                                    enum lval_type *lvalp, CORE_ADDR *addrp,
1227                                    int *realnump, gdb_byte *valuep)
1228 {
1229   /* Make sure we've initialized the cache.  */
1230   i386_sigtramp_frame_cache (next_frame, this_cache);
1231
1232   i386_frame_prev_register (next_frame, this_cache, regnum,
1233                             optimizedp, lvalp, addrp, realnump, valuep);
1234 }
1235
1236 static const struct frame_unwind i386_sigtramp_frame_unwind =
1237 {
1238   SIGTRAMP_FRAME,
1239   i386_sigtramp_frame_this_id,
1240   i386_sigtramp_frame_prev_register
1241 };
1242
1243 static const struct frame_unwind *
1244 i386_sigtramp_frame_sniffer (struct frame_info *next_frame)
1245 {
1246   struct gdbarch_tdep *tdep = gdbarch_tdep (get_frame_arch (next_frame));
1247
1248   /* We shouldn't even bother if we don't have a sigcontext_addr
1249      handler.  */
1250   if (tdep->sigcontext_addr == NULL)
1251     return NULL;
1252
1253   if (tdep->sigtramp_p != NULL)
1254     {
1255       if (tdep->sigtramp_p (next_frame))
1256         return &i386_sigtramp_frame_unwind;
1257     }
1258
1259   if (tdep->sigtramp_start != 0)
1260     {
1261       CORE_ADDR pc = frame_pc_unwind (next_frame);
1262
1263       gdb_assert (tdep->sigtramp_end != 0);
1264       if (pc >= tdep->sigtramp_start && pc < tdep->sigtramp_end)
1265         return &i386_sigtramp_frame_unwind;
1266     }
1267
1268   return NULL;
1269 }
1270 \f
1271
1272 static CORE_ADDR
1273 i386_frame_base_address (struct frame_info *next_frame, void **this_cache)
1274 {
1275   struct i386_frame_cache *cache = i386_frame_cache (next_frame, this_cache);
1276
1277   return cache->base;
1278 }
1279
1280 static const struct frame_base i386_frame_base =
1281 {
1282   &i386_frame_unwind,
1283   i386_frame_base_address,
1284   i386_frame_base_address,
1285   i386_frame_base_address
1286 };
1287
1288 static struct frame_id
1289 i386_unwind_dummy_id (struct gdbarch *gdbarch, struct frame_info *next_frame)
1290 {
1291   gdb_byte buf[4];
1292   CORE_ADDR fp;
1293
1294   frame_unwind_register (next_frame, I386_EBP_REGNUM, buf);
1295   fp = extract_unsigned_integer (buf, 4);
1296
1297   /* See the end of i386_push_dummy_call.  */
1298   return frame_id_build (fp + 8, frame_pc_unwind (next_frame));
1299 }
1300 \f
1301
1302 /* Figure out where the longjmp will land.  Slurp the args out of the
1303    stack.  We expect the first arg to be a pointer to the jmp_buf
1304    structure from which we extract the address that we will land at.
1305    This address is copied into PC.  This routine returns non-zero on
1306    success.
1307
1308    This function is 64-bit safe.  */
1309
1310 static int
1311 i386_get_longjmp_target (struct frame_info *frame, CORE_ADDR *pc)
1312 {
1313   gdb_byte buf[8];
1314   CORE_ADDR sp, jb_addr;
1315   int jb_pc_offset = gdbarch_tdep (get_frame_arch (frame))->jb_pc_offset;
1316   int len = TYPE_LENGTH (builtin_type_void_func_ptr);
1317
1318   /* If JB_PC_OFFSET is -1, we have no way to find out where the
1319      longjmp will land.  */
1320   if (jb_pc_offset == -1)
1321     return 0;
1322
1323   /* Don't use I386_ESP_REGNUM here, since this function is also used
1324      for AMD64.  */
1325   get_frame_register (frame, gdbarch_sp_regnum (get_frame_arch (frame)), buf);
1326   sp = extract_typed_address (buf, builtin_type_void_data_ptr);
1327   if (target_read_memory (sp + len, buf, len))
1328     return 0;
1329
1330   jb_addr = extract_typed_address (buf, builtin_type_void_data_ptr);
1331   if (target_read_memory (jb_addr + jb_pc_offset, buf, len))
1332     return 0;
1333
1334   *pc = extract_typed_address (buf, builtin_type_void_func_ptr);
1335   return 1;
1336 }
1337 \f
1338
1339 static CORE_ADDR
1340 i386_push_dummy_call (struct gdbarch *gdbarch, struct value *function,
1341                       struct regcache *regcache, CORE_ADDR bp_addr, int nargs,
1342                       struct value **args, CORE_ADDR sp, int struct_return,
1343                       CORE_ADDR struct_addr)
1344 {
1345   gdb_byte buf[4];
1346   int i;
1347
1348   /* Push arguments in reverse order.  */
1349   for (i = nargs - 1; i >= 0; i--)
1350     {
1351       int len = TYPE_LENGTH (value_enclosing_type (args[i]));
1352
1353       /* The System V ABI says that:
1354
1355          "An argument's size is increased, if necessary, to make it a
1356          multiple of [32-bit] words.  This may require tail padding,
1357          depending on the size of the argument."
1358
1359          This makes sure the stack stays word-aligned.  */
1360       sp -= (len + 3) & ~3;
1361       write_memory (sp, value_contents_all (args[i]), len);
1362     }
1363
1364   /* Push value address.  */
1365   if (struct_return)
1366     {
1367       sp -= 4;
1368       store_unsigned_integer (buf, 4, struct_addr);
1369       write_memory (sp, buf, 4);
1370     }
1371
1372   /* Store return address.  */
1373   sp -= 4;
1374   store_unsigned_integer (buf, 4, bp_addr);
1375   write_memory (sp, buf, 4);
1376
1377   /* Finally, update the stack pointer...  */
1378   store_unsigned_integer (buf, 4, sp);
1379   regcache_cooked_write (regcache, I386_ESP_REGNUM, buf);
1380
1381   /* ...and fake a frame pointer.  */
1382   regcache_cooked_write (regcache, I386_EBP_REGNUM, buf);
1383
1384   /* MarkK wrote: This "+ 8" is all over the place:
1385      (i386_frame_this_id, i386_sigtramp_frame_this_id,
1386      i386_unwind_dummy_id).  It's there, since all frame unwinders for
1387      a given target have to agree (within a certain margin) on the
1388      definition of the stack address of a frame.  Otherwise
1389      frame_id_inner() won't work correctly.  Since DWARF2/GCC uses the
1390      stack address *before* the function call as a frame's CFA.  On
1391      the i386, when %ebp is used as a frame pointer, the offset
1392      between the contents %ebp and the CFA as defined by GCC.  */
1393   return sp + 8;
1394 }
1395
1396 /* These registers are used for returning integers (and on some
1397    targets also for returning `struct' and `union' values when their
1398    size and alignment match an integer type).  */
1399 #define LOW_RETURN_REGNUM       I386_EAX_REGNUM /* %eax */
1400 #define HIGH_RETURN_REGNUM      I386_EDX_REGNUM /* %edx */
1401
1402 /* Read, for architecture GDBARCH, a function return value of TYPE
1403    from REGCACHE, and copy that into VALBUF.  */
1404
1405 static void
1406 i386_extract_return_value (struct gdbarch *gdbarch, struct type *type,
1407                            struct regcache *regcache, gdb_byte *valbuf)
1408 {
1409   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1410   int len = TYPE_LENGTH (type);
1411   gdb_byte buf[I386_MAX_REGISTER_SIZE];
1412
1413   if (TYPE_CODE (type) == TYPE_CODE_FLT)
1414     {
1415       if (tdep->st0_regnum < 0)
1416         {
1417           warning (_("Cannot find floating-point return value."));
1418           memset (valbuf, 0, len);
1419           return;
1420         }
1421
1422       /* Floating-point return values can be found in %st(0).  Convert
1423          its contents to the desired type.  This is probably not
1424          exactly how it would happen on the target itself, but it is
1425          the best we can do.  */
1426       regcache_raw_read (regcache, I386_ST0_REGNUM, buf);
1427       convert_typed_floating (buf, builtin_type_i387_ext, valbuf, type);
1428     }
1429   else
1430     {
1431       int low_size = register_size (gdbarch, LOW_RETURN_REGNUM);
1432       int high_size = register_size (gdbarch, HIGH_RETURN_REGNUM);
1433
1434       if (len <= low_size)
1435         {
1436           regcache_raw_read (regcache, LOW_RETURN_REGNUM, buf);
1437           memcpy (valbuf, buf, len);
1438         }
1439       else if (len <= (low_size + high_size))
1440         {
1441           regcache_raw_read (regcache, LOW_RETURN_REGNUM, buf);
1442           memcpy (valbuf, buf, low_size);
1443           regcache_raw_read (regcache, HIGH_RETURN_REGNUM, buf);
1444           memcpy (valbuf + low_size, buf, len - low_size);
1445         }
1446       else
1447         internal_error (__FILE__, __LINE__,
1448                         _("Cannot extract return value of %d bytes long."), len);
1449     }
1450 }
1451
1452 /* Write, for architecture GDBARCH, a function return value of TYPE
1453    from VALBUF into REGCACHE.  */
1454
1455 static void
1456 i386_store_return_value (struct gdbarch *gdbarch, struct type *type,
1457                          struct regcache *regcache, const gdb_byte *valbuf)
1458 {
1459   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1460   int len = TYPE_LENGTH (type);
1461
1462   /* Define I387_ST0_REGNUM such that we use the proper definitions
1463      for the architecture.  */
1464 #define I387_ST0_REGNUM I386_ST0_REGNUM
1465
1466   if (TYPE_CODE (type) == TYPE_CODE_FLT)
1467     {
1468       ULONGEST fstat;
1469       gdb_byte buf[I386_MAX_REGISTER_SIZE];
1470
1471       if (tdep->st0_regnum < 0)
1472         {
1473           warning (_("Cannot set floating-point return value."));
1474           return;
1475         }
1476
1477       /* Returning floating-point values is a bit tricky.  Apart from
1478          storing the return value in %st(0), we have to simulate the
1479          state of the FPU at function return point.  */
1480
1481       /* Convert the value found in VALBUF to the extended
1482          floating-point format used by the FPU.  This is probably
1483          not exactly how it would happen on the target itself, but
1484          it is the best we can do.  */
1485       convert_typed_floating (valbuf, type, buf, builtin_type_i387_ext);
1486       regcache_raw_write (regcache, I386_ST0_REGNUM, buf);
1487
1488       /* Set the top of the floating-point register stack to 7.  The
1489          actual value doesn't really matter, but 7 is what a normal
1490          function return would end up with if the program started out
1491          with a freshly initialized FPU.  */
1492       regcache_raw_read_unsigned (regcache, I387_FSTAT_REGNUM, &fstat);
1493       fstat |= (7 << 11);
1494       regcache_raw_write_unsigned (regcache, I387_FSTAT_REGNUM, fstat);
1495
1496       /* Mark %st(1) through %st(7) as empty.  Since we set the top of
1497          the floating-point register stack to 7, the appropriate value
1498          for the tag word is 0x3fff.  */
1499       regcache_raw_write_unsigned (regcache, I387_FTAG_REGNUM, 0x3fff);
1500     }
1501   else
1502     {
1503       int low_size = register_size (gdbarch, LOW_RETURN_REGNUM);
1504       int high_size = register_size (gdbarch, HIGH_RETURN_REGNUM);
1505
1506       if (len <= low_size)
1507         regcache_raw_write_part (regcache, LOW_RETURN_REGNUM, 0, len, valbuf);
1508       else if (len <= (low_size + high_size))
1509         {
1510           regcache_raw_write (regcache, LOW_RETURN_REGNUM, valbuf);
1511           regcache_raw_write_part (regcache, HIGH_RETURN_REGNUM, 0,
1512                                    len - low_size, valbuf + low_size);
1513         }
1514       else
1515         internal_error (__FILE__, __LINE__,
1516                         _("Cannot store return value of %d bytes long."), len);
1517     }
1518
1519 #undef I387_ST0_REGNUM
1520 }
1521 \f
1522
1523 /* This is the variable that is set with "set struct-convention", and
1524    its legitimate values.  */
1525 static const char default_struct_convention[] = "default";
1526 static const char pcc_struct_convention[] = "pcc";
1527 static const char reg_struct_convention[] = "reg";
1528 static const char *valid_conventions[] =
1529 {
1530   default_struct_convention,
1531   pcc_struct_convention,
1532   reg_struct_convention,
1533   NULL
1534 };
1535 static const char *struct_convention = default_struct_convention;
1536
1537 /* Return non-zero if TYPE, which is assumed to be a structure,
1538    a union type, or an array type, should be returned in registers
1539    for architecture GDBARCH.  */
1540
1541 static int
1542 i386_reg_struct_return_p (struct gdbarch *gdbarch, struct type *type)
1543 {
1544   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1545   enum type_code code = TYPE_CODE (type);
1546   int len = TYPE_LENGTH (type);
1547
1548   gdb_assert (code == TYPE_CODE_STRUCT
1549               || code == TYPE_CODE_UNION
1550               || code == TYPE_CODE_ARRAY);
1551
1552   if (struct_convention == pcc_struct_convention
1553       || (struct_convention == default_struct_convention
1554           && tdep->struct_return == pcc_struct_return))
1555     return 0;
1556
1557   /* Structures consisting of a single `float', `double' or 'long
1558      double' member are returned in %st(0).  */
1559   if (code == TYPE_CODE_STRUCT && TYPE_NFIELDS (type) == 1)
1560     {
1561       type = check_typedef (TYPE_FIELD_TYPE (type, 0));
1562       if (TYPE_CODE (type) == TYPE_CODE_FLT)
1563         return (len == 4 || len == 8 || len == 12);
1564     }
1565
1566   return (len == 1 || len == 2 || len == 4 || len == 8);
1567 }
1568
1569 /* Determine, for architecture GDBARCH, how a return value of TYPE
1570    should be returned.  If it is supposed to be returned in registers,
1571    and READBUF is non-zero, read the appropriate value from REGCACHE,
1572    and copy it into READBUF.  If WRITEBUF is non-zero, write the value
1573    from WRITEBUF into REGCACHE.  */
1574
1575 static enum return_value_convention
1576 i386_return_value (struct gdbarch *gdbarch, struct type *type,
1577                    struct regcache *regcache, gdb_byte *readbuf,
1578                    const gdb_byte *writebuf)
1579 {
1580   enum type_code code = TYPE_CODE (type);
1581
1582   if ((code == TYPE_CODE_STRUCT
1583        || code == TYPE_CODE_UNION
1584        || code == TYPE_CODE_ARRAY)
1585       && !i386_reg_struct_return_p (gdbarch, type))
1586     {
1587       /* The System V ABI says that:
1588
1589          "A function that returns a structure or union also sets %eax
1590          to the value of the original address of the caller's area
1591          before it returns.  Thus when the caller receives control
1592          again, the address of the returned object resides in register
1593          %eax and can be used to access the object."
1594
1595          So the ABI guarantees that we can always find the return
1596          value just after the function has returned.  */
1597
1598       /* Note that the ABI doesn't mention functions returning arrays,
1599          which is something possible in certain languages such as Ada.
1600          In this case, the value is returned as if it was wrapped in
1601          a record, so the convention applied to records also applies
1602          to arrays.  */
1603
1604       if (readbuf)
1605         {
1606           ULONGEST addr;
1607
1608           regcache_raw_read_unsigned (regcache, I386_EAX_REGNUM, &addr);
1609           read_memory (addr, readbuf, TYPE_LENGTH (type));
1610         }
1611
1612       return RETURN_VALUE_ABI_RETURNS_ADDRESS;
1613     }
1614
1615   /* This special case is for structures consisting of a single
1616      `float', `double' or 'long double' member.  These structures are
1617      returned in %st(0).  For these structures, we call ourselves
1618      recursively, changing TYPE into the type of the first member of
1619      the structure.  Since that should work for all structures that
1620      have only one member, we don't bother to check the member's type
1621      here.  */
1622   if (code == TYPE_CODE_STRUCT && TYPE_NFIELDS (type) == 1)
1623     {
1624       type = check_typedef (TYPE_FIELD_TYPE (type, 0));
1625       return i386_return_value (gdbarch, type, regcache, readbuf, writebuf);
1626     }
1627
1628   if (readbuf)
1629     i386_extract_return_value (gdbarch, type, regcache, readbuf);
1630   if (writebuf)
1631     i386_store_return_value (gdbarch, type, regcache, writebuf);
1632
1633   return RETURN_VALUE_REGISTER_CONVENTION;
1634 }
1635 \f
1636
1637 /* Type for %eflags.  */
1638 struct type *i386_eflags_type;
1639
1640 /* Type for %mxcsr.  */
1641 struct type *i386_mxcsr_type;
1642
1643 /* Construct types for ISA-specific registers.  */
1644 static void
1645 i386_init_types (void)
1646 {
1647   struct type *type;
1648
1649   type = init_flags_type ("builtin_type_i386_eflags", 4);
1650   append_flags_type_flag (type, 0, "CF");
1651   append_flags_type_flag (type, 1, NULL);
1652   append_flags_type_flag (type, 2, "PF");
1653   append_flags_type_flag (type, 4, "AF");
1654   append_flags_type_flag (type, 6, "ZF");
1655   append_flags_type_flag (type, 7, "SF");
1656   append_flags_type_flag (type, 8, "TF");
1657   append_flags_type_flag (type, 9, "IF");
1658   append_flags_type_flag (type, 10, "DF");
1659   append_flags_type_flag (type, 11, "OF");
1660   append_flags_type_flag (type, 14, "NT");
1661   append_flags_type_flag (type, 16, "RF");
1662   append_flags_type_flag (type, 17, "VM");
1663   append_flags_type_flag (type, 18, "AC");
1664   append_flags_type_flag (type, 19, "VIF");
1665   append_flags_type_flag (type, 20, "VIP");
1666   append_flags_type_flag (type, 21, "ID");
1667   i386_eflags_type = type;
1668
1669   type = init_flags_type ("builtin_type_i386_mxcsr", 4);
1670   append_flags_type_flag (type, 0, "IE");
1671   append_flags_type_flag (type, 1, "DE");
1672   append_flags_type_flag (type, 2, "ZE");
1673   append_flags_type_flag (type, 3, "OE");
1674   append_flags_type_flag (type, 4, "UE");
1675   append_flags_type_flag (type, 5, "PE");
1676   append_flags_type_flag (type, 6, "DAZ");
1677   append_flags_type_flag (type, 7, "IM");
1678   append_flags_type_flag (type, 8, "DM");
1679   append_flags_type_flag (type, 9, "ZM");
1680   append_flags_type_flag (type, 10, "OM");
1681   append_flags_type_flag (type, 11, "UM");
1682   append_flags_type_flag (type, 12, "PM");
1683   append_flags_type_flag (type, 15, "FZ");
1684   i386_mxcsr_type = type;
1685 }
1686
1687 /* Construct vector type for MMX registers.  */
1688 struct type *
1689 i386_mmx_type (struct gdbarch *gdbarch)
1690 {
1691   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1692
1693   if (!tdep->i386_mmx_type)
1694     {
1695       /* The type we're building is this: */
1696 #if 0
1697       union __gdb_builtin_type_vec64i
1698       {
1699         int64_t uint64;
1700         int32_t v2_int32[2];
1701         int16_t v4_int16[4];
1702         int8_t v8_int8[8];
1703       };
1704 #endif
1705
1706       struct type *t;
1707
1708       t = init_composite_type ("__gdb_builtin_type_vec64i", TYPE_CODE_UNION);
1709       append_composite_type_field (t, "uint64", builtin_type_int64);
1710       append_composite_type_field (t, "v2_int32",
1711                                    init_vector_type (builtin_type_int32, 2));
1712       append_composite_type_field (t, "v4_int16",
1713                                    init_vector_type (builtin_type_int16, 4));
1714       append_composite_type_field (t, "v8_int8",
1715                                    init_vector_type (builtin_type_int8, 8));
1716
1717       TYPE_FLAGS (t) |= TYPE_FLAG_VECTOR;
1718       TYPE_NAME (t) = "builtin_type_vec64i";
1719       tdep->i386_mmx_type = t;
1720     }
1721
1722   return tdep->i386_mmx_type;
1723 }
1724
1725 struct type *
1726 i386_sse_type (struct gdbarch *gdbarch)
1727 {
1728   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
1729
1730   if (!tdep->i386_sse_type)
1731     {
1732       /* The type we're building is this: */
1733 #if 0
1734       union __gdb_builtin_type_vec128i
1735       {
1736         int128_t uint128;
1737         int64_t v2_int64[2];
1738         int32_t v4_int32[4];
1739         int16_t v8_int16[8];
1740         int8_t v16_int8[16];
1741         double v2_double[2];
1742         float v4_float[4];
1743       };
1744 #endif
1745
1746       struct type *t;
1747
1748       t = init_composite_type ("__gdb_builtin_type_vec128i", TYPE_CODE_UNION);
1749       append_composite_type_field (t, "v4_float",
1750                                    init_vector_type (builtin_type_float, 4));
1751       append_composite_type_field (t, "v2_double",
1752                                    init_vector_type (builtin_type_double, 2));
1753       append_composite_type_field (t, "v16_int8",
1754                                    init_vector_type (builtin_type_int8, 16));
1755       append_composite_type_field (t, "v8_int16",
1756                                    init_vector_type (builtin_type_int16, 8));
1757       append_composite_type_field (t, "v4_int32",
1758                                    init_vector_type (builtin_type_int32, 4));
1759       append_composite_type_field (t, "v2_int64",
1760                                    init_vector_type (builtin_type_int64, 2));
1761       append_composite_type_field (t, "uint128", builtin_type_int128);
1762
1763       TYPE_FLAGS (t) |= TYPE_FLAG_VECTOR;
1764       TYPE_NAME (t) = "builtin_type_vec128i";
1765       tdep->i386_sse_type = t;
1766     }
1767
1768   return tdep->i386_sse_type;
1769 }
1770
1771 /* Return the GDB type object for the "standard" data type of data in
1772    register REGNUM.  Perhaps %esi and %edi should go here, but
1773    potentially they could be used for things other than address.  */
1774
1775 static struct type *
1776 i386_register_type (struct gdbarch *gdbarch, int regnum)
1777 {
1778   if (regnum == I386_EIP_REGNUM)
1779     return builtin_type_void_func_ptr;
1780
1781   if (regnum == I386_EFLAGS_REGNUM)
1782     return i386_eflags_type;
1783
1784   if (regnum == I386_EBP_REGNUM || regnum == I386_ESP_REGNUM)
1785     return builtin_type_void_data_ptr;
1786
1787   if (i386_fp_regnum_p (regnum))
1788     return builtin_type_i387_ext;
1789
1790   if (i386_mmx_regnum_p (gdbarch, regnum))
1791     return i386_mmx_type (gdbarch);
1792
1793   if (i386_sse_regnum_p (gdbarch, regnum))
1794     return i386_sse_type (gdbarch);
1795
1796 #define I387_ST0_REGNUM I386_ST0_REGNUM
1797 #define I387_NUM_XMM_REGS (gdbarch_tdep (gdbarch)->num_xmm_regs)
1798
1799   if (regnum == I387_MXCSR_REGNUM)
1800     return i386_mxcsr_type;
1801
1802 #undef I387_ST0_REGNUM
1803 #undef I387_NUM_XMM_REGS
1804
1805   return builtin_type_int;
1806 }
1807
1808 /* Map a cooked register onto a raw register or memory.  For the i386,
1809    the MMX registers need to be mapped onto floating point registers.  */
1810
1811 static int
1812 i386_mmx_regnum_to_fp_regnum (struct regcache *regcache, int regnum)
1813 {
1814   struct gdbarch_tdep *tdep = gdbarch_tdep (get_regcache_arch (regcache));
1815   int mmxreg, fpreg;
1816   ULONGEST fstat;
1817   int tos;
1818
1819   /* Define I387_ST0_REGNUM such that we use the proper definitions
1820      for REGCACHE's architecture.  */
1821 #define I387_ST0_REGNUM tdep->st0_regnum
1822
1823   mmxreg = regnum - tdep->mm0_regnum;
1824   regcache_raw_read_unsigned (regcache, I387_FSTAT_REGNUM, &fstat);
1825   tos = (fstat >> 11) & 0x7;
1826   fpreg = (mmxreg + tos) % 8;
1827
1828   return (I387_ST0_REGNUM + fpreg);
1829
1830 #undef I387_ST0_REGNUM
1831 }
1832
1833 static void
1834 i386_pseudo_register_read (struct gdbarch *gdbarch, struct regcache *regcache,
1835                            int regnum, gdb_byte *buf)
1836 {
1837   if (i386_mmx_regnum_p (gdbarch, regnum))
1838     {
1839       gdb_byte mmx_buf[MAX_REGISTER_SIZE];
1840       int fpnum = i386_mmx_regnum_to_fp_regnum (regcache, regnum);
1841
1842       /* Extract (always little endian).  */
1843       regcache_raw_read (regcache, fpnum, mmx_buf);
1844       memcpy (buf, mmx_buf, register_size (gdbarch, regnum));
1845     }
1846   else
1847     regcache_raw_read (regcache, regnum, buf);
1848 }
1849
1850 static void
1851 i386_pseudo_register_write (struct gdbarch *gdbarch, struct regcache *regcache,
1852                             int regnum, const gdb_byte *buf)
1853 {
1854   if (i386_mmx_regnum_p (gdbarch, regnum))
1855     {
1856       gdb_byte mmx_buf[MAX_REGISTER_SIZE];
1857       int fpnum = i386_mmx_regnum_to_fp_regnum (regcache, regnum);
1858
1859       /* Read ...  */
1860       regcache_raw_read (regcache, fpnum, mmx_buf);
1861       /* ... Modify ... (always little endian).  */
1862       memcpy (mmx_buf, buf, register_size (gdbarch, regnum));
1863       /* ... Write.  */
1864       regcache_raw_write (regcache, fpnum, mmx_buf);
1865     }
1866   else
1867     regcache_raw_write (regcache, regnum, buf);
1868 }
1869 \f
1870
1871 /* Return the register number of the register allocated by GCC after
1872    REGNUM, or -1 if there is no such register.  */
1873
1874 static int
1875 i386_next_regnum (int regnum)
1876 {
1877   /* GCC allocates the registers in the order:
1878
1879      %eax, %edx, %ecx, %ebx, %esi, %edi, %ebp, %esp, ...
1880
1881      Since storing a variable in %esp doesn't make any sense we return
1882      -1 for %ebp and for %esp itself.  */
1883   static int next_regnum[] =
1884   {
1885     I386_EDX_REGNUM,            /* Slot for %eax.  */
1886     I386_EBX_REGNUM,            /* Slot for %ecx.  */
1887     I386_ECX_REGNUM,            /* Slot for %edx.  */
1888     I386_ESI_REGNUM,            /* Slot for %ebx.  */
1889     -1, -1,                     /* Slots for %esp and %ebp.  */
1890     I386_EDI_REGNUM,            /* Slot for %esi.  */
1891     I386_EBP_REGNUM             /* Slot for %edi.  */
1892   };
1893
1894   if (regnum >= 0 && regnum < sizeof (next_regnum) / sizeof (next_regnum[0]))
1895     return next_regnum[regnum];
1896
1897   return -1;
1898 }
1899
1900 /* Return nonzero if a value of type TYPE stored in register REGNUM
1901    needs any special handling.  */
1902
1903 static int
1904 i386_convert_register_p (struct gdbarch *gdbarch, int regnum, struct type *type)
1905 {
1906   int len = TYPE_LENGTH (type);
1907
1908   /* Values may be spread across multiple registers.  Most debugging
1909      formats aren't expressive enough to specify the locations, so
1910      some heuristics is involved.  Right now we only handle types that
1911      have a length that is a multiple of the word size, since GCC
1912      doesn't seem to put any other types into registers.  */
1913   if (len > 4 && len % 4 == 0)
1914     {
1915       int last_regnum = regnum;
1916
1917       while (len > 4)
1918         {
1919           last_regnum = i386_next_regnum (last_regnum);
1920           len -= 4;
1921         }
1922
1923       if (last_regnum != -1)
1924         return 1;
1925     }
1926
1927   return i387_convert_register_p (gdbarch, regnum, type);
1928 }
1929
1930 /* Read a value of type TYPE from register REGNUM in frame FRAME, and
1931    return its contents in TO.  */
1932
1933 static void
1934 i386_register_to_value (struct frame_info *frame, int regnum,
1935                         struct type *type, gdb_byte *to)
1936 {
1937   int len = TYPE_LENGTH (type);
1938
1939   /* FIXME: kettenis/20030609: What should we do if REGNUM isn't
1940      available in FRAME (i.e. if it wasn't saved)?  */
1941
1942   if (i386_fp_regnum_p (regnum))
1943     {
1944       i387_register_to_value (frame, regnum, type, to);
1945       return;
1946     }
1947
1948   /* Read a value spread across multiple registers.  */
1949
1950   gdb_assert (len > 4 && len % 4 == 0);
1951
1952   while (len > 0)
1953     {
1954       gdb_assert (regnum != -1);
1955       gdb_assert (register_size (get_frame_arch (frame), regnum) == 4);
1956
1957       get_frame_register (frame, regnum, to);
1958       regnum = i386_next_regnum (regnum);
1959       len -= 4;
1960       to += 4;
1961     }
1962 }
1963
1964 /* Write the contents FROM of a value of type TYPE into register
1965    REGNUM in frame FRAME.  */
1966
1967 static void
1968 i386_value_to_register (struct frame_info *frame, int regnum,
1969                         struct type *type, const gdb_byte *from)
1970 {
1971   int len = TYPE_LENGTH (type);
1972
1973   if (i386_fp_regnum_p (regnum))
1974     {
1975       i387_value_to_register (frame, regnum, type, from);
1976       return;
1977     }
1978
1979   /* Write a value spread across multiple registers.  */
1980
1981   gdb_assert (len > 4 && len % 4 == 0);
1982
1983   while (len > 0)
1984     {
1985       gdb_assert (regnum != -1);
1986       gdb_assert (register_size (get_frame_arch (frame), regnum) == 4);
1987
1988       put_frame_register (frame, regnum, from);
1989       regnum = i386_next_regnum (regnum);
1990       len -= 4;
1991       from += 4;
1992     }
1993 }
1994 \f
1995 /* Supply register REGNUM from the buffer specified by GREGS and LEN
1996    in the general-purpose register set REGSET to register cache
1997    REGCACHE.  If REGNUM is -1, do this for all registers in REGSET.  */
1998
1999 void
2000 i386_supply_gregset (const struct regset *regset, struct regcache *regcache,
2001                      int regnum, const void *gregs, size_t len)
2002 {
2003   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2004   const gdb_byte *regs = gregs;
2005   int i;
2006
2007   gdb_assert (len == tdep->sizeof_gregset);
2008
2009   for (i = 0; i < tdep->gregset_num_regs; i++)
2010     {
2011       if ((regnum == i || regnum == -1)
2012           && tdep->gregset_reg_offset[i] != -1)
2013         regcache_raw_supply (regcache, i, regs + tdep->gregset_reg_offset[i]);
2014     }
2015 }
2016
2017 /* Collect register REGNUM from the register cache REGCACHE and store
2018    it in the buffer specified by GREGS and LEN as described by the
2019    general-purpose register set REGSET.  If REGNUM is -1, do this for
2020    all registers in REGSET.  */
2021
2022 void
2023 i386_collect_gregset (const struct regset *regset,
2024                       const struct regcache *regcache,
2025                       int regnum, void *gregs, size_t len)
2026 {
2027   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2028   gdb_byte *regs = gregs;
2029   int i;
2030
2031   gdb_assert (len == tdep->sizeof_gregset);
2032
2033   for (i = 0; i < tdep->gregset_num_regs; i++)
2034     {
2035       if ((regnum == i || regnum == -1)
2036           && tdep->gregset_reg_offset[i] != -1)
2037         regcache_raw_collect (regcache, i, regs + tdep->gregset_reg_offset[i]);
2038     }
2039 }
2040
2041 /* Supply register REGNUM from the buffer specified by FPREGS and LEN
2042    in the floating-point register set REGSET to register cache
2043    REGCACHE.  If REGNUM is -1, do this for all registers in REGSET.  */
2044
2045 static void
2046 i386_supply_fpregset (const struct regset *regset, struct regcache *regcache,
2047                       int regnum, const void *fpregs, size_t len)
2048 {
2049   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2050
2051   if (len == I387_SIZEOF_FXSAVE)
2052     {
2053       i387_supply_fxsave (regcache, regnum, fpregs);
2054       return;
2055     }
2056
2057   gdb_assert (len == tdep->sizeof_fpregset);
2058   i387_supply_fsave (regcache, regnum, fpregs);
2059 }
2060
2061 /* Collect register REGNUM from the register cache REGCACHE and store
2062    it in the buffer specified by FPREGS and LEN as described by the
2063    floating-point register set REGSET.  If REGNUM is -1, do this for
2064    all registers in REGSET.  */
2065
2066 static void
2067 i386_collect_fpregset (const struct regset *regset,
2068                        const struct regcache *regcache,
2069                        int regnum, void *fpregs, size_t len)
2070 {
2071   const struct gdbarch_tdep *tdep = gdbarch_tdep (regset->arch);
2072
2073   if (len == I387_SIZEOF_FXSAVE)
2074     {
2075       i387_collect_fxsave (regcache, regnum, fpregs);
2076       return;
2077     }
2078
2079   gdb_assert (len == tdep->sizeof_fpregset);
2080   i387_collect_fsave (regcache, regnum, fpregs);
2081 }
2082
2083 /* Return the appropriate register set for the core section identified
2084    by SECT_NAME and SECT_SIZE.  */
2085
2086 const struct regset *
2087 i386_regset_from_core_section (struct gdbarch *gdbarch,
2088                                const char *sect_name, size_t sect_size)
2089 {
2090   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2091
2092   if (strcmp (sect_name, ".reg") == 0 && sect_size == tdep->sizeof_gregset)
2093     {
2094       if (tdep->gregset == NULL)
2095         tdep->gregset = regset_alloc (gdbarch, i386_supply_gregset,
2096                                       i386_collect_gregset);
2097       return tdep->gregset;
2098     }
2099
2100   if ((strcmp (sect_name, ".reg2") == 0 && sect_size == tdep->sizeof_fpregset)
2101       || (strcmp (sect_name, ".reg-xfp") == 0
2102           && sect_size == I387_SIZEOF_FXSAVE))
2103     {
2104       if (tdep->fpregset == NULL)
2105         tdep->fpregset = regset_alloc (gdbarch, i386_supply_fpregset,
2106                                        i386_collect_fpregset);
2107       return tdep->fpregset;
2108     }
2109
2110   return NULL;
2111 }
2112 \f
2113
2114 /* Stuff for WIN32 PE style DLL's but is pretty generic really.  */
2115
2116 CORE_ADDR
2117 i386_pe_skip_trampoline_code (CORE_ADDR pc, char *name)
2118 {
2119   if (pc && read_memory_unsigned_integer (pc, 2) == 0x25ff) /* jmp *(dest) */
2120     {
2121       unsigned long indirect = read_memory_unsigned_integer (pc + 2, 4);
2122       struct minimal_symbol *indsym =
2123         indirect ? lookup_minimal_symbol_by_pc (indirect) : 0;
2124       char *symname = indsym ? SYMBOL_LINKAGE_NAME (indsym) : 0;
2125
2126       if (symname)
2127         {
2128           if (strncmp (symname, "__imp_", 6) == 0
2129               || strncmp (symname, "_imp_", 5) == 0)
2130             return name ? 1 : read_memory_unsigned_integer (indirect, 4);
2131         }
2132     }
2133   return 0;                     /* Not a trampoline.  */
2134 }
2135 \f
2136
2137 /* Return whether the frame preceding NEXT_FRAME corresponds to a
2138    sigtramp routine.  */
2139
2140 static int
2141 i386_sigtramp_p (struct frame_info *next_frame)
2142 {
2143   CORE_ADDR pc = frame_pc_unwind (next_frame);
2144   char *name;
2145
2146   find_pc_partial_function (pc, &name, NULL, NULL);
2147   return (name && strcmp ("_sigtramp", name) == 0);
2148 }
2149 \f
2150
2151 /* We have two flavours of disassembly.  The machinery on this page
2152    deals with switching between those.  */
2153
2154 static int
2155 i386_print_insn (bfd_vma pc, struct disassemble_info *info)
2156 {
2157   gdb_assert (disassembly_flavor == att_flavor
2158               || disassembly_flavor == intel_flavor);
2159
2160   /* FIXME: kettenis/20020915: Until disassembler_options is properly
2161      constified, cast to prevent a compiler warning.  */
2162   info->disassembler_options = (char *) disassembly_flavor;
2163   info->mach = gdbarch_bfd_arch_info (current_gdbarch)->mach;
2164
2165   return print_insn_i386 (pc, info);
2166 }
2167 \f
2168
2169 /* There are a few i386 architecture variants that differ only
2170    slightly from the generic i386 target.  For now, we don't give them
2171    their own source file, but include them here.  As a consequence,
2172    they'll always be included.  */
2173
2174 /* System V Release 4 (SVR4).  */
2175
2176 /* Return whether the frame preceding NEXT_FRAME corresponds to a SVR4
2177    sigtramp routine.  */
2178
2179 static int
2180 i386_svr4_sigtramp_p (struct frame_info *next_frame)
2181 {
2182   CORE_ADDR pc = frame_pc_unwind (next_frame);
2183   char *name;
2184
2185   /* UnixWare uses _sigacthandler.  The origin of the other symbols is
2186      currently unknown.  */
2187   find_pc_partial_function (pc, &name, NULL, NULL);
2188   return (name && (strcmp ("_sigreturn", name) == 0
2189                    || strcmp ("_sigacthandler", name) == 0
2190                    || strcmp ("sigvechandler", name) == 0));
2191 }
2192
2193 /* Assuming NEXT_FRAME is for a frame following a SVR4 sigtramp
2194    routine, return the address of the associated sigcontext (ucontext)
2195    structure.  */
2196
2197 static CORE_ADDR
2198 i386_svr4_sigcontext_addr (struct frame_info *next_frame)
2199 {
2200   gdb_byte buf[4];
2201   CORE_ADDR sp;
2202
2203   frame_unwind_register (next_frame, I386_ESP_REGNUM, buf);
2204   sp = extract_unsigned_integer (buf, 4);
2205
2206   return read_memory_unsigned_integer (sp + 8, 4);
2207 }
2208 \f
2209
2210 /* Generic ELF.  */
2211
2212 void
2213 i386_elf_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2214 {
2215   /* We typically use stabs-in-ELF with the SVR4 register numbering.  */
2216   set_gdbarch_stab_reg_to_regnum (gdbarch, i386_svr4_reg_to_regnum);
2217 }
2218
2219 /* System V Release 4 (SVR4).  */
2220
2221 void
2222 i386_svr4_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2223 {
2224   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2225
2226   /* System V Release 4 uses ELF.  */
2227   i386_elf_init_abi (info, gdbarch);
2228
2229   /* System V Release 4 has shared libraries.  */
2230   set_gdbarch_skip_trampoline_code (gdbarch, find_solib_trampoline_target);
2231
2232   tdep->sigtramp_p = i386_svr4_sigtramp_p;
2233   tdep->sigcontext_addr = i386_svr4_sigcontext_addr;
2234   tdep->sc_pc_offset = 36 + 14 * 4;
2235   tdep->sc_sp_offset = 36 + 17 * 4;
2236
2237   tdep->jb_pc_offset = 20;
2238 }
2239
2240 /* DJGPP.  */
2241
2242 static void
2243 i386_go32_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch)
2244 {
2245   struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch);
2246
2247   /* DJGPP doesn't have any special frames for signal handlers.  */
2248   tdep->sigtramp_p = NULL;
2249
2250   tdep->jb_pc_offset = 36;
2251 }
2252 \f
2253
2254 /* i386 register groups.  In addition to the normal groups, add "mmx"
2255    and "sse".  */
2256
2257 static struct reggroup *i386_sse_reggroup;
2258 static struct reggroup *i386_mmx_reggroup;
2259
2260 static void
2261 i386_init_reggroups (void)
2262 {
2263   i386_sse_reggroup = reggroup_new ("sse", USER_REGGROUP);
2264   i386_mmx_reggroup = reggroup_new ("mmx", USER_REGGROUP);
2265 }
2266
2267 static void
2268 i386_add_reggroups (struct gdbarch *gdbarch)
2269 {
2270   reggroup_add (gdbarch, i386_sse_reggroup);
2271   reggroup_add (gdbarch, i386_mmx_reggroup);
2272   reggroup_add (gdbarch, general_reggroup);
2273   reggroup_add (gdbarch, float_reggroup);
2274   reggroup_add (gdbarch, all_reggroup);
2275   reggroup_add (gdbarch, save_reggroup);
2276   reggroup_add (gdbarch, restore_reggroup);
2277   reggroup_add (gdbarch, vector_reggroup);
2278   reggroup_add (gdbarch, system_reggroup);
2279 }
2280
2281 int
2282 i386_register_reggroup_p (struct gdbarch *gdbarch, int regnum,
2283                           struct reggroup *group)
2284 {
2285   int sse_regnum_p = (i386_sse_regnum_p (gdbarch, regnum)
2286                       || i386_mxcsr_regnum_p (gdbarch, regnum));
2287   int fp_regnum_p = (i386_fp_regnum_p (regnum)
2288                      || i386_fpc_regnum_p (regnum));
2289   int mmx_regnum_p = (i386_mmx_regnum_p (gdbarch, regnum));
2290
2291   if (group == i386_mmx_reggroup)
2292     return mmx_regnum_p;
2293   if (group == i386_sse_reggroup)
2294     return sse_regnum_p;
2295   if (group == vector_reggroup)
2296     return (mmx_regnum_p || sse_regnum_p);
2297   if (group == float_reggroup)
2298     return fp_regnum_p;
2299   if (group == general_reggroup)
2300     return (!fp_regnum_p && !mmx_regnum_p && !sse_regnum_p);
2301
2302   return default_register_reggroup_p (gdbarch, regnum, group);
2303 }
2304 \f
2305
2306 /* Get the ARGIth function argument for the current function.  */
2307
2308 static CORE_ADDR
2309 i386_fetch_pointer_argument (struct frame_info *frame, int argi, 
2310                              struct type *type)
2311 {
2312   CORE_ADDR sp = get_frame_register_unsigned  (frame, I386_ESP_REGNUM);
2313   return read_memory_unsigned_integer (sp + (4 * (argi + 1)), 4);
2314 }
2315
2316 \f
2317 static struct gdbarch *
2318 i386_gdbarch_init (struct gdbarch_info info, struct gdbarch_list *arches)
2319 {
2320   struct gdbarch_tdep *tdep;
2321   struct gdbarch *gdbarch;
2322
2323   /* If there is already a candidate, use it.  */
2324   arches = gdbarch_list_lookup_by_info (arches, &info);
2325   if (arches != NULL)
2326     return arches->gdbarch;
2327
2328   /* Allocate space for the new architecture.  */
2329   tdep = XCALLOC (1, struct gdbarch_tdep);
2330   gdbarch = gdbarch_alloc (&info, tdep);
2331
2332   /* General-purpose registers.  */
2333   tdep->gregset = NULL;
2334   tdep->gregset_reg_offset = NULL;
2335   tdep->gregset_num_regs = I386_NUM_GREGS;
2336   tdep->sizeof_gregset = 0;
2337
2338   /* Floating-point registers.  */
2339   tdep->fpregset = NULL;
2340   tdep->sizeof_fpregset = I387_SIZEOF_FSAVE;
2341
2342   /* The default settings include the FPU registers, the MMX registers
2343      and the SSE registers.  This can be overridden for a specific ABI
2344      by adjusting the members `st0_regnum', `mm0_regnum' and
2345      `num_xmm_regs' of `struct gdbarch_tdep', otherwise the registers
2346      will show up in the output of "info all-registers".  Ideally we
2347      should try to autodetect whether they are available, such that we
2348      can prevent "info all-registers" from displaying registers that
2349      aren't available.
2350
2351      NOTE: kevinb/2003-07-13: ... if it's a choice between printing
2352      [the SSE registers] always (even when they don't exist) or never
2353      showing them to the user (even when they do exist), I prefer the
2354      former over the latter.  */
2355
2356   tdep->st0_regnum = I386_ST0_REGNUM;
2357
2358   /* The MMX registers are implemented as pseudo-registers.  Put off
2359      calculating the register number for %mm0 until we know the number
2360      of raw registers.  */
2361   tdep->mm0_regnum = 0;
2362
2363   /* I386_NUM_XREGS includes %mxcsr, so substract one.  */
2364   tdep->num_xmm_regs = I386_NUM_XREGS - 1;
2365
2366   tdep->jb_pc_offset = -1;
2367   tdep->struct_return = pcc_struct_return;
2368   tdep->sigtramp_start = 0;
2369   tdep->sigtramp_end = 0;
2370   tdep->sigtramp_p = i386_sigtramp_p;
2371   tdep->sigcontext_addr = NULL;
2372   tdep->sc_reg_offset = NULL;
2373   tdep->sc_pc_offset = -1;
2374   tdep->sc_sp_offset = -1;
2375
2376   /* The format used for `long double' on almost all i386 targets is
2377      the i387 extended floating-point format.  In fact, of all targets
2378      in the GCC 2.95 tree, only OSF/1 does it different, and insists
2379      on having a `long double' that's not `long' at all.  */
2380   set_gdbarch_long_double_format (gdbarch, floatformats_i387_ext);
2381
2382   /* Although the i387 extended floating-point has only 80 significant
2383      bits, a `long double' actually takes up 96, probably to enforce
2384      alignment.  */
2385   set_gdbarch_long_double_bit (gdbarch, 96);
2386
2387   /* The default ABI includes general-purpose registers, 
2388      floating-point registers, and the SSE registers.  */
2389   set_gdbarch_num_regs (gdbarch, I386_SSE_NUM_REGS);
2390   set_gdbarch_register_name (gdbarch, i386_register_name);
2391   set_gdbarch_register_type (gdbarch, i386_register_type);
2392
2393   /* Register numbers of various important registers.  */
2394   set_gdbarch_sp_regnum (gdbarch, I386_ESP_REGNUM); /* %esp */
2395   set_gdbarch_pc_regnum (gdbarch, I386_EIP_REGNUM); /* %eip */
2396   set_gdbarch_ps_regnum (gdbarch, I386_EFLAGS_REGNUM); /* %eflags */
2397   set_gdbarch_fp0_regnum (gdbarch, I386_ST0_REGNUM); /* %st(0) */
2398
2399   /* NOTE: kettenis/20040418: GCC does have two possible register
2400      numbering schemes on the i386: dbx and SVR4.  These schemes
2401      differ in how they number %ebp, %esp, %eflags, and the
2402      floating-point registers, and are implemented by the arrays
2403      dbx_register_map[] and svr4_dbx_register_map in
2404      gcc/config/i386.c.  GCC also defines a third numbering scheme in
2405      gcc/config/i386.c, which it designates as the "default" register
2406      map used in 64bit mode.  This last register numbering scheme is
2407      implemented in dbx64_register_map, and is used for AMD64; see
2408      amd64-tdep.c.
2409
2410      Currently, each GCC i386 target always uses the same register
2411      numbering scheme across all its supported debugging formats
2412      i.e. SDB (COFF), stabs and DWARF 2.  This is because
2413      gcc/sdbout.c, gcc/dbxout.c and gcc/dwarf2out.c all use the
2414      DBX_REGISTER_NUMBER macro which is defined by each target's
2415      respective config header in a manner independent of the requested
2416      output debugging format.
2417
2418      This does not match the arrangement below, which presumes that
2419      the SDB and stabs numbering schemes differ from the DWARF and
2420      DWARF 2 ones.  The reason for this arrangement is that it is
2421      likely to get the numbering scheme for the target's
2422      default/native debug format right.  For targets where GCC is the
2423      native compiler (FreeBSD, NetBSD, OpenBSD, GNU/Linux) or for
2424      targets where the native toolchain uses a different numbering
2425      scheme for a particular debug format (stabs-in-ELF on Solaris)
2426      the defaults below will have to be overridden, like
2427      i386_elf_init_abi() does.  */
2428
2429   /* Use the dbx register numbering scheme for stabs and COFF.  */
2430   set_gdbarch_stab_reg_to_regnum (gdbarch, i386_dbx_reg_to_regnum);
2431   set_gdbarch_sdb_reg_to_regnum (gdbarch, i386_dbx_reg_to_regnum);
2432
2433   /* Use the SVR4 register numbering scheme for DWARF and DWARF 2.  */
2434   set_gdbarch_dwarf_reg_to_regnum (gdbarch, i386_svr4_reg_to_regnum);
2435   set_gdbarch_dwarf2_reg_to_regnum (gdbarch, i386_svr4_reg_to_regnum);
2436
2437   /* We don't set gdbarch_stab_reg_to_regnum, since ECOFF doesn't seem to
2438      be in use on any of the supported i386 targets.  */
2439
2440   set_gdbarch_print_float_info (gdbarch, i387_print_float_info);
2441
2442   set_gdbarch_get_longjmp_target (gdbarch, i386_get_longjmp_target);
2443
2444   /* Call dummy code.  */
2445   set_gdbarch_push_dummy_call (gdbarch, i386_push_dummy_call);
2446
2447   set_gdbarch_convert_register_p (gdbarch, i386_convert_register_p);
2448   set_gdbarch_register_to_value (gdbarch,  i386_register_to_value);
2449   set_gdbarch_value_to_register (gdbarch, i386_value_to_register);
2450
2451   set_gdbarch_return_value (gdbarch, i386_return_value);
2452
2453   set_gdbarch_skip_prologue (gdbarch, i386_skip_prologue);
2454
2455   /* Stack grows downward.  */
2456   set_gdbarch_inner_than (gdbarch, core_addr_lessthan);
2457
2458   set_gdbarch_breakpoint_from_pc (gdbarch, i386_breakpoint_from_pc);
2459   set_gdbarch_decr_pc_after_break (gdbarch, 1);
2460
2461   set_gdbarch_frame_args_skip (gdbarch, 8);
2462
2463   /* Wire in the MMX registers.  */
2464   set_gdbarch_num_pseudo_regs (gdbarch, i386_num_mmx_regs);
2465   set_gdbarch_pseudo_register_read (gdbarch, i386_pseudo_register_read);
2466   set_gdbarch_pseudo_register_write (gdbarch, i386_pseudo_register_write);
2467
2468   set_gdbarch_print_insn (gdbarch, i386_print_insn);
2469
2470   set_gdbarch_unwind_dummy_id (gdbarch, i386_unwind_dummy_id);
2471
2472   set_gdbarch_unwind_pc (gdbarch, i386_unwind_pc);
2473
2474   /* Add the i386 register groups.  */
2475   i386_add_reggroups (gdbarch);
2476   set_gdbarch_register_reggroup_p (gdbarch, i386_register_reggroup_p);
2477
2478   /* Helper for function argument information.  */
2479   set_gdbarch_fetch_pointer_argument (gdbarch, i386_fetch_pointer_argument);
2480
2481   /* Hook in the DWARF CFI frame unwinder.  */
2482   frame_unwind_append_sniffer (gdbarch, dwarf2_frame_sniffer);
2483
2484   frame_base_set_default (gdbarch, &i386_frame_base);
2485
2486   /* Hook in ABI-specific overrides, if they have been registered.  */
2487   gdbarch_init_osabi (info, gdbarch);
2488
2489   frame_unwind_append_sniffer (gdbarch, i386_sigtramp_frame_sniffer);
2490   frame_unwind_append_sniffer (gdbarch, i386_frame_sniffer);
2491
2492   /* If we have a register mapping, enable the generic core file
2493      support, unless it has already been enabled.  */
2494   if (tdep->gregset_reg_offset
2495       && !gdbarch_regset_from_core_section_p (gdbarch))
2496     set_gdbarch_regset_from_core_section (gdbarch,
2497                                           i386_regset_from_core_section);
2498
2499   /* Unless support for MMX has been disabled, make %mm0 the first
2500      pseudo-register.  */
2501   if (tdep->mm0_regnum == 0)
2502     tdep->mm0_regnum = gdbarch_num_regs (gdbarch);
2503
2504   return gdbarch;
2505 }
2506
2507 static enum gdb_osabi
2508 i386_coff_osabi_sniffer (bfd *abfd)
2509 {
2510   if (strcmp (bfd_get_target (abfd), "coff-go32-exe") == 0
2511       || strcmp (bfd_get_target (abfd), "coff-go32") == 0)
2512     return GDB_OSABI_GO32;
2513
2514   return GDB_OSABI_UNKNOWN;
2515 }
2516 \f
2517
2518 /* Provide a prototype to silence -Wmissing-prototypes.  */
2519 void _initialize_i386_tdep (void);
2520
2521 void
2522 _initialize_i386_tdep (void)
2523 {
2524   register_gdbarch_init (bfd_arch_i386, i386_gdbarch_init);
2525
2526   /* Add the variable that controls the disassembly flavor.  */
2527   add_setshow_enum_cmd ("disassembly-flavor", no_class, valid_flavors,
2528                         &disassembly_flavor, _("\
2529 Set the disassembly flavor."), _("\
2530 Show the disassembly flavor."), _("\
2531 The valid values are \"att\" and \"intel\", and the default value is \"att\"."),
2532                         NULL,
2533                         NULL, /* FIXME: i18n: */
2534                         &setlist, &showlist);
2535
2536   /* Add the variable that controls the convention for returning
2537      structs.  */
2538   add_setshow_enum_cmd ("struct-convention", no_class, valid_conventions,
2539                         &struct_convention, _("\
2540 Set the convention for returning small structs."), _("\
2541 Show the convention for returning small structs."), _("\
2542 Valid values are \"default\", \"pcc\" and \"reg\", and the default value\n\
2543 is \"default\"."),
2544                         NULL,
2545                         NULL, /* FIXME: i18n: */
2546                         &setlist, &showlist);
2547
2548   gdbarch_register_osabi_sniffer (bfd_arch_i386, bfd_target_coff_flavour,
2549                                   i386_coff_osabi_sniffer);
2550
2551   gdbarch_register_osabi (bfd_arch_i386, 0, GDB_OSABI_SVR4,
2552                           i386_svr4_init_abi);
2553   gdbarch_register_osabi (bfd_arch_i386, 0, GDB_OSABI_GO32,
2554                           i386_go32_init_abi);
2555
2556   /* Initialize the i386-specific register groups & types.  */
2557   i386_init_reggroups ();
2558   i386_init_types();
2559 }