import gdb-1999-08-30 snapshot
[external/binutils.git] / gdb / go32-nat.c
1 /* Native debugging support for Intel x86 running DJGPP.
2    Copyright 1997, 1999 Free Software Foundation, Inc.
3    Written by Robert Hoehne.
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 2 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, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #include <fcntl.h>
23
24 #include "defs.h"
25 #include "frame.h"              /* required by inferior.h */
26 #include "inferior.h"
27 #include "target.h"
28 #include "wait.h"
29 #include "gdbcore.h"
30 #include "command.h"
31 #include "floatformat.h"
32
33 #include <stdio.h>              /* required for __DJGPP_MINOR__ */
34 #include <stdlib.h>
35 #include <string.h>
36 #include <errno.h>
37 #include <io.h>
38 #include <dpmi.h>
39 #include <debug/v2load.h>
40 #include <debug/dbgcom.h>
41 #if __DJGPP_MINOR__ > 2
42 #include <debug/redir.h>
43 #endif
44
45 #if __DJGPP_MINOR__ < 3
46 /* This code will be provided from DJGPP 2.03 on. Until then I code it
47    here */
48 typedef struct
49   {
50     unsigned short sig0;
51     unsigned short sig1;
52     unsigned short sig2;
53     unsigned short sig3;
54     unsigned short exponent:15;
55     unsigned short sign:1;
56   }
57 NPXREG;
58
59 typedef struct
60   {
61     unsigned int control;
62     unsigned int status;
63     unsigned int tag;
64     unsigned int eip;
65     unsigned int cs;
66     unsigned int dataptr;
67     unsigned int datasel;
68     NPXREG reg[8];
69   }
70 NPX;
71
72 static NPX npx;
73
74 static void save_npx (void);    /* Save the FPU of the debugged program */
75 static void load_npx (void);    /* Restore the FPU of the debugged program */
76
77 /* ------------------------------------------------------------------------- */
78 /* Store the contents of the NPX in the global variable `npx'.  */
79 /* *INDENT-OFF* */
80
81 static void
82 save_npx (void)
83 {
84   asm ("inb    $0xa0, %%al
85        testb $0x20, %%al
86        jz 1f
87        xorb %% al, %%al
88        outb %% al, $0xf0
89        movb $0x20, %%al
90        outb %% al, $0xa0
91        outb %% al, $0x20
92 1:
93        fnsave % 0
94        fwait "
95 :     "=m" (npx)
96 :                               /* No input */
97 :     "%eax");
98 }
99
100 /* *INDENT-ON* */
101
102
103
104
105
106 /* ------------------------------------------------------------------------- */
107 /* Reload the contents of the NPX from the global variable `npx'.  */
108
109 static void
110 load_npx (void)
111 {
112 asm ("frstor %0":"=m" (npx));
113 }
114 /* ------------------------------------------------------------------------- */
115 /* Stubs for the missing redirection functions.  */
116 typedef struct {
117   char *command;
118   int redirected;
119 } cmdline_t;
120
121 void redir_cmdline_delete (cmdline_t *ptr) {ptr->redirected = 0;}
122 int  redir_cmdline_parse (const char *args, cmdline_t *ptr)
123 {
124   return -1;
125 }
126 int redir_to_child (cmdline_t *ptr)
127 {
128   return 1;
129 }
130 int redir_to_debugger (cmdline_t *ptr)
131 {
132   return 1;
133 }
134 int redir_debug_init (cmdline_t *ptr) { return 0; }
135 #endif /* __DJGPP_MINOR < 3 */
136
137 extern void _initialize_go32_nat (void);
138
139 struct env387
140   {
141     unsigned short control;
142     unsigned short r0;
143     unsigned short status;
144     unsigned short r1;
145     unsigned short tag;
146     unsigned short r2;
147     unsigned long eip;
148     unsigned short code_seg;
149     unsigned short opcode;
150     unsigned long operand;
151     unsigned short operand_seg;
152     unsigned short r3;
153     unsigned char regs[8][10];
154   };
155
156 typedef enum { wp_insert, wp_remove, wp_count } wp_op;
157
158 /* This holds the current reference counts for each debug register.  */
159 static int dr_ref_count[4];
160
161 extern char **environ;
162
163 #define SOME_PID 42
164
165 static int prog_has_started = 0;
166 static void print_387_status (unsigned short status, struct env387 *ep);
167 static void go32_open (char *name, int from_tty);
168 static void go32_close (int quitting);
169 static void go32_attach (char *args, int from_tty);
170 static void go32_detach (char *args, int from_tty);
171 static void go32_resume (int pid, int step, enum target_signal siggnal);
172 static int go32_wait (int pid, struct target_waitstatus *status);
173 static void go32_fetch_registers (int regno);
174 static void store_register (int regno);
175 static void go32_store_registers (int regno);
176 static void go32_prepare_to_store (void);
177 static int go32_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len,
178                              int write, struct target_ops *target);
179 static void go32_files_info (struct target_ops *target);
180 static void go32_stop (void);
181 static void go32_kill_inferior (void);
182 static void go32_create_inferior (char *exec_file, char *args, char **env);
183 static void cleanup_dregs (void);
184 static void go32_mourn_inferior (void);
185 static int go32_can_run (void);
186 static void ignore (void);
187 static void ignore2 (char *a, int b);
188 static int go32_insert_aligned_watchpoint (CORE_ADDR waddr, CORE_ADDR addr,
189                                            int len, int rw);
190 static int go32_remove_aligned_watchpoint (CORE_ADDR waddr, CORE_ADDR addr,
191                                            int len, int rw);
192 static int go32_handle_nonaligned_watchpoint (wp_op what, CORE_ADDR waddr,
193                                               CORE_ADDR addr, int len, int rw);
194
195 static struct target_ops go32_ops;
196 static void go32_terminal_init (void);
197 static void go32_terminal_inferior (void);
198 static void go32_terminal_ours (void);
199
200 static void
201 print_387_status (unsigned short status, struct env387 *ep)
202 {
203   int i;
204   int bothstatus;
205   int top;
206   int fpreg;
207
208   bothstatus = ((status != 0) && (ep->status != 0));
209   if (status != 0)
210     {
211       if (bothstatus)
212         printf_unfiltered ("u: ");
213       print_387_status_word (status);
214     }
215
216   if (ep->status != 0)
217     {
218       if (bothstatus)
219         printf_unfiltered ("e: ");
220       print_387_status_word (ep->status);
221     }
222
223   print_387_control_word (ep->control & 0xffff);
224   /* Other platforms say "last exception", but that's not true: the
225      FPU stores the last non-control instruction there.  */
226   printf_unfiltered ("last FP instruction: ");
227   /* The ORing with D800h restores the upper 5 bits of the opcode that
228      are not stored by the FPU (since these bits are the same for all
229      floating-point instructions).  */
230   printf_unfiltered ("opcode %s; ",
231                      local_hex_string (ep->opcode ? (ep->opcode|0xd800) : 0));
232   printf_unfiltered ("pc %s:", local_hex_string (ep->code_seg));
233   printf_unfiltered ("%s; ", local_hex_string (ep->eip));
234   printf_unfiltered ("operand %s", local_hex_string (ep->operand_seg));
235   printf_unfiltered (":%s\n", local_hex_string (ep->operand));
236
237   top = (ep->status >> 11) & 7;
238
239   printf_unfiltered ("regno tag     msb              lsb  value\n");
240   for (fpreg = 7; fpreg >= 0; fpreg--)
241     {
242       /* FNSAVE saves the FP registers in their logical TOP-relative
243          order, beginning with ST(0).  Since we need to print them in
244          their physical order, we have to remap them.  */
245       int  regno = fpreg - top;
246       long double val;
247
248       if (regno < 0)
249         regno += 8;
250
251       printf_unfiltered ("%s %d: ", fpreg == top ? "=>" : "  ", fpreg);
252
253       switch ((ep->tag >> (fpreg * 2)) & 3)
254         {
255         case 0:
256           printf_unfiltered ("valid   ");
257           break;
258         case 1:
259           printf_unfiltered ("zero    ");
260           break;
261         case 2:
262           /* All other versions of print_387_status use TRAP here, but I
263              think this is misleading, since Intel manuals say SPECIAL.  */
264           printf_unfiltered ("special ");
265           break;
266         case 3:
267           printf_unfiltered ("empty   ");
268           break;
269         }
270       for (i = 9; i >= 0; i--)
271         printf_unfiltered ("%02x", ep->regs[regno][i]);
272
273       REGISTER_CONVERT_TO_VIRTUAL (FP0_REGNUM+regno, builtin_type_long_double,
274                                    &ep->regs[regno], &val);
275
276       printf_unfiltered ("  %.19LG\n", val);
277     }
278 }
279
280 void
281 i386_go32_float_info (void)
282 {
283   print_387_status (0, (struct env387 *) &npx);
284 }
285
286 #define r_ofs(x) (offsetof(TSS,x))
287
288 static struct
289 {
290   size_t tss_ofs;
291   size_t size;
292 }
293 regno_mapping[] =
294 {
295   r_ofs (tss_eax), 4,   /* normal registers, from a_tss */
296     r_ofs (tss_ecx), 4,
297     r_ofs (tss_edx), 4,
298     r_ofs (tss_ebx), 4,
299     r_ofs (tss_esp), 4,
300     r_ofs (tss_ebp), 4,
301     r_ofs (tss_esi), 4,
302     r_ofs (tss_edi), 4,
303     r_ofs (tss_eip), 4,
304     r_ofs (tss_eflags), 4,
305     r_ofs (tss_cs), 2,
306     r_ofs (tss_ss), 2,
307     r_ofs (tss_ds), 2,
308     r_ofs (tss_es), 2,
309     r_ofs (tss_fs), 2,
310     r_ofs (tss_gs), 2,
311     0, 10,              /* 8 FP registers, from npx.reg[] */
312     1, 10,
313     2, 10,
314     3, 10,
315     4, 10,
316     5, 10,
317     6, 10,
318     7, 10,
319         /* The order of the next 7 registers must be consistent
320            with their numbering in config/i386/tm-go32.h, which see.  */
321   0, 2,                 /* control word, from npx */
322   4, 2,                 /* status word, from npx */
323   8, 2,                 /* tag word, from npx */
324   16, 2,                /* last FP exception CS from npx */
325   24, 2,                /* last FP exception operand selector from npx */
326   12, 4,                /* last FP exception EIP from npx */
327   20, 4                 /* last FP exception operand offset from npx */
328 };
329
330 static struct
331   {
332     int go32_sig;
333     int gdb_sig;
334   }
335 sig_map[] =
336 {
337   0, TARGET_SIGNAL_FPE,
338     1, TARGET_SIGNAL_TRAP,
339   /* Exception 2 is triggered by the NMI.  DJGPP handles it as SIGILL,
340      but I think SIGBUS is better, since the NMI is usually activated
341      as a result of a memory parity check failure.  */
342     2, TARGET_SIGNAL_BUS,
343     3, TARGET_SIGNAL_TRAP,
344     4, TARGET_SIGNAL_FPE,
345     5, TARGET_SIGNAL_SEGV,
346     6, TARGET_SIGNAL_ILL,
347     7, TARGET_SIGNAL_FPE,
348     8, TARGET_SIGNAL_SEGV,
349     9, TARGET_SIGNAL_SEGV,
350     10, TARGET_SIGNAL_BUS,
351     11, TARGET_SIGNAL_SEGV,
352     12, TARGET_SIGNAL_SEGV,
353     13, TARGET_SIGNAL_SEGV,
354     14, TARGET_SIGNAL_SEGV,
355     16, TARGET_SIGNAL_FPE,
356     17, TARGET_SIGNAL_BUS,
357     31, TARGET_SIGNAL_ILL,
358     0x1b, TARGET_SIGNAL_INT,
359     0x75, TARGET_SIGNAL_FPE,
360     0x78, TARGET_SIGNAL_ALRM,
361     0x79, TARGET_SIGNAL_INT,
362     0x7a, TARGET_SIGNAL_QUIT,
363     -1, -1
364 };
365
366 static struct {
367   enum target_signal gdb_sig;
368   int djgpp_excepno;
369 } excepn_map[] = {
370   TARGET_SIGNAL_0, -1,
371   TARGET_SIGNAL_ILL, 6,         /* Invalid Opcode */
372   TARGET_SIGNAL_EMT, 7,         /* triggers SIGNOFP */
373   TARGET_SIGNAL_SEGV, 13,       /* GPF */
374   TARGET_SIGNAL_BUS, 17,        /* Alignment Check */
375   /* The rest are fake exceptions, see dpmiexcp.c in djlsr*.zip for
376      details.  */
377   TARGET_SIGNAL_TERM, 0x1b,     /* triggers Ctrl-Break type of SIGINT */
378   TARGET_SIGNAL_FPE, 0x75,
379   TARGET_SIGNAL_INT, 0x79,
380   TARGET_SIGNAL_QUIT, 0x7a,
381   TARGET_SIGNAL_ALRM, 0x78,     /* triggers SIGTIMR */
382   TARGET_SIGNAL_PROF, 0x78,
383   -1, -1
384 };
385
386 static void
387 go32_open (char *name, int from_tty)
388 {
389   printf_unfiltered ("Done.  Use the \"run\" command to run the program.\n");
390 }
391
392 static void
393 go32_close (int quitting)
394 {
395 }
396
397 static void
398 go32_attach (char *args, int from_tty)
399 {
400   error ("\
401 You cannot attach to a running program on this platform.\n\
402 Use the `run' command to run DJGPP programs.");
403 }
404
405 static void
406 go32_detach (char *args, int from_tty)
407 {
408 }
409
410 static int resume_is_step;
411 static int resume_signal = -1;
412
413 static void
414 go32_resume (int pid, int step, enum target_signal siggnal)
415 {
416   int i;
417
418   resume_is_step = step;
419
420   if (siggnal != TARGET_SIGNAL_0 && siggnal != TARGET_SIGNAL_TRAP)
421   {
422     for (i = 0, resume_signal = -1; excepn_map[i].gdb_sig != -1; i++)
423       if (excepn_map[i].gdb_sig == siggnal)
424       {
425         resume_signal = excepn_map[i].djgpp_excepno;
426         break;
427       }
428     if (resume_signal == -1)
429       printf_unfiltered ("Cannot deliver signal %s on this platform.\n",
430                          target_signal_to_name (siggnal));
431   }
432 }
433
434 static char child_cwd[FILENAME_MAX];
435
436 static int
437 go32_wait (int pid, struct target_waitstatus *status)
438 {
439   int i;
440   unsigned char saved_opcode;
441   unsigned long INT3_addr;
442   int stepping_over_INT = 0;
443
444   a_tss.tss_eflags &= 0xfeff;   /* reset the single-step flag (TF) */
445   if (resume_is_step)
446     {
447       /* If the next instruction is INT xx or INTO, we need to handle
448          them specially.  Intel manuals say that these instructions
449          reset the single-step flag (a.k.a. TF).  However, it seems
450          that, at least in the DPMI environment, and at least when
451          stepping over the DPMI interrupt 31h, the problem is having
452          TF set at all when INT 31h is executed: the debuggee either
453          crashes (and takes the system with it) or is killed by a
454          SIGTRAP.
455
456          So we need to emulate single-step mode: we put an INT3 opcode
457          right after the INT xx instruction, let the debuggee run
458          until it hits INT3 and stops, then restore the original
459          instruction which we overwrote with the INT3 opcode, and back
460          up the debuggee's EIP to that instruction.  */
461       read_child (a_tss.tss_eip, &saved_opcode, 1);
462       if (saved_opcode == 0xCD || saved_opcode == 0xCE)
463         {
464           unsigned char INT3_opcode = 0xCC;
465
466           INT3_addr
467             = saved_opcode == 0xCD ? a_tss.tss_eip + 2 : a_tss.tss_eip + 1;
468           stepping_over_INT = 1;
469           read_child (INT3_addr, &saved_opcode, 1);
470           write_child (INT3_addr, &INT3_opcode, 1);
471         }
472       else
473         a_tss.tss_eflags |= 0x0100; /* normal instruction: set TF */
474     }
475
476   /* The special value FFFFh in tss_trap indicates to run_child that
477      tss_irqn holds a signal to be delivered to the debuggee.  */
478   if (resume_signal <= -1)
479     {
480       a_tss.tss_trap = 0;
481       a_tss.tss_irqn = 0xff;
482     }
483   else
484     {
485       a_tss.tss_trap = 0xffff;  /* run_child looks for this */
486       a_tss.tss_irqn = resume_signal;
487     }
488
489   /* The child might change working directory behind our back.  The
490      GDB users won't like the side effects of that when they work with
491      relative file names, and GDB might be confused by its current
492      directory not being in sync with the truth.  So we always make a
493      point of changing back to where GDB thinks is its cwd, when we
494      return control to the debugger, but restore child's cwd before we
495      run it.  */
496   chdir (child_cwd);
497
498 #if __DJGPP_MINOR__ < 3
499   load_npx ();
500 #endif
501   run_child ();
502 #if __DJGPP_MINOR__ < 3
503   save_npx ();
504 #endif
505
506   /* Did we step over an INT xx instruction?  */
507   if (stepping_over_INT && a_tss.tss_eip == INT3_addr + 1)
508     {
509       /* Restore the original opcode.  */
510       a_tss.tss_eip--;  /* EIP points *after* the INT3 instruction */
511       write_child (a_tss.tss_eip, &saved_opcode, 1);
512       /* Simulate a TRAP exception.  */
513       a_tss.tss_irqn = 1;
514       a_tss.tss_eflags |= 0x0100;
515     }
516
517   getcwd (child_cwd, sizeof (child_cwd)); /* in case it has changed */
518   chdir (current_directory);
519
520   if (a_tss.tss_irqn == 0x21)
521     {
522       status->kind = TARGET_WAITKIND_EXITED;
523       status->value.integer = a_tss.tss_eax & 0xff;
524     }
525   else
526     {
527       status->value.sig = TARGET_SIGNAL_UNKNOWN;
528       status->kind = TARGET_WAITKIND_STOPPED;
529       for (i = 0; sig_map[i].go32_sig != -1; i++)
530         {
531           if (a_tss.tss_irqn == sig_map[i].go32_sig)
532             {
533 #if __DJGPP_MINOR__ < 3
534               if ((status->value.sig = sig_map[i].gdb_sig) !=
535                   TARGET_SIGNAL_TRAP)
536                 status->kind = TARGET_WAITKIND_SIGNALLED;
537 #else
538               status->value.sig = sig_map[i].gdb_sig;
539 #endif
540               break;
541             }
542         }
543     }
544   return SOME_PID;
545 }
546
547 static void
548 go32_fetch_registers (int regno)
549 {
550   /*JHW */
551   int end_reg = regno + 1;      /* just one reg initially */
552
553   if (regno < 0)                /* do the all registers */
554     {
555       regno = 0;                /* start at first register */
556       /* # regs in table */
557       end_reg = sizeof (regno_mapping) / sizeof (regno_mapping[0]);
558     }
559
560   for (; regno < end_reg; regno++)
561     {
562       if (regno < 16)
563         supply_register (regno,
564                          (char *) &a_tss + regno_mapping[regno].tss_ofs);
565       else if (regno < 24)
566         supply_register (regno,
567                          (char *) &npx.reg[regno_mapping[regno].tss_ofs]);
568       else if (regno < 31)
569         supply_register (regno,
570                          (char *) &npx + regno_mapping[regno].tss_ofs);
571       else
572         fatal ("Invalid register no. %d in go32_fetch_register.", regno);
573     }
574 }
575
576 static void
577 store_register (int regno)
578 {
579   void *rp;
580   void *v = (void *) &registers[REGISTER_BYTE (regno)];
581
582   if (regno < 16)
583     rp = (char *) &a_tss + regno_mapping[regno].tss_ofs;
584   else if (regno < 24)
585     rp = (char *) &npx.reg[regno_mapping[regno].tss_ofs];
586   else if (regno < 31)
587     rp = (char *) &npx + regno_mapping[regno].tss_ofs;
588   else
589     fatal ("Invalid register no. %d in store_register.", regno);
590   memcpy (rp, v, regno_mapping[regno].size);
591 }
592
593 static void
594 go32_store_registers (int regno)
595 {
596   int r;
597
598   if (regno >= 0)
599     store_register (regno);
600   else
601     {
602       for (r = 0; r < sizeof (regno_mapping) / sizeof (regno_mapping[0]); r++)
603         store_register (r);
604     }
605 }
606
607 static void
608 go32_prepare_to_store (void)
609 {
610 }
611
612 static int
613 go32_xfer_memory (CORE_ADDR memaddr, char *myaddr, int len, int write,
614                   struct target_ops *target)
615 {
616   if (write)
617     {
618       if (write_child (memaddr, myaddr, len))
619         {
620           return 0;
621         }
622       else
623         {
624           return len;
625         }
626     }
627   else
628     {
629       if (read_child (memaddr, myaddr, len))
630         {
631           return 0;
632         }
633       else
634         {
635           return len;
636         }
637     }
638 }
639
640 static cmdline_t child_cmd;     /* parsed child's command line kept here */
641
642 static void
643 go32_files_info (struct target_ops *target)
644 {
645   printf_unfiltered ("You are running a DJGPP V2 program.\n");
646 }
647
648 static void
649 go32_stop (void)
650 {
651   normal_stop ();
652   cleanup_client ();
653   inferior_pid = 0;
654   prog_has_started = 0;
655 }
656
657 static void
658 go32_kill_inferior (void)
659 {
660   redir_cmdline_delete (&child_cmd);
661   resume_signal = -1;
662   resume_is_step = 0;
663   unpush_target (&go32_ops);
664 }
665
666 static void
667 go32_create_inferior (char *exec_file, char *args, char **env)
668 {
669   jmp_buf start_state;
670   char *cmdline;
671   char **env_save = environ;
672
673   if (prog_has_started)
674     {
675       go32_stop ();
676       go32_kill_inferior ();
677     }
678   resume_signal = -1;
679   resume_is_step = 0;
680   /* Init command line storage.  */
681   if (redir_debug_init (&child_cmd) == -1)
682     fatal ("Cannot allocate redirection storage: not enough memory.\n");
683
684   /* Parse the command line and create redirections.  */
685   if (strpbrk (args, "<>"))
686     {
687       if (redir_cmdline_parse (args, &child_cmd) == 0)
688         args = child_cmd.command;
689       else
690         error ("Syntax error in command line.");
691     }
692   else
693     child_cmd.command = strdup (args);
694
695   cmdline = (char *) alloca (strlen (args) + 4);
696   cmdline[0] = strlen (args);
697   strcpy (cmdline + 1, args);
698   cmdline[strlen (args) + 1] = 13;
699
700   environ = env;
701
702   if (v2loadimage (exec_file, cmdline, start_state))
703     {
704       environ = env_save;
705       printf_unfiltered ("Load failed for image %s\n", exec_file);
706       exit (1);
707     }
708   environ = env_save;
709
710   edi_init (start_state);
711 #if __DJGPP_MINOR__ < 3
712   save_npx ();
713 #endif
714
715   inferior_pid = SOME_PID;
716   push_target (&go32_ops);
717   clear_proceed_status ();
718   insert_breakpoints ();
719   proceed ((CORE_ADDR) - 1, TARGET_SIGNAL_0, 0);
720   prog_has_started = 1;
721 }
722
723 static void
724 go32_mourn_inferior (void)
725 {
726   /* We need to make sure all the breakpoint enable bits in the DR7
727      register are reset when the inferior exits.  Otherwise, if they
728      rerun the inferior, the uncleared bits may cause random SIGTRAPs,
729      failure to set more watchpoints, and other calamities.  It would
730      be nice if GDB itself would take care to remove all breakpoints
731      at all times, but it doesn't, probably under an assumption that
732      the OS cleans up when the debuggee exits.  */
733   cleanup_dregs ();
734   go32_kill_inferior ();
735   generic_mourn_inferior ();
736 }
737
738 static int
739 go32_can_run (void)
740 {
741   return 1;
742 }
743
744 static void
745 ignore (void)
746 {
747 }
748
749 /* Hardware watchpoint support.  */
750
751 #define DR_STATUS 6
752 #define DR_CONTROL 7
753 #define DR_ENABLE_SIZE 2
754 #define DR_LOCAL_ENABLE_SHIFT 0
755 #define DR_GLOBAL_ENABLE_SHIFT 1
756 #define DR_LOCAL_SLOWDOWN 0x100
757 #define DR_GLOBAL_SLOWDOWN 0x200
758 #define DR_CONTROL_SHIFT 16
759 #define DR_CONTROL_SIZE 4
760 #define DR_RW_READWRITE 0x3
761 #define DR_RW_WRITE 0x1
762 #define DR_CONTROL_MASK 0xf
763 #define DR_ENABLE_MASK 0x3
764 #define DR_LEN_1 0x0
765 #define DR_LEN_2 0x4
766 #define DR_LEN_4 0xc
767
768 #define D_REGS edi.dr
769 #define CONTROL D_REGS[DR_CONTROL]
770 #define STATUS D_REGS[DR_STATUS]
771
772 #define IS_REG_FREE(index) \
773   (!(CONTROL & (3 << (DR_ENABLE_SIZE * (index)))))
774
775 #define LOCAL_ENABLE_REG(index) \
776   (CONTROL |= (1 << (DR_LOCAL_ENABLE_SHIFT + DR_ENABLE_SIZE * (index))))
777
778 #define GLOBAL_ENABLE_REG(index) \
779   (CONTROL |= (1 << (DR_GLOBAL_ENABLE_SHIFT + DR_ENABLE_SIZE * (index))))
780
781 #define DISABLE_REG(index) \
782   (CONTROL &= ~(3 << (DR_ENABLE_SIZE * (index))))
783
784 #define SET_LOCAL_EXACT() \
785   (CONTROL |= DR_LOCAL_SLOWDOWN)
786
787 #define SET_GLOBAL_EXACT() \
788   (CONTROL |= DR_GLOBAL_SLOWDOWN)
789
790 #define RESET_LOCAL_EXACT() \
791    (CONTROL &= ~(DR_LOCAL_SLOWDOWN))
792
793 #define RESET_GLOBAL_EXACT() \
794    (CONTROL &= ~(DR_GLOBAL_SLOWDOWN))
795
796 #define SET_BREAK(index,address) \
797   do {\
798     CONTROL &= ~(DR_CONTROL_MASK << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (index)));\
799     D_REGS[index] = address;\
800   } while(0)
801
802 #define SET_WATCH(index,address,rw,len) \
803   do {\
804     SET_BREAK(index,address);\
805     CONTROL |= ((len)|(rw)) << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (index));\
806   } while (0)
807
808 #define IS_WATCH(index) \
809   (CONTROL & (DR_CONTROL_MASK << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE*(index))))
810
811 #define WATCH_HIT(index) \
812   (\
813    (STATUS & (1 << index)) && \
814    (CONTROL & (DR_CONTROL_MASK << (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * index)))\
815   )
816
817 #define DR_DEF(index) \
818   ((CONTROL >> (DR_CONTROL_SHIFT + DR_CONTROL_SIZE * (index))) & 0x0f)
819     
820
821 #if 0 /* use debugging macro */
822 #define SHOW_DR(text,len) \
823 do { \
824   if (!getenv ("GDB_SHOW_DR")) break; \
825   fprintf(stderr,"%08x %08x ",edi.dr[7],edi.dr[6]); \
826   fprintf(stderr,"%08x %d %08x %d ", \
827           edi.dr[0],dr_ref_count[0],edi.dr[1],dr_ref_count[1]); \
828   fprintf(stderr,"%08x %d %08x %d ", \
829           edi.dr[2],dr_ref_count[2],edi.dr[3],dr_ref_count[3]); \
830   fprintf(stderr,(len)?"(%s:%d)\n":"(%s)\n",#text,len); \
831 } while (0)
832 #else
833 #define SHOW_DR(text,len) do {} while (0)
834 #endif
835
836 static void
837 cleanup_dregs (void)
838 {
839   int i;
840
841   CONTROL = 0;
842   STATUS = 0;
843   for (i = 0; i < 4; i++)
844     {
845       D_REGS[i] = 0;
846       dr_ref_count[i] = 0;
847     }
848 }
849
850 /* Insert a watchpoint.  */
851
852 int
853 go32_insert_watchpoint (int pid, CORE_ADDR addr, int len, int rw)
854 {
855   int ret = go32_insert_aligned_watchpoint (addr, addr, len, rw);
856
857   SHOW_DR (insert_watch, len);
858   return ret;
859 }
860
861 static int
862 go32_insert_aligned_watchpoint (CORE_ADDR waddr, CORE_ADDR addr,
863                                 int len, int rw)
864 {
865   int i;
866   int read_write_bits, len_bits;
867
868   /* Values of rw: 0 - write, 1 - read, 2 - access (read and write).
869      However, x86 doesn't support read-only data breakpoints.  */
870   read_write_bits = rw ? DR_RW_READWRITE : DR_RW_WRITE;
871
872   switch (len)
873   {
874   case 4:
875     len_bits = DR_LEN_4;
876     break;
877   case 2:
878     len_bits = DR_LEN_2;
879     break;
880   case 1:
881     len_bits = DR_LEN_1;
882     break;
883   default:
884     /* The debug registers only have 2 bits for the length, so
885        so this value will always fail the loop below.  */
886     len_bits = 0x10;
887   }
888
889   /* Look for an occupied debug register with the same address and the
890      same RW and LEN definitions.  If we find one, we can use it for
891      this watchpoint as well (and save a register).  */
892   for (i = 0; i < 4; i++)
893   {
894     if (!IS_REG_FREE (i) && D_REGS[i] == addr
895         && DR_DEF (i) == (len_bits | read_write_bits))
896     {
897       dr_ref_count[i]++;
898       return 0;
899     }
900   }
901
902   /* Look for a free debug register.  */
903   for (i = 0; i <= 3; i++)
904   {
905     if (IS_REG_FREE (i))
906       break;
907   }
908
909   /* No more debug registers!  */
910   if (i > 3)
911     return -1;
912
913   if (len == 2)
914   {
915     if (addr % 2)
916       return go32_handle_nonaligned_watchpoint (wp_insert, waddr, addr,
917                                                 len, rw);
918   }
919   else if (len == 4)
920   {
921     if (addr % 4)
922       return go32_handle_nonaligned_watchpoint (wp_insert, waddr, addr,
923                                                 len, rw);
924   }
925   else if (len != 1)
926     return go32_handle_nonaligned_watchpoint (wp_insert, waddr, addr, len, rw);
927
928   SET_WATCH (i, addr, read_write_bits, len_bits);
929   LOCAL_ENABLE_REG (i);
930   SET_LOCAL_EXACT ();
931   SET_GLOBAL_EXACT ();
932   return 0;
933 }
934
935 static int
936 go32_handle_nonaligned_watchpoint (wp_op what, CORE_ADDR waddr, CORE_ADDR addr,
937                                    int len, int rw)
938 {
939   int align;
940   int size;
941   int rv = 0, status = 0;
942
943   static int size_try_array[16] =
944   {
945     1, 1, 1, 1,                 /* trying size one */
946     2, 1, 2, 1,                 /* trying size two */
947     2, 1, 2, 1,                 /* trying size three */
948     4, 1, 2, 1                  /* trying size four */
949   };
950
951   while (len > 0)
952     {
953       align = addr % 4;
954       /* Four is the maximum length for 386.  */
955       size = (len > 4) ? 3 : len - 1;
956       size = size_try_array[size * 4 + align];
957       if (what == wp_insert)
958         status = go32_insert_aligned_watchpoint (waddr, addr, size, rw);
959       else if (what == wp_remove)
960         status = go32_remove_aligned_watchpoint (waddr, addr, size, rw);
961       else if (what == wp_count)
962         rv++;
963       else
964         status = -1;
965       /* We keep the loop going even after a failure, because some of
966          the other aligned watchpoints might still succeed, e.g. if
967          they watch addresses that are already watched, and thus just
968          increment the reference counts of occupied debug registers.
969          If we break out of the loop too early, we could cause those
970          addresses watched by other watchpoints to be disabled when
971          GDB reacts to our failure to insert this watchpoint and tries
972          to remove it.  */
973       if (status)
974         rv = status;
975       addr += size;
976       len -= size;
977     }
978   return rv;
979 }
980
981 /* Remove a watchpoint.  */
982
983 int
984 go32_remove_watchpoint (int pid, CORE_ADDR addr, int len, int rw)
985 {
986   int ret = go32_remove_aligned_watchpoint (addr, addr, len, rw);
987
988   SHOW_DR (remove_watch, len);
989   return ret;
990 }
991
992 static int
993 go32_remove_aligned_watchpoint (CORE_ADDR waddr, CORE_ADDR addr,
994                                 int len, int rw)
995 {
996   int i;
997   int read_write_bits, len_bits;
998
999   /* Values of rw: 0 - write, 1 - read, 2 - access (read and write).
1000      However, x86 doesn't support read-only data breakpoints.  */
1001   read_write_bits = rw ? DR_RW_READWRITE : DR_RW_WRITE;
1002
1003   switch (len)
1004     {
1005       case 4:
1006         len_bits = DR_LEN_4;
1007         break;
1008       case 2:
1009         len_bits = DR_LEN_2;
1010         break;
1011       case 1:
1012         len_bits = DR_LEN_1;
1013         break;
1014       default:
1015         /* The debug registers only have 2 bits for the length, so
1016            so this value will always fail the loop below.  */
1017         len_bits = 0x10;
1018     }
1019
1020   if (len == 2)
1021     {
1022       if (addr % 2)
1023         return go32_handle_nonaligned_watchpoint (wp_remove, waddr, addr,
1024                                                   len, rw);
1025     }
1026   else if (len == 4)
1027     {
1028       if (addr % 4)
1029         return go32_handle_nonaligned_watchpoint (wp_remove, waddr, addr,
1030                                                   len, rw);
1031     }
1032   else if (len != 1)
1033     return go32_handle_nonaligned_watchpoint (wp_remove, waddr, addr, len, rw);
1034
1035   for (i = 0; i <= 3; i++)
1036     {
1037       if (!IS_REG_FREE (i) && D_REGS[i] == addr
1038           && DR_DEF (i) == (len_bits | read_write_bits))
1039         {
1040           dr_ref_count[i]--;
1041           if (dr_ref_count[i] == 0)
1042             DISABLE_REG (i);
1043         }
1044     }
1045   RESET_LOCAL_EXACT ();
1046   RESET_GLOBAL_EXACT ();
1047
1048   return 0;
1049 }
1050
1051 /* Can we use debug registers to watch a region whose address is ADDR
1052    and whose length is LEN bytes?  */
1053
1054 int
1055 go32_region_ok_for_watchpoint (CORE_ADDR addr, int len)
1056 {
1057   /* Compute how many aligned watchpoints we would need to cover this
1058      region.  */
1059   int nregs = go32_handle_nonaligned_watchpoint (wp_count, addr, addr, len, 0);
1060
1061   return nregs <= 4 ? 1 : 0;
1062 }
1063
1064 /* Check if stopped by a data watchpoint.  If so, return the address
1065    whose access triggered the watchpoint.  */
1066
1067 CORE_ADDR
1068 go32_stopped_by_watchpoint (int pid, int data_watchpoint)
1069 {
1070   int i, ret = 0;
1071   int status;
1072
1073   status = edi.dr[DR_STATUS];
1074   SHOW_DR (stopped_by, 0);
1075   for (i = 0; i <= 3; i++)
1076     {
1077       if (WATCH_HIT (i) && data_watchpoint)
1078         {
1079           SHOW_DR (WP_HIT, 0);
1080           ret = D_REGS[i];
1081         }
1082     }
1083
1084   return ret;
1085 }
1086
1087 /* Remove a breakpoint.  */
1088
1089 int
1090 go32_remove_hw_breakpoint (CORE_ADDR addr, CORE_ADDR shadow)
1091 {
1092   int i;
1093   for (i = 0; i <= 3; i++)
1094     {
1095       if (!IS_REG_FREE (i) && D_REGS[i] == addr && DR_DEF (i) == 0)
1096         {
1097           dr_ref_count[i]--;
1098           if (dr_ref_count[i] == 0)
1099             DISABLE_REG (i);
1100         }
1101     }
1102   SHOW_DR (remove_hw, 0);
1103   return 0;
1104 }
1105
1106 int
1107 go32_insert_hw_breakpoint (CORE_ADDR addr, CORE_ADDR shadow)
1108 {
1109   int i;
1110   int read_write_bits, len_bits;
1111   int free_debug_register;
1112   int register_number;
1113
1114   /* Look for an occupied debug register with the same address and the
1115      same RW and LEN definitions.  If we find one, we can use it for
1116      this breakpoint as well (and save a register).  */
1117   for (i = 0; i < 4; i++)
1118     {
1119       if (!IS_REG_FREE (i) && D_REGS[i] == addr && DR_DEF (i) == 0)
1120         {
1121           dr_ref_count[i]++;
1122           SHOW_DR (insert_hw, 0);
1123           return 0;
1124         }
1125     }
1126
1127   /* Look for a free debug register.  */
1128   for (i = 0; i <= 3; i++)
1129     {
1130       if (IS_REG_FREE (i))
1131         break;
1132     }
1133
1134   /* No more debug registers?  */
1135   if (i < 4)
1136     {
1137       SET_BREAK (i, addr);
1138       LOCAL_ENABLE_REG (i);
1139     }
1140   SHOW_DR (insert_hw, 0);
1141
1142   return i < 4 ? 0 : -1;
1143 }
1144
1145 static int inf_flags_valid = 0;
1146 static int inf_in_flag;
1147 static int inf_out_flag;
1148
1149 /* Put the device open on handle FD into either raw or cooked
1150    mode, return 1 if it was in raw mode, zero otherwise.  */
1151
1152 static int
1153 device_mode (int fd, int raw_p)
1154 {
1155   int oldmode, newmode;
1156   __dpmi_regs regs;
1157
1158   regs.x.ax = 0x4400;
1159   regs.x.bx = fd;
1160   __dpmi_int (0x21, &regs);
1161   if (regs.x.flags & 1)
1162     return -1;
1163   newmode = oldmode = regs.x.dx;
1164
1165   if (raw_p)
1166     newmode |= 0x20;
1167   else
1168     newmode &= ~0x20;
1169
1170   if (oldmode & 0x80)   /* Only for character dev */
1171   {
1172     regs.x.ax = 0x4401;
1173     regs.x.bx = fd;
1174     regs.x.dx = newmode & 0xff;   /* Force upper byte zero, else it fails */
1175     __dpmi_int (0x21, &regs);
1176     if (regs.x.flags & 1)
1177       return -1;
1178   }
1179   return (oldmode & 0x20) == 0x20;
1180 }
1181
1182
1183 static int inf_mode_valid = 0;
1184 static int inf_terminal_mode;
1185
1186 /* This semaphore is needed because, amazingly enough, GDB calls
1187    target.to_terminal_ours more than once after the inferior stops.
1188    But we need the information from the first call only, since the
1189    second call will always see GDB's own cooked terminal.  */
1190 static int terminal_is_ours = 1;
1191
1192 static void
1193 go32_terminal_init (void)
1194 {
1195   inf_mode_valid = 0;   /* reinitialize, in case they are restarting child */
1196   terminal_is_ours = 1;
1197 }
1198
1199 static void
1200 go32_terminal_info (char *args, int from_tty)
1201 {
1202   printf_unfiltered ("Inferior's terminal is in %s mode.\n",
1203                      !inf_mode_valid
1204                      ? "default" : inf_terminal_mode ? "raw" : "cooked");
1205
1206 #if __DJGPP_MINOR__ > 2
1207   if (child_cmd.redirection)
1208   {
1209     int i;
1210
1211     for (i = 0; i < DBG_HANDLES; i++)
1212     {
1213       if (child_cmd.redirection[i]->file_name)
1214         printf_unfiltered ("\tFile handle %d is redirected to `%s'.\n",
1215                            i, child_cmd.redirection[i]->file_name);
1216       else if (_get_dev_info (child_cmd.redirection[i]->inf_handle) == -1)
1217         printf_unfiltered
1218           ("\tFile handle %d appears to be closed by inferior.\n", i);
1219       /* Mask off the raw/cooked bit when comparing device info words.  */
1220       else if ((_get_dev_info (child_cmd.redirection[i]->inf_handle) & 0xdf)
1221                != (_get_dev_info (i) & 0xdf))
1222         printf_unfiltered
1223           ("\tFile handle %d appears to be redirected by inferior.\n", i);
1224     }
1225   }
1226 #endif
1227 }
1228
1229 static void
1230 go32_terminal_inferior (void)
1231 {
1232   /* Redirect standard handles as child wants them.  */
1233   errno = 0;
1234   if (redir_to_child (&child_cmd) == -1)
1235   {
1236     redir_to_debugger (&child_cmd);
1237     error ("Cannot redirect standard handles for program: %s.",
1238            strerror (errno));
1239   }
1240   /* set the console device of the inferior to whatever mode
1241      (raw or cooked) we found it last time */
1242   if (terminal_is_ours)
1243   {
1244     if (inf_mode_valid)
1245       device_mode (0, inf_terminal_mode);
1246     terminal_is_ours = 0;
1247   }
1248 }
1249
1250 static void
1251 go32_terminal_ours (void)
1252 {
1253   /* Switch to cooked mode on the gdb terminal and save the inferior
1254      terminal mode to be restored when it is resumed */
1255   if (!terminal_is_ours)
1256   {
1257     inf_terminal_mode = device_mode (0, 0);
1258     if (inf_terminal_mode != -1)
1259       inf_mode_valid = 1;
1260     else
1261       /* If device_mode returned -1, we don't know what happens with
1262          handle 0 anymore, so make the info invalid.  */
1263       inf_mode_valid = 0;
1264     terminal_is_ours = 1;
1265
1266     /* Restore debugger's standard handles.  */
1267     errno = 0;
1268     if (redir_to_debugger (&child_cmd) == -1)
1269     {
1270       redir_to_child (&child_cmd);
1271       error ("Cannot redirect standard handles for debugger: %s.",
1272              strerror (errno));
1273     }
1274   }
1275 }
1276
1277 static void
1278 init_go32_ops (void)
1279 {
1280   go32_ops.to_shortname = "djgpp";
1281   go32_ops.to_longname = "djgpp target process";
1282   go32_ops.to_doc =
1283     "Program loaded by djgpp, when gdb is used as an external debugger";
1284   go32_ops.to_open = go32_open;
1285   go32_ops.to_close = go32_close;
1286   go32_ops.to_attach = go32_attach;
1287   go32_ops.to_detach = go32_detach;
1288   go32_ops.to_resume = go32_resume;
1289   go32_ops.to_wait = go32_wait;
1290   go32_ops.to_fetch_registers = go32_fetch_registers;
1291   go32_ops.to_store_registers = go32_store_registers;
1292   go32_ops.to_prepare_to_store = go32_prepare_to_store;
1293   go32_ops.to_xfer_memory = go32_xfer_memory;
1294   go32_ops.to_files_info = go32_files_info;
1295   go32_ops.to_insert_breakpoint = memory_insert_breakpoint;
1296   go32_ops.to_remove_breakpoint = memory_remove_breakpoint;
1297   go32_ops.to_terminal_init = go32_terminal_init;
1298   go32_ops.to_terminal_inferior = go32_terminal_inferior;
1299   go32_ops.to_terminal_ours_for_output = go32_terminal_ours;
1300   go32_ops.to_terminal_ours = go32_terminal_ours;
1301   go32_ops.to_terminal_info = go32_terminal_info;
1302   go32_ops.to_kill = go32_kill_inferior;
1303   go32_ops.to_create_inferior = go32_create_inferior;
1304   go32_ops.to_mourn_inferior = go32_mourn_inferior;
1305   go32_ops.to_can_run = go32_can_run;
1306   go32_ops.to_stop = go32_stop;
1307   go32_ops.to_stratum = process_stratum;
1308   go32_ops.to_has_all_memory = 1;
1309   go32_ops.to_has_memory = 1;
1310   go32_ops.to_has_stack = 1;
1311   go32_ops.to_has_registers = 1;
1312   go32_ops.to_has_execution = 1;
1313   go32_ops.to_magic = OPS_MAGIC;
1314
1315   /* Initialize child's cwd with the current one.  */
1316   getcwd (child_cwd, sizeof (child_cwd));
1317
1318   /* Initialize child's command line storage.  */
1319   if (redir_debug_init (&child_cmd) == -1)
1320     fatal ("Cannot allocate redirection storage: not enough memory.\n");
1321 }
1322
1323 void
1324 _initialize_go32_nat (void)
1325 {
1326   init_go32_ops ();
1327   add_target (&go32_ops);
1328 }
1329
1330 pid_t
1331 tcgetpgrp (int fd)
1332 {
1333   if (isatty (fd))
1334     return SOME_PID;
1335   errno = ENOTTY;
1336   return -1;
1337 }
1338
1339 int
1340 tcsetpgrp (int fd, pid_t pgid)
1341 {
1342   if (isatty (fd) && pgid == SOME_PID)
1343     return 0;
1344   errno = pgid == SOME_PID ? ENOTTY : ENOSYS;
1345   return -1;
1346 }