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