* go32-nat.c (fetch_register, store_register): Pass the regcache
[platform/upstream/binutils.git] / gdb / go32-nat.c
1 /* Native debugging support for Intel x86 running DJGPP.
2    Copyright (C) 1997, 1999, 2000, 2001, 2005, 2006, 2007, 2008
3    Free Software Foundation, Inc.
4    Written by Robert Hoehne.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include <fcntl.h>
22
23 #include "defs.h"
24 #include "inferior.h"
25 #include "gdb_wait.h"
26 #include "gdbcore.h"
27 #include "command.h"
28 #include "gdbcmd.h"
29 #include "floatformat.h"
30 #include "buildsym.h"
31 #include "i387-tdep.h"
32 #include "i386-tdep.h"
33 #include "value.h"
34 #include "regcache.h"
35 #include "gdb_string.h"
36 #include "top.h"
37
38 #include <stdio.h>              /* might be required for __DJGPP_MINOR__ */
39 #include <stdlib.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <unistd.h>
43 #include <sys/utsname.h>
44 #include <io.h>
45 #include <dos.h>
46 #include <dpmi.h>
47 #include <go32.h>
48 #include <sys/farptr.h>
49 #include <debug/v2load.h>
50 #include <debug/dbgcom.h>
51 #if __DJGPP_MINOR__ > 2
52 #include <debug/redir.h>
53 #endif
54
55 #if __DJGPP_MINOR__ < 3
56 /* This code will be provided from DJGPP 2.03 on. Until then I code it
57    here */
58 typedef struct
59   {
60     unsigned short sig0;
61     unsigned short sig1;
62     unsigned short sig2;
63     unsigned short sig3;
64     unsigned short exponent:15;
65     unsigned short sign:1;
66   }
67 NPXREG;
68
69 typedef struct
70   {
71     unsigned int control;
72     unsigned int status;
73     unsigned int tag;
74     unsigned int eip;
75     unsigned int cs;
76     unsigned int dataptr;
77     unsigned int datasel;
78     NPXREG reg[8];
79   }
80 NPX;
81
82 static NPX npx;
83
84 static void save_npx (void);    /* Save the FPU of the debugged program */
85 static void load_npx (void);    /* Restore the FPU of the debugged program */
86
87 /* ------------------------------------------------------------------------- */
88 /* Store the contents of the NPX in the global variable `npx'.  */
89 /* *INDENT-OFF* */
90
91 static void
92 save_npx (void)
93 {
94   asm ("inb    $0xa0, %%al  \n\
95        testb $0x20, %%al    \n\
96        jz 1f                \n\
97        xorb %%al, %%al      \n\
98        outb %%al, $0xf0     \n\
99        movb $0x20, %%al     \n\
100        outb %%al, $0xa0     \n\
101        outb %%al, $0x20     \n\
102 1:                          \n\
103        fnsave %0            \n\
104        fwait "
105 :     "=m" (npx)
106 :                               /* No input */
107 :     "%eax");
108 }
109
110 /* *INDENT-ON* */
111
112
113 /* ------------------------------------------------------------------------- */
114 /* Reload the contents of the NPX from the global variable `npx'.  */
115
116 static void
117 load_npx (void)
118 {
119   asm ("frstor %0":"=m" (npx));
120 }
121 /* ------------------------------------------------------------------------- */
122 /* Stubs for the missing redirection functions.  */
123 typedef struct {
124   char *command;
125   int redirected;
126 } cmdline_t;
127
128 void
129 redir_cmdline_delete (cmdline_t *ptr)
130 {
131   ptr->redirected = 0;
132 }
133
134 int
135 redir_cmdline_parse (const char *args, cmdline_t *ptr)
136 {
137   return -1;
138 }
139
140 int
141 redir_to_child (cmdline_t *ptr)
142 {
143   return 1;
144 }
145
146 int
147 redir_to_debugger (cmdline_t *ptr)
148 {
149   return 1;
150 }
151
152 int
153 redir_debug_init (cmdline_t *ptr)
154 {
155   return 0;
156 }
157 #endif /* __DJGPP_MINOR < 3 */
158
159 typedef enum { wp_insert, wp_remove, wp_count } wp_op;
160
161 /* This holds the current reference counts for each debug register.  */
162 static int dr_ref_count[4];
163
164 #define SOME_PID 42
165
166 static int prog_has_started = 0;
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 (ptid_t ptid, int step,
172                          enum target_signal siggnal);
173 static ptid_t go32_wait (ptid_t ptid,
174                                struct target_waitstatus *status);
175 static void go32_fetch_registers (struct regcache *, int regno);
176 static void store_register (const struct regcache *, int regno);
177 static void go32_store_registers (struct regcache *, int regno);
178 static void go32_prepare_to_store (struct regcache *);
179 static int go32_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len,
180                              int write,
181                              struct mem_attrib *attrib,
182                              struct target_ops *target);
183 static void go32_files_info (struct target_ops *target);
184 static void go32_stop (ptid_t);
185 static void go32_kill_inferior (void);
186 static void go32_create_inferior (char *exec_file, char *args, char **env, int from_tty);
187 static void go32_mourn_inferior (void);
188 static int go32_can_run (void);
189
190 static struct target_ops go32_ops;
191 static void go32_terminal_init (void);
192 static void go32_terminal_inferior (void);
193 static void go32_terminal_ours (void);
194
195 #define r_ofs(x) (offsetof(TSS,x))
196
197 static struct
198 {
199   size_t tss_ofs;
200   size_t size;
201 }
202 regno_mapping[] =
203 {
204   {r_ofs (tss_eax), 4}, /* normal registers, from a_tss */
205   {r_ofs (tss_ecx), 4},
206   {r_ofs (tss_edx), 4},
207   {r_ofs (tss_ebx), 4},
208   {r_ofs (tss_esp), 4},
209   {r_ofs (tss_ebp), 4},
210   {r_ofs (tss_esi), 4},
211   {r_ofs (tss_edi), 4},
212   {r_ofs (tss_eip), 4},
213   {r_ofs (tss_eflags), 4},
214   {r_ofs (tss_cs), 2},
215   {r_ofs (tss_ss), 2},
216   {r_ofs (tss_ds), 2},
217   {r_ofs (tss_es), 2},
218   {r_ofs (tss_fs), 2},
219   {r_ofs (tss_gs), 2},
220   {0, 10},              /* 8 FP registers, from npx.reg[] */
221   {1, 10},
222   {2, 10},
223   {3, 10},
224   {4, 10},
225   {5, 10},
226   {6, 10},
227   {7, 10},
228         /* The order of the next 7 registers must be consistent
229            with their numbering in config/i386/tm-i386.h, which see.  */
230   {0, 2},               /* control word, from npx */
231   {4, 2},               /* status word, from npx */
232   {8, 2},               /* tag word, from npx */
233   {16, 2},              /* last FP exception CS from npx */
234   {12, 4},              /* last FP exception EIP from npx */
235   {24, 2},              /* last FP exception operand selector from npx */
236   {20, 4},              /* last FP exception operand offset from npx */
237   {18, 2}               /* last FP opcode from npx */
238 };
239
240 static struct
241   {
242     int go32_sig;
243     enum target_signal gdb_sig;
244   }
245 sig_map[] =
246 {
247   {0, TARGET_SIGNAL_FPE},
248   {1, TARGET_SIGNAL_TRAP},
249   /* Exception 2 is triggered by the NMI.  DJGPP handles it as SIGILL,
250      but I think SIGBUS is better, since the NMI is usually activated
251      as a result of a memory parity check failure.  */
252   {2, TARGET_SIGNAL_BUS},
253   {3, TARGET_SIGNAL_TRAP},
254   {4, TARGET_SIGNAL_FPE},
255   {5, TARGET_SIGNAL_SEGV},
256   {6, TARGET_SIGNAL_ILL},
257   {7, TARGET_SIGNAL_EMT},       /* no-coprocessor exception */
258   {8, TARGET_SIGNAL_SEGV},
259   {9, TARGET_SIGNAL_SEGV},
260   {10, TARGET_SIGNAL_BUS},
261   {11, TARGET_SIGNAL_SEGV},
262   {12, TARGET_SIGNAL_SEGV},
263   {13, TARGET_SIGNAL_SEGV},
264   {14, TARGET_SIGNAL_SEGV},
265   {16, TARGET_SIGNAL_FPE},
266   {17, TARGET_SIGNAL_BUS},
267   {31, TARGET_SIGNAL_ILL},
268   {0x1b, TARGET_SIGNAL_INT},
269   {0x75, TARGET_SIGNAL_FPE},
270   {0x78, TARGET_SIGNAL_ALRM},
271   {0x79, TARGET_SIGNAL_INT},
272   {0x7a, TARGET_SIGNAL_QUIT},
273   {-1, TARGET_SIGNAL_LAST}
274 };
275
276 static struct {
277   enum target_signal gdb_sig;
278   int djgpp_excepno;
279 } excepn_map[] = {
280   {TARGET_SIGNAL_0, -1},
281   {TARGET_SIGNAL_ILL, 6},       /* Invalid Opcode */
282   {TARGET_SIGNAL_EMT, 7},       /* triggers SIGNOFP */
283   {TARGET_SIGNAL_SEGV, 13},     /* GPF */
284   {TARGET_SIGNAL_BUS, 17},      /* Alignment Check */
285   /* The rest are fake exceptions, see dpmiexcp.c in djlsr*.zip for
286      details.  */
287   {TARGET_SIGNAL_TERM, 0x1b},   /* triggers Ctrl-Break type of SIGINT */
288   {TARGET_SIGNAL_FPE, 0x75},
289   {TARGET_SIGNAL_INT, 0x79},
290   {TARGET_SIGNAL_QUIT, 0x7a},
291   {TARGET_SIGNAL_ALRM, 0x78},   /* triggers SIGTIMR */
292   {TARGET_SIGNAL_PROF, 0x78},
293   {TARGET_SIGNAL_LAST, -1}
294 };
295
296 static void
297 go32_open (char *name, int from_tty)
298 {
299   printf_unfiltered ("Done.  Use the \"run\" command to run the program.\n");
300 }
301
302 static void
303 go32_close (int quitting)
304 {
305 }
306
307 static void
308 go32_attach (char *args, int from_tty)
309 {
310   error (_("\
311 You cannot attach to a running program on this platform.\n\
312 Use the `run' command to run DJGPP programs."));
313 }
314
315 static void
316 go32_detach (char *args, int from_tty)
317 {
318 }
319
320 static int resume_is_step;
321 static int resume_signal = -1;
322
323 static void
324 go32_resume (ptid_t ptid, int step, enum target_signal siggnal)
325 {
326   int i;
327
328   resume_is_step = step;
329
330   if (siggnal != TARGET_SIGNAL_0 && siggnal != TARGET_SIGNAL_TRAP)
331   {
332     for (i = 0, resume_signal = -1;
333          excepn_map[i].gdb_sig != TARGET_SIGNAL_LAST; i++)
334       if (excepn_map[i].gdb_sig == siggnal)
335       {
336         resume_signal = excepn_map[i].djgpp_excepno;
337         break;
338       }
339     if (resume_signal == -1)
340       printf_unfiltered ("Cannot deliver signal %s on this platform.\n",
341                          target_signal_to_name (siggnal));
342   }
343 }
344
345 static char child_cwd[FILENAME_MAX];
346
347 static ptid_t
348 go32_wait (ptid_t ptid, struct target_waitstatus *status)
349 {
350   int i;
351   unsigned char saved_opcode;
352   unsigned long INT3_addr = 0;
353   int stepping_over_INT = 0;
354
355   a_tss.tss_eflags &= 0xfeff;   /* reset the single-step flag (TF) */
356   if (resume_is_step)
357     {
358       /* If the next instruction is INT xx or INTO, we need to handle
359          them specially.  Intel manuals say that these instructions
360          reset the single-step flag (a.k.a. TF).  However, it seems
361          that, at least in the DPMI environment, and at least when
362          stepping over the DPMI interrupt 31h, the problem is having
363          TF set at all when INT 31h is executed: the debuggee either
364          crashes (and takes the system with it) or is killed by a
365          SIGTRAP.
366
367          So we need to emulate single-step mode: we put an INT3 opcode
368          right after the INT xx instruction, let the debuggee run
369          until it hits INT3 and stops, then restore the original
370          instruction which we overwrote with the INT3 opcode, and back
371          up the debuggee's EIP to that instruction.  */
372       read_child (a_tss.tss_eip, &saved_opcode, 1);
373       if (saved_opcode == 0xCD || saved_opcode == 0xCE)
374         {
375           unsigned char INT3_opcode = 0xCC;
376
377           INT3_addr
378             = saved_opcode == 0xCD ? a_tss.tss_eip + 2 : a_tss.tss_eip + 1;
379           stepping_over_INT = 1;
380           read_child (INT3_addr, &saved_opcode, 1);
381           write_child (INT3_addr, &INT3_opcode, 1);
382         }
383       else
384         a_tss.tss_eflags |= 0x0100; /* normal instruction: set TF */
385     }
386
387   /* The special value FFFFh in tss_trap indicates to run_child that
388      tss_irqn holds a signal to be delivered to the debuggee.  */
389   if (resume_signal <= -1)
390     {
391       a_tss.tss_trap = 0;
392       a_tss.tss_irqn = 0xff;
393     }
394   else
395     {
396       a_tss.tss_trap = 0xffff;  /* run_child looks for this */
397       a_tss.tss_irqn = resume_signal;
398     }
399
400   /* The child might change working directory behind our back.  The
401      GDB users won't like the side effects of that when they work with
402      relative file names, and GDB might be confused by its current
403      directory not being in sync with the truth.  So we always make a
404      point of changing back to where GDB thinks is its cwd, when we
405      return control to the debugger, but restore child's cwd before we
406      run it.  */
407   /* Initialize child_cwd, before the first call to run_child and not
408      in the initialization, so the child get also the changed directory
409      set with the gdb-command "cd ..." */
410   if (!*child_cwd)
411     /* Initialize child's cwd with the current one.  */
412     getcwd (child_cwd, sizeof (child_cwd));
413
414   chdir (child_cwd);
415
416 #if __DJGPP_MINOR__ < 3
417   load_npx ();
418 #endif
419   run_child ();
420 #if __DJGPP_MINOR__ < 3
421   save_npx ();
422 #endif
423
424   /* Did we step over an INT xx instruction?  */
425   if (stepping_over_INT && a_tss.tss_eip == INT3_addr + 1)
426     {
427       /* Restore the original opcode.  */
428       a_tss.tss_eip--;  /* EIP points *after* the INT3 instruction */
429       write_child (a_tss.tss_eip, &saved_opcode, 1);
430       /* Simulate a TRAP exception.  */
431       a_tss.tss_irqn = 1;
432       a_tss.tss_eflags |= 0x0100;
433     }
434
435   getcwd (child_cwd, sizeof (child_cwd)); /* in case it has changed */
436   chdir (current_directory);
437
438   if (a_tss.tss_irqn == 0x21)
439     {
440       status->kind = TARGET_WAITKIND_EXITED;
441       status->value.integer = a_tss.tss_eax & 0xff;
442     }
443   else
444     {
445       status->value.sig = TARGET_SIGNAL_UNKNOWN;
446       status->kind = TARGET_WAITKIND_STOPPED;
447       for (i = 0; sig_map[i].go32_sig != -1; i++)
448         {
449           if (a_tss.tss_irqn == sig_map[i].go32_sig)
450             {
451 #if __DJGPP_MINOR__ < 3
452               if ((status->value.sig = sig_map[i].gdb_sig) !=
453                   TARGET_SIGNAL_TRAP)
454                 status->kind = TARGET_WAITKIND_SIGNALLED;
455 #else
456               status->value.sig = sig_map[i].gdb_sig;
457 #endif
458               break;
459             }
460         }
461     }
462   return pid_to_ptid (SOME_PID);
463 }
464
465 static void
466 fetch_register (struct regcache *regcache, int regno)
467 {
468   struct gdbarch *gdbarch = get_regcache_arch (regcache);
469   if (regno < gdbarch_fp0_regnum (gdbarch))
470     regcache_raw_supply (regcache, regno,
471                          (char *) &a_tss + regno_mapping[regno].tss_ofs);
472   else if (i386_fp_regnum_p (gdbarch, regno) || i386_fpc_regnum_p (gdbarch, regno))
473     i387_supply_fsave (regcache, regno, &npx);
474   else
475     internal_error (__FILE__, __LINE__,
476                     _("Invalid register no. %d in fetch_register."), regno);
477 }
478
479 static void
480 go32_fetch_registers (struct regcache *regcache, int regno)
481 {
482   if (regno >= 0)
483     fetch_register (regcache, regno);
484   else
485     {
486       for (regno = 0;
487            regno < gdbarch_fp0_regnum (get_regcache_arch (regcache));
488            regno++)
489         fetch_register (regcache, regno);
490       i387_supply_fsave (regcache, -1, &npx);
491     }
492 }
493
494 static void
495 store_register (const struct regcache *regcache, int regno)
496 {
497   struct gdbarch *gdbarch = get_regcache_arch (regcache);
498   if (regno < gdbarch_fp0_regnum (gdbarch))
499     regcache_raw_collect (regcache, regno,
500                           (char *) &a_tss + regno_mapping[regno].tss_ofs);
501   else if (i386_fp_regnum_p (gdbarch, regno) || i386_fpc_regnum_p (gdbarch, regno))
502     i387_collect_fsave (regcache, regno, &npx);
503   else
504     internal_error (__FILE__, __LINE__,
505                     _("Invalid register no. %d in store_register."), regno);
506 }
507
508 static void
509 go32_store_registers (struct regcache *regcache, int regno)
510 {
511   unsigned r;
512
513   if (regno >= 0)
514     store_register (regcache, regno);
515   else
516     {
517       for (r = 0; r < gdbarch_fp0_regnum (get_regcache_arch (regcache)); r++)
518         store_register (regcache, r);
519       i387_collect_fsave (regcache, -1, &npx);
520     }
521 }
522
523 static void
524 go32_prepare_to_store (struct regcache *regcache)
525 {
526 }
527
528 static int
529 go32_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len, int write,
530                   struct mem_attrib *attrib, struct target_ops *target)
531 {
532   if (write)
533     {
534       if (write_child (memaddr, myaddr, len))
535         {
536           return 0;
537         }
538       else
539         {
540           return len;
541         }
542     }
543   else
544     {
545       if (read_child (memaddr, myaddr, len))
546         {
547           return 0;
548         }
549       else
550         {
551           return len;
552         }
553     }
554 }
555
556 static cmdline_t child_cmd;     /* parsed child's command line kept here */
557
558 static void
559 go32_files_info (struct target_ops *target)
560 {
561   printf_unfiltered ("You are running a DJGPP V2 program.\n");
562 }
563
564 static void
565 go32_stop (ptid_t ptid)
566 {
567   normal_stop ();
568   cleanup_client ();
569   inferior_ptid = null_ptid;
570   prog_has_started = 0;
571 }
572
573 static void
574 go32_kill_inferior (void)
575 {
576   redir_cmdline_delete (&child_cmd);
577   resume_signal = -1;
578   resume_is_step = 0;
579   unpush_target (&go32_ops);
580 }
581
582 static void
583 go32_create_inferior (char *exec_file, char *args, char **env, int from_tty)
584 {
585   extern char **environ;
586   jmp_buf start_state;
587   char *cmdline;
588   char **env_save = environ;
589   size_t cmdlen;
590
591   /* If no exec file handed to us, get it from the exec-file command -- with
592      a good, common error message if none is specified.  */
593   if (exec_file == 0)
594     exec_file = get_exec_file (1);
595
596   if (prog_has_started)
597     {
598       go32_stop (inferior_ptid);
599       go32_kill_inferior ();
600     }
601   resume_signal = -1;
602   resume_is_step = 0;
603
604   /* Initialize child's cwd as empty to be initialized when starting
605      the child.  */
606   *child_cwd = 0;
607
608   /* Init command line storage.  */
609   if (redir_debug_init (&child_cmd) == -1)
610     internal_error (__FILE__, __LINE__,
611                     _("Cannot allocate redirection storage: not enough memory.\n"));
612
613   /* Parse the command line and create redirections.  */
614   if (strpbrk (args, "<>"))
615     {
616       if (redir_cmdline_parse (args, &child_cmd) == 0)
617         args = child_cmd.command;
618       else
619         error (_("Syntax error in command line."));
620     }
621   else
622     child_cmd.command = xstrdup (args);
623
624   cmdlen = strlen (args);
625   /* v2loadimage passes command lines via DOS memory, so it cannot
626      possibly handle commands longer than 1MB.  */
627   if (cmdlen > 1024*1024)
628     error (_("Command line too long."));
629
630   cmdline = xmalloc (cmdlen + 4);
631   strcpy (cmdline + 1, args);
632   /* If the command-line length fits into DOS 126-char limits, use the
633      DOS command tail format; otherwise, tell v2loadimage to pass it
634      through a buffer in conventional memory.  */
635   if (cmdlen < 127)
636     {
637       cmdline[0] = strlen (args);
638       cmdline[cmdlen + 1] = 13;
639     }
640   else
641     cmdline[0] = 0xff;  /* signal v2loadimage it's a long command */
642
643   environ = env;
644
645   if (v2loadimage (exec_file, cmdline, start_state))
646     {
647       environ = env_save;
648       printf_unfiltered ("Load failed for image %s\n", exec_file);
649       exit (1);
650     }
651   environ = env_save;
652   xfree (cmdline);
653
654   edi_init (start_state);
655 #if __DJGPP_MINOR__ < 3
656   save_npx ();
657 #endif
658
659   inferior_ptid = pid_to_ptid (SOME_PID);
660   push_target (&go32_ops);
661   clear_proceed_status ();
662   insert_breakpoints ();
663   prog_has_started = 1;
664 }
665
666 static void
667 go32_mourn_inferior (void)
668 {
669   /* We need to make sure all the breakpoint enable bits in the DR7
670      register are reset when the inferior exits.  Otherwise, if they
671      rerun the inferior, the uncleared bits may cause random SIGTRAPs,
672      failure to set more watchpoints, and other calamities.  It would
673      be nice if GDB itself would take care to remove all breakpoints
674      at all times, but it doesn't, probably under an assumption that
675      the OS cleans up when the debuggee exits.  */
676   i386_cleanup_dregs ();
677   go32_kill_inferior ();
678   generic_mourn_inferior ();
679 }
680
681 static int
682 go32_can_run (void)
683 {
684   return 1;
685 }
686
687 /* Hardware watchpoint support.  */
688
689 #define D_REGS edi.dr
690 #define CONTROL D_REGS[7]
691 #define STATUS D_REGS[6]
692
693 /* Pass the address ADDR to the inferior in the I'th debug register.
694    Here we just store the address in D_REGS, the watchpoint will be
695    actually set up when go32_wait runs the debuggee.  */
696 void
697 go32_set_dr (int i, CORE_ADDR addr)
698 {
699   if (i < 0 || i > 3)
700     internal_error (__FILE__, __LINE__, 
701                     _("Invalid register %d in go32_set_dr.\n"), i);
702   D_REGS[i] = addr;
703 }
704
705 /* Pass the value VAL to the inferior in the DR7 debug control
706    register.  Here we just store the address in D_REGS, the watchpoint
707    will be actually set up when go32_wait runs the debuggee.  */
708 void
709 go32_set_dr7 (unsigned val)
710 {
711   CONTROL = val;
712 }
713
714 /* Get the value of the DR6 debug status register from the inferior.
715    Here we just return the value stored in D_REGS, as we've got it
716    from the last go32_wait call.  */
717 unsigned
718 go32_get_dr6 (void)
719 {
720   return STATUS;
721 }
722
723 /* Put the device open on handle FD into either raw or cooked
724    mode, return 1 if it was in raw mode, zero otherwise.  */
725
726 static int
727 device_mode (int fd, int raw_p)
728 {
729   int oldmode, newmode;
730   __dpmi_regs regs;
731
732   regs.x.ax = 0x4400;
733   regs.x.bx = fd;
734   __dpmi_int (0x21, &regs);
735   if (regs.x.flags & 1)
736     return -1;
737   newmode = oldmode = regs.x.dx;
738
739   if (raw_p)
740     newmode |= 0x20;
741   else
742     newmode &= ~0x20;
743
744   if (oldmode & 0x80)   /* Only for character dev */
745   {
746     regs.x.ax = 0x4401;
747     regs.x.bx = fd;
748     regs.x.dx = newmode & 0xff;   /* Force upper byte zero, else it fails */
749     __dpmi_int (0x21, &regs);
750     if (regs.x.flags & 1)
751       return -1;
752   }
753   return (oldmode & 0x20) == 0x20;
754 }
755
756
757 static int inf_mode_valid = 0;
758 static int inf_terminal_mode;
759
760 /* This semaphore is needed because, amazingly enough, GDB calls
761    target.to_terminal_ours more than once after the inferior stops.
762    But we need the information from the first call only, since the
763    second call will always see GDB's own cooked terminal.  */
764 static int terminal_is_ours = 1;
765
766 static void
767 go32_terminal_init (void)
768 {
769   inf_mode_valid = 0;   /* reinitialize, in case they are restarting child */
770   terminal_is_ours = 1;
771 }
772
773 static void
774 go32_terminal_info (char *args, int from_tty)
775 {
776   printf_unfiltered ("Inferior's terminal is in %s mode.\n",
777                      !inf_mode_valid
778                      ? "default" : inf_terminal_mode ? "raw" : "cooked");
779
780 #if __DJGPP_MINOR__ > 2
781   if (child_cmd.redirection)
782   {
783     int i;
784
785     for (i = 0; i < DBG_HANDLES; i++)
786     {
787       if (child_cmd.redirection[i]->file_name)
788         printf_unfiltered ("\tFile handle %d is redirected to `%s'.\n",
789                            i, child_cmd.redirection[i]->file_name);
790       else if (_get_dev_info (child_cmd.redirection[i]->inf_handle) == -1)
791         printf_unfiltered
792           ("\tFile handle %d appears to be closed by inferior.\n", i);
793       /* Mask off the raw/cooked bit when comparing device info words.  */
794       else if ((_get_dev_info (child_cmd.redirection[i]->inf_handle) & 0xdf)
795                != (_get_dev_info (i) & 0xdf))
796         printf_unfiltered
797           ("\tFile handle %d appears to be redirected by inferior.\n", i);
798     }
799   }
800 #endif
801 }
802
803 static void
804 go32_terminal_inferior (void)
805 {
806   /* Redirect standard handles as child wants them.  */
807   errno = 0;
808   if (redir_to_child (&child_cmd) == -1)
809   {
810     redir_to_debugger (&child_cmd);
811     error (_("Cannot redirect standard handles for program: %s."),
812            safe_strerror (errno));
813   }
814   /* set the console device of the inferior to whatever mode
815      (raw or cooked) we found it last time */
816   if (terminal_is_ours)
817   {
818     if (inf_mode_valid)
819       device_mode (0, inf_terminal_mode);
820     terminal_is_ours = 0;
821   }
822 }
823
824 static void
825 go32_terminal_ours (void)
826 {
827   /* Switch to cooked mode on the gdb terminal and save the inferior
828      terminal mode to be restored when it is resumed */
829   if (!terminal_is_ours)
830   {
831     inf_terminal_mode = device_mode (0, 0);
832     if (inf_terminal_mode != -1)
833       inf_mode_valid = 1;
834     else
835       /* If device_mode returned -1, we don't know what happens with
836          handle 0 anymore, so make the info invalid.  */
837       inf_mode_valid = 0;
838     terminal_is_ours = 1;
839
840     /* Restore debugger's standard handles.  */
841     errno = 0;
842     if (redir_to_debugger (&child_cmd) == -1)
843     {
844       redir_to_child (&child_cmd);
845       error (_("Cannot redirect standard handles for debugger: %s."),
846              safe_strerror (errno));
847     }
848   }
849 }
850
851 static void
852 init_go32_ops (void)
853 {
854   go32_ops.to_shortname = "djgpp";
855   go32_ops.to_longname = "djgpp target process";
856   go32_ops.to_doc =
857     "Program loaded by djgpp, when gdb is used as an external debugger";
858   go32_ops.to_open = go32_open;
859   go32_ops.to_close = go32_close;
860   go32_ops.to_attach = go32_attach;
861   go32_ops.to_detach = go32_detach;
862   go32_ops.to_resume = go32_resume;
863   go32_ops.to_wait = go32_wait;
864   go32_ops.to_fetch_registers = go32_fetch_registers;
865   go32_ops.to_store_registers = go32_store_registers;
866   go32_ops.to_prepare_to_store = go32_prepare_to_store;
867   go32_ops.deprecated_xfer_memory = go32_xfer_memory;
868   go32_ops.to_files_info = go32_files_info;
869   go32_ops.to_insert_breakpoint = memory_insert_breakpoint;
870   go32_ops.to_remove_breakpoint = memory_remove_breakpoint;
871   go32_ops.to_terminal_init = go32_terminal_init;
872   go32_ops.to_terminal_inferior = go32_terminal_inferior;
873   go32_ops.to_terminal_ours_for_output = go32_terminal_ours;
874   go32_ops.to_terminal_ours = go32_terminal_ours;
875   go32_ops.to_terminal_info = go32_terminal_info;
876   go32_ops.to_kill = go32_kill_inferior;
877   go32_ops.to_create_inferior = go32_create_inferior;
878   go32_ops.to_mourn_inferior = go32_mourn_inferior;
879   go32_ops.to_can_run = go32_can_run;
880   go32_ops.to_stop = go32_stop;
881   go32_ops.to_stratum = process_stratum;
882   go32_ops.to_has_all_memory = 1;
883   go32_ops.to_has_memory = 1;
884   go32_ops.to_has_stack = 1;
885   go32_ops.to_has_registers = 1;
886   go32_ops.to_has_execution = 1;
887   go32_ops.to_magic = OPS_MAGIC;
888
889   /* Initialize child's cwd as empty to be initialized when starting
890      the child.  */
891   *child_cwd = 0;
892
893   /* Initialize child's command line storage.  */
894   if (redir_debug_init (&child_cmd) == -1)
895     internal_error (__FILE__, __LINE__,
896                     _("Cannot allocate redirection storage: not enough memory.\n"));
897
898   /* We are always processing GCC-compiled programs.  */
899   processing_gcc_compilation = 2;
900
901   /* Override the default name of the GDB init file.  */
902   strcpy (gdbinit, "gdb.ini");
903 }
904
905 unsigned short windows_major, windows_minor;
906
907 /* Compute the version Windows reports via Int 2Fh/AX=1600h.  */
908 static void
909 go32_get_windows_version(void)
910 {
911   __dpmi_regs r;
912
913   r.x.ax = 0x1600;
914   __dpmi_int(0x2f, &r);
915   if (r.h.al > 2 && r.h.al != 0x80 && r.h.al != 0xff
916       && (r.h.al > 3 || r.h.ah > 0))
917     {
918       windows_major = r.h.al;
919       windows_minor = r.h.ah;
920     }
921   else
922     windows_major = 0xff;       /* meaning no Windows */
923 }
924
925 /* A subroutine of go32_sysinfo to display memory info.  */
926 static void
927 print_mem (unsigned long datum, const char *header, int in_pages_p)
928 {
929   if (datum != 0xffffffffUL)
930     {
931       if (in_pages_p)
932         datum <<= 12;
933       puts_filtered (header);
934       if (datum > 1024)
935         {
936           printf_filtered ("%lu KB", datum >> 10);
937           if (datum > 1024 * 1024)
938             printf_filtered (" (%lu MB)", datum >> 20);
939         }
940       else
941         printf_filtered ("%lu Bytes", datum);
942       puts_filtered ("\n");
943     }
944 }
945
946 /* Display assorted information about the underlying OS.  */
947 static void
948 go32_sysinfo (char *arg, int from_tty)
949 {
950   struct utsname u;
951   char cpuid_vendor[13];
952   unsigned cpuid_max = 0, cpuid_eax, cpuid_ebx, cpuid_ecx, cpuid_edx;
953   unsigned true_dos_version = _get_dos_version (1);
954   unsigned advertized_dos_version = ((unsigned int)_osmajor << 8) | _osminor;
955   int dpmi_flags;
956   char dpmi_vendor_info[129];
957   int dpmi_vendor_available =
958     __dpmi_get_capabilities (&dpmi_flags, dpmi_vendor_info);
959   __dpmi_version_ret dpmi_version_data;
960   long eflags;
961   __dpmi_free_mem_info mem_info;
962   __dpmi_regs regs;
963
964   cpuid_vendor[0] = '\0';
965   if (uname (&u))
966     strcpy (u.machine, "Unknown x86");
967   else if (u.machine[0] == 'i' && u.machine[1] > 4)
968     {
969       /* CPUID with EAX = 0 returns the Vendor ID.  */
970       __asm__ __volatile__ ("xorl   %%ebx, %%ebx;"
971                             "xorl   %%ecx, %%ecx;"
972                             "xorl   %%edx, %%edx;"
973                             "movl   $0,    %%eax;"
974                             "cpuid;"
975                             "movl   %%ebx,  %0;"
976                             "movl   %%edx,  %1;"
977                             "movl   %%ecx,  %2;"
978                             "movl   %%eax,  %3;"
979                             : "=m" (cpuid_vendor[0]),
980                               "=m" (cpuid_vendor[4]),
981                               "=m" (cpuid_vendor[8]),
982                               "=m" (cpuid_max)
983                             :
984                             : "%eax", "%ebx", "%ecx", "%edx");
985       cpuid_vendor[12] = '\0';
986     }
987
988   printf_filtered ("CPU Type.......................%s", u.machine);
989   if (cpuid_vendor[0])
990     printf_filtered (" (%s)", cpuid_vendor);
991   puts_filtered ("\n");
992
993   /* CPUID with EAX = 1 returns processor signature and features.  */
994   if (cpuid_max >= 1)
995     {
996       static char *brand_name[] = {
997         "",
998         " Celeron",
999         " III",
1000         " III Xeon",
1001         "", "", "", "",
1002         " 4"
1003       };
1004       char cpu_string[80];
1005       char cpu_brand[20];
1006       unsigned brand_idx;
1007       int intel_p = strcmp (cpuid_vendor, "GenuineIntel") == 0;
1008       int amd_p = strcmp (cpuid_vendor, "AuthenticAMD") == 0;
1009       unsigned cpu_family, cpu_model;
1010
1011       __asm__ __volatile__ ("movl   $1, %%eax;"
1012                             "cpuid;"
1013                             : "=a" (cpuid_eax),
1014                               "=b" (cpuid_ebx),
1015                               "=d" (cpuid_edx)
1016                             :
1017                             : "%ecx");
1018       brand_idx = cpuid_ebx & 0xff;
1019       cpu_family = (cpuid_eax >> 8) & 0xf;
1020       cpu_model  = (cpuid_eax >> 4) & 0xf;
1021       cpu_brand[0] = '\0';
1022       if (intel_p)
1023         {
1024           if (brand_idx > 0
1025               && brand_idx < sizeof(brand_name)/sizeof(brand_name[0])
1026               && *brand_name[brand_idx])
1027             strcpy (cpu_brand, brand_name[brand_idx]);
1028           else if (cpu_family == 5)
1029             {
1030               if (((cpuid_eax >> 12) & 3) == 0 && cpu_model == 4)
1031                 strcpy (cpu_brand, " MMX");
1032               else if (cpu_model > 1 && ((cpuid_eax >> 12) & 3) == 1)
1033                 strcpy (cpu_brand, " OverDrive");
1034               else if (cpu_model > 1 && ((cpuid_eax >> 12) & 3) == 2)
1035                 strcpy (cpu_brand, " Dual");
1036             }
1037           else if (cpu_family == 6 && cpu_model < 8)
1038             {
1039               switch (cpu_model)
1040                 {
1041                   case 1:
1042                     strcpy (cpu_brand, " Pro");
1043                     break;
1044                   case 3:
1045                     strcpy (cpu_brand, " II");
1046                     break;
1047                   case 5:
1048                     strcpy (cpu_brand, " II Xeon");
1049                     break;
1050                   case 6:
1051                     strcpy (cpu_brand, " Celeron");
1052                     break;
1053                   case 7:
1054                     strcpy (cpu_brand, " III");
1055                     break;
1056                 }
1057             }
1058         }
1059       else if (amd_p)
1060         {
1061           switch (cpu_family)
1062             {
1063               case 4:
1064                 strcpy (cpu_brand, "486/5x86");
1065                 break;
1066               case 5:
1067                 switch (cpu_model)
1068                   {
1069                     case 0:
1070                     case 1:
1071                     case 2:
1072                     case 3:
1073                       strcpy (cpu_brand, "-K5");
1074                       break;
1075                     case 6:
1076                     case 7:
1077                       strcpy (cpu_brand, "-K6");
1078                       break;
1079                     case 8:
1080                       strcpy (cpu_brand, "-K6-2");
1081                       break;
1082                     case 9:
1083                       strcpy (cpu_brand, "-K6-III");
1084                       break;
1085                   }
1086                 break;
1087               case 6:
1088                 switch (cpu_model)
1089                   {
1090                     case 1:
1091                     case 2:
1092                     case 4:
1093                       strcpy (cpu_brand, " Athlon");
1094                       break;
1095                     case 3:
1096                       strcpy (cpu_brand, " Duron");
1097                       break;
1098                   }
1099                 break;
1100             }
1101         }
1102       sprintf (cpu_string, "%s%s Model %d Stepping %d",
1103                intel_p ? "Pentium" : (amd_p ? "AMD" : "ix86"),
1104                cpu_brand, cpu_model, cpuid_eax & 0xf);
1105       printfi_filtered (31, "%s\n", cpu_string);
1106       if (((cpuid_edx & (6 | (0x0d << 23))) != 0)
1107           || ((cpuid_edx & 1) == 0)
1108           || (amd_p && (cpuid_edx & (3 << 30)) != 0))
1109         {
1110           puts_filtered ("CPU Features...................");
1111           /* We only list features which might be useful in the DPMI
1112              environment.  */
1113           if ((cpuid_edx & 1) == 0)
1114             puts_filtered ("No FPU "); /* it's unusual to not have an FPU */
1115           if ((cpuid_edx & (1 << 1)) != 0)
1116             puts_filtered ("VME ");
1117           if ((cpuid_edx & (1 << 2)) != 0)
1118             puts_filtered ("DE ");
1119           if ((cpuid_edx & (1 << 4)) != 0)
1120             puts_filtered ("TSC ");
1121           if ((cpuid_edx & (1 << 23)) != 0)
1122             puts_filtered ("MMX ");
1123           if ((cpuid_edx & (1 << 25)) != 0)
1124             puts_filtered ("SSE ");
1125           if ((cpuid_edx & (1 << 26)) != 0)
1126             puts_filtered ("SSE2 ");
1127           if (amd_p)
1128             {
1129               if ((cpuid_edx & (1 << 31)) != 0)
1130                 puts_filtered ("3DNow! ");
1131               if ((cpuid_edx & (1 << 30)) != 0)
1132                 puts_filtered ("3DNow!Ext");
1133             }
1134           puts_filtered ("\n");
1135         }
1136     }
1137   puts_filtered ("\n");
1138   printf_filtered ("DOS Version....................%s %s.%s",
1139                    _os_flavor, u.release, u.version);
1140   if (true_dos_version != advertized_dos_version)
1141     printf_filtered (" (disguised as v%d.%d)", _osmajor, _osminor);
1142   puts_filtered ("\n");
1143   if (!windows_major)
1144     go32_get_windows_version ();
1145   if (windows_major != 0xff)
1146     {
1147       const char *windows_flavor;
1148
1149       printf_filtered ("Windows Version................%d.%02d (Windows ",
1150                        windows_major, windows_minor);
1151       switch (windows_major)
1152         {
1153           case 3:
1154             windows_flavor = "3.X";
1155             break;
1156           case 4:
1157             switch (windows_minor)
1158               {
1159                 case 0:
1160                   windows_flavor = "95, 95A, or 95B";
1161                   break;
1162                 case 3:
1163                   windows_flavor = "95B OSR2.1 or 95C OSR2.5";
1164                   break;
1165                 case 10:
1166                   windows_flavor = "98 or 98 SE";
1167                   break;
1168                 case 90:
1169                   windows_flavor = "ME";
1170                   break;
1171                 default:
1172                   windows_flavor = "9X";
1173                   break;
1174               }
1175             break;
1176           default:
1177             windows_flavor = "??";
1178             break;
1179         }
1180       printf_filtered ("%s)\n", windows_flavor);
1181     }
1182   else if (true_dos_version == 0x532 && advertized_dos_version == 0x500)
1183     printf_filtered ("Windows Version................Windows NT or Windows 2000\n");
1184   puts_filtered ("\n");
1185   if (dpmi_vendor_available == 0)
1186     {
1187       /* The DPMI spec says the vendor string should be ASCIIZ, but
1188          I don't trust the vendors to follow that...  */
1189       if (!memchr (&dpmi_vendor_info[2], 0, 126))
1190         dpmi_vendor_info[128] = '\0';
1191       printf_filtered ("DPMI Host......................%s v%d.%d (capabilities: %#x)\n",
1192                        &dpmi_vendor_info[2],
1193                        (unsigned)dpmi_vendor_info[0],
1194                        (unsigned)dpmi_vendor_info[1],
1195                        ((unsigned)dpmi_flags & 0x7f));
1196     }
1197   __dpmi_get_version (&dpmi_version_data);
1198   printf_filtered ("DPMI Version...................%d.%02d\n",
1199                    dpmi_version_data.major, dpmi_version_data.minor);
1200   printf_filtered ("DPMI Info......................%s-bit DPMI, with%s Virtual Memory support\n",
1201                    (dpmi_version_data.flags & 1) ? "32" : "16",
1202                    (dpmi_version_data.flags & 4) ? "" : "out");
1203   printfi_filtered (31, "Interrupts reflected to %s mode\n",
1204                    (dpmi_version_data.flags & 2) ? "V86" : "Real");
1205   printfi_filtered (31, "Processor type: i%d86\n",
1206                    dpmi_version_data.cpu);
1207   printfi_filtered (31, "PIC base interrupt: Master: %#x  Slave: %#x\n",
1208                    dpmi_version_data.master_pic, dpmi_version_data.slave_pic);
1209
1210   /* a_tss is only initialized when the debuggee is first run.  */
1211   if (prog_has_started)
1212     {
1213       __asm__ __volatile__ ("pushfl ; popl %0" : "=g" (eflags));
1214       printf_filtered ("Protection.....................Ring %d (in %s), with%s I/O protection\n",
1215                        a_tss.tss_cs & 3, (a_tss.tss_cs & 4) ? "LDT" : "GDT",
1216                        (a_tss.tss_cs & 3) > ((eflags >> 12) & 3) ? "" : "out");
1217     }
1218   puts_filtered ("\n");
1219   __dpmi_get_free_memory_information (&mem_info);
1220   print_mem (mem_info.total_number_of_physical_pages,
1221              "DPMI Total Physical Memory.....", 1);
1222   print_mem (mem_info.total_number_of_free_pages,
1223              "DPMI Free Physical Memory......", 1);
1224   print_mem (mem_info.size_of_paging_file_partition_in_pages,
1225              "DPMI Swap Space................", 1);
1226   print_mem (mem_info.linear_address_space_size_in_pages,
1227              "DPMI Total Linear Address Size.", 1);
1228   print_mem (mem_info.free_linear_address_space_in_pages,
1229              "DPMI Free Linear Address Size..", 1);
1230   print_mem (mem_info.largest_available_free_block_in_bytes,
1231              "DPMI Largest Free Memory Block.", 0);
1232
1233   regs.h.ah = 0x48;
1234   regs.x.bx = 0xffff;
1235   __dpmi_int (0x21, &regs);
1236   print_mem (regs.x.bx << 4, "Free DOS Memory................", 0);
1237   regs.x.ax = 0x5800;
1238   __dpmi_int (0x21, &regs);
1239   if ((regs.x.flags & 1) == 0)
1240     {
1241       static const char *dos_hilo[] = {
1242         "Low", "", "", "", "High", "", "", "", "High, then Low"
1243       };
1244       static const char *dos_fit[] = {
1245         "First", "Best", "Last"
1246       };
1247       int hilo_idx = (regs.x.ax >> 4) & 0x0f;
1248       int fit_idx  = regs.x.ax & 0x0f;
1249
1250       if (hilo_idx > 8)
1251         hilo_idx = 0;
1252       if (fit_idx > 2)
1253         fit_idx = 0;
1254       printf_filtered ("DOS Memory Allocation..........%s memory, %s fit\n",
1255                        dos_hilo[hilo_idx], dos_fit[fit_idx]);
1256       regs.x.ax = 0x5802;
1257       __dpmi_int (0x21, &regs);
1258       if ((regs.x.flags & 1) != 0)
1259         regs.h.al = 0;
1260       printfi_filtered (31, "UMBs %sin DOS memory chain\n",
1261                         regs.h.al == 0 ? "not " : "");
1262     }
1263 }
1264
1265 struct seg_descr {
1266   unsigned short limit0;
1267   unsigned short base0;
1268   unsigned char  base1;
1269   unsigned       stype:5;
1270   unsigned       dpl:2;
1271   unsigned       present:1;
1272   unsigned       limit1:4;
1273   unsigned       available:1;
1274   unsigned       dummy:1;
1275   unsigned       bit32:1;
1276   unsigned       page_granular:1;
1277   unsigned char  base2;
1278 } __attribute__ ((packed));
1279
1280 struct gate_descr {
1281   unsigned short offset0;
1282   unsigned short selector;
1283   unsigned       param_count:5;
1284   unsigned       dummy:3;
1285   unsigned       stype:5;
1286   unsigned       dpl:2;
1287   unsigned       present:1;
1288   unsigned short offset1;
1289 } __attribute__ ((packed));
1290
1291 /* Read LEN bytes starting at logical address ADDR, and put the result
1292    into DEST.  Return 1 if success, zero if not.  */
1293 static int
1294 read_memory_region (unsigned long addr, void *dest, size_t len)
1295 {
1296   unsigned long dos_ds_limit = __dpmi_get_segment_limit (_dos_ds);
1297   int retval = 1;
1298
1299   /* For the low memory, we can simply use _dos_ds.  */
1300   if (addr <= dos_ds_limit - len)
1301     dosmemget (addr, len, dest);
1302   else
1303     {
1304       /* For memory above 1MB we need to set up a special segment to
1305          be able to access that memory.  */
1306       int sel = __dpmi_allocate_ldt_descriptors (1);
1307
1308       if (sel <= 0)
1309         retval = 0;
1310       else
1311         {
1312           int access_rights = __dpmi_get_descriptor_access_rights (sel);
1313           size_t segment_limit = len - 1;
1314
1315           /* Make sure the crucial bits in the descriptor access
1316              rights are set correctly.  Some DPMI providers might barf
1317              if we set the segment limit to something that is not an
1318              integral multiple of 4KB pages if the granularity bit is
1319              not set to byte-granular, even though the DPMI spec says
1320              it's the host's responsibility to set that bit correctly.  */
1321           if (len > 1024 * 1024)
1322             {
1323               access_rights |= 0x8000;
1324               /* Page-granular segments should have the low 12 bits of
1325                  the limit set.  */
1326               segment_limit |= 0xfff;
1327             }
1328           else
1329             access_rights &= ~0x8000;
1330
1331           if (__dpmi_set_segment_base_address (sel, addr) != -1
1332               && __dpmi_set_descriptor_access_rights (sel, access_rights) != -1
1333               && __dpmi_set_segment_limit (sel, segment_limit) != -1
1334               /* W2K silently fails to set the segment limit, leaving
1335                  it at zero; this test avoids the resulting crash.  */
1336               && __dpmi_get_segment_limit (sel) >= segment_limit)
1337             movedata (sel, 0, _my_ds (), (unsigned)dest, len);
1338           else
1339             retval = 0;
1340
1341           __dpmi_free_ldt_descriptor (sel);
1342         }
1343     }
1344   return retval;
1345 }
1346
1347 /* Get a segment descriptor stored at index IDX in the descriptor
1348    table whose base address is TABLE_BASE.  Return the descriptor
1349    type, or -1 if failure.  */
1350 static int
1351 get_descriptor (unsigned long table_base, int idx, void *descr)
1352 {
1353   unsigned long addr = table_base + idx * 8; /* 8 bytes per entry */
1354
1355   if (read_memory_region (addr, descr, 8))
1356     return (int)((struct seg_descr *)descr)->stype;
1357   return -1;
1358 }
1359
1360 struct dtr_reg {
1361   unsigned short limit __attribute__((packed));
1362   unsigned long  base  __attribute__((packed));
1363 };
1364
1365 /* Display a segment descriptor stored at index IDX in a descriptor
1366    table whose type is TYPE and whose base address is BASE_ADDR.  If
1367    FORCE is non-zero, display even invalid descriptors.  */
1368 static void
1369 display_descriptor (unsigned type, unsigned long base_addr, int idx, int force)
1370 {
1371   struct seg_descr descr;
1372   struct gate_descr gate;
1373
1374   /* Get the descriptor from the table.  */
1375   if (idx == 0 && type == 0)
1376     puts_filtered ("0x000: null descriptor\n");
1377   else if (get_descriptor (base_addr, idx, &descr) != -1)
1378     {
1379       /* For each type of descriptor table, this has a bit set if the
1380          corresponding type of selectors is valid in that table.  */
1381       static unsigned allowed_descriptors[] = {
1382           0xffffdafeL,   /* GDT */
1383           0x0000c0e0L,   /* IDT */
1384           0xffffdafaL    /* LDT */
1385       };
1386
1387       /* If the program hasn't started yet, assume the debuggee will
1388          have the same CPL as the debugger.  */
1389       int cpl = prog_has_started ? (a_tss.tss_cs & 3) : _my_cs () & 3;
1390       unsigned long limit = (descr.limit1 << 16) | descr.limit0;
1391
1392       if (descr.present
1393           && (allowed_descriptors[type] & (1 << descr.stype)) != 0)
1394         {
1395           printf_filtered ("0x%03x: ",
1396                            type == 1
1397                            ? idx : (idx * 8) | (type ? (cpl | 4) : 0));
1398           if (descr.page_granular)
1399             limit = (limit << 12) | 0xfff; /* big segment: low 12 bit set */
1400           if (descr.stype == 1 || descr.stype == 2 || descr.stype == 3
1401               || descr.stype == 9 || descr.stype == 11
1402               || (descr.stype >= 16 && descr.stype < 32))
1403             printf_filtered ("base=0x%02x%02x%04x limit=0x%08lx",
1404                              descr.base2, descr.base1, descr.base0, limit);
1405
1406           switch (descr.stype)
1407             {
1408               case 1:
1409               case 3:
1410                 printf_filtered (" 16-bit TSS  (task %sactive)",
1411                                  descr.stype == 3 ? "" : "in");
1412                 break;
1413               case 2:
1414                 puts_filtered (" LDT");
1415                 break;
1416               case 4:
1417                 memcpy (&gate, &descr, sizeof gate);
1418                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
1419                                  gate.selector, gate.offset1, gate.offset0);
1420                 printf_filtered (" 16-bit Call Gate (params=%d)",
1421                                  gate.param_count);
1422                 break;
1423               case 5:
1424                 printf_filtered ("TSS selector=0x%04x", descr.base0);
1425                 printfi_filtered (16, "Task Gate");
1426                 break;
1427               case 6:
1428               case 7:
1429                 memcpy (&gate, &descr, sizeof gate);
1430                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
1431                                  gate.selector, gate.offset1, gate.offset0);
1432                 printf_filtered (" 16-bit %s Gate",
1433                                  descr.stype == 6 ? "Interrupt" : "Trap");
1434                 break;
1435               case 9:
1436               case 11:
1437                 printf_filtered (" 32-bit TSS (task %sactive)",
1438                                  descr.stype == 3 ? "" : "in");
1439                 break;
1440               case 12:
1441                 memcpy (&gate, &descr, sizeof gate);
1442                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
1443                                  gate.selector, gate.offset1, gate.offset0);
1444                 printf_filtered (" 32-bit Call Gate (params=%d)",
1445                                  gate.param_count);
1446                 break;
1447               case 14:
1448               case 15:
1449                 memcpy (&gate, &descr, sizeof gate);
1450                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
1451                                  gate.selector, gate.offset1, gate.offset0);
1452                 printf_filtered (" 32-bit %s Gate",
1453                                  descr.stype == 14 ? "Interrupt" : "Trap");
1454                 break;
1455               case 16:          /* data segments */
1456               case 17:
1457               case 18:
1458               case 19:
1459               case 20:
1460               case 21:
1461               case 22:
1462               case 23:
1463                 printf_filtered (" %s-bit Data (%s Exp-%s%s)",
1464                                  descr.bit32 ? "32" : "16",
1465                                  descr.stype & 2 ? "Read/Write," : "Read-Only, ",
1466                                  descr.stype & 4 ? "down" : "up",
1467                                  descr.stype & 1 ? "" : ", N.Acc");
1468                 break;
1469               case 24:          /* code segments */
1470               case 25:
1471               case 26:
1472               case 27:
1473               case 28:
1474               case 29:
1475               case 30:
1476               case 31:
1477                 printf_filtered (" %s-bit Code (%s,  %sConf%s)",
1478                                  descr.bit32 ? "32" : "16",
1479                                  descr.stype & 2 ? "Exec/Read" : "Exec-Only",
1480                                  descr.stype & 4 ? "" : "N.",
1481                                  descr.stype & 1 ? "" : ", N.Acc");
1482                 break;
1483               default:
1484                 printf_filtered ("Unknown type 0x%02x", descr.stype);
1485                 break;
1486             }
1487           puts_filtered ("\n");
1488         }
1489       else if (force)
1490         {
1491           printf_filtered ("0x%03x: ",
1492                            type == 1
1493                            ? idx : (idx * 8) | (type ? (cpl | 4) : 0));
1494           if (!descr.present)
1495             puts_filtered ("Segment not present\n");
1496           else
1497             printf_filtered ("Segment type 0x%02x is invalid in this table\n",
1498                              descr.stype);
1499         }
1500     }
1501   else if (force)
1502     printf_filtered ("0x%03x: Cannot read this descriptor\n", idx);
1503 }
1504
1505 static void
1506 go32_sldt (char *arg, int from_tty)
1507 {
1508   struct dtr_reg gdtr;
1509   unsigned short ldtr = 0;
1510   int ldt_idx;
1511   struct seg_descr ldt_descr;
1512   long ldt_entry = -1L;
1513   int cpl = (prog_has_started ? a_tss.tss_cs : _my_cs ()) & 3;
1514
1515   if (arg && *arg)
1516     {
1517       while (*arg && isspace(*arg))
1518         arg++;
1519
1520       if (*arg)
1521         {
1522           ldt_entry = parse_and_eval_long (arg);
1523           if (ldt_entry < 0
1524               || (ldt_entry & 4) == 0
1525               || (ldt_entry & 3) != (cpl & 3))
1526             error (_("Invalid LDT entry 0x%03lx."), (unsigned long)ldt_entry);
1527         }
1528     }
1529
1530   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
1531   __asm__ __volatile__ ("sldt   %0" : "=m" (ldtr) : /* no inputs */ );
1532   ldt_idx = ldtr / 8;
1533   if (ldt_idx == 0)
1534     puts_filtered ("There is no LDT.\n");
1535   /* LDT's entry in the GDT must have the type LDT, which is 2.  */
1536   else if (get_descriptor (gdtr.base, ldt_idx, &ldt_descr) != 2)
1537     printf_filtered ("LDT is present (at %#x), but unreadable by GDB.\n",
1538                      ldt_descr.base0
1539                      | (ldt_descr.base1 << 16)
1540                      | (ldt_descr.base2 << 24));
1541   else
1542     {
1543       unsigned base =
1544         ldt_descr.base0
1545         | (ldt_descr.base1 << 16)
1546         | (ldt_descr.base2 << 24);
1547       unsigned limit = ldt_descr.limit0 | (ldt_descr.limit1 << 16);
1548       int max_entry;
1549
1550       if (ldt_descr.page_granular)
1551         /* Page-granular segments must have the low 12 bits of their
1552            limit set.  */
1553         limit = (limit << 12) | 0xfff;
1554       /* LDT cannot have more than 8K 8-byte entries, i.e. more than
1555          64KB.  */
1556       if (limit > 0xffff)
1557         limit = 0xffff;
1558
1559       max_entry = (limit + 1) / 8;
1560
1561       if (ldt_entry >= 0)
1562         {
1563           if (ldt_entry > limit)
1564             error (_("Invalid LDT entry %#lx: outside valid limits [0..%#x]"),
1565                    (unsigned long)ldt_entry, limit);
1566
1567           display_descriptor (ldt_descr.stype, base, ldt_entry / 8, 1);
1568         }
1569       else
1570         {
1571           int i;
1572
1573           for (i = 0; i < max_entry; i++)
1574             display_descriptor (ldt_descr.stype, base, i, 0);
1575         }
1576     }
1577 }
1578
1579 static void
1580 go32_sgdt (char *arg, int from_tty)
1581 {
1582   struct dtr_reg gdtr;
1583   long gdt_entry = -1L;
1584   int max_entry;
1585
1586   if (arg && *arg)
1587     {
1588       while (*arg && isspace(*arg))
1589         arg++;
1590
1591       if (*arg)
1592         {
1593           gdt_entry = parse_and_eval_long (arg);
1594           if (gdt_entry < 0 || (gdt_entry & 7) != 0)
1595             error (_("Invalid GDT entry 0x%03lx: not an integral multiple of 8."),
1596                    (unsigned long)gdt_entry);
1597         }
1598     }
1599
1600   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
1601   max_entry = (gdtr.limit + 1) / 8;
1602
1603   if (gdt_entry >= 0)
1604     {
1605       if (gdt_entry > gdtr.limit)
1606         error (_("Invalid GDT entry %#lx: outside valid limits [0..%#x]"),
1607                (unsigned long)gdt_entry, gdtr.limit);
1608
1609       display_descriptor (0, gdtr.base, gdt_entry / 8, 1);
1610     }
1611   else
1612     {
1613       int i;
1614
1615       for (i = 0; i < max_entry; i++)
1616         display_descriptor (0, gdtr.base, i, 0);
1617     }
1618 }
1619
1620 static void
1621 go32_sidt (char *arg, int from_tty)
1622 {
1623   struct dtr_reg idtr;
1624   long idt_entry = -1L;
1625   int max_entry;
1626
1627   if (arg && *arg)
1628     {
1629       while (*arg && isspace(*arg))
1630         arg++;
1631
1632       if (*arg)
1633         {
1634           idt_entry = parse_and_eval_long (arg);
1635           if (idt_entry < 0)
1636             error (_("Invalid (negative) IDT entry %ld."), idt_entry);
1637         }
1638     }
1639
1640   __asm__ __volatile__ ("sidt   %0" : "=m" (idtr) : /* no inputs */ );
1641   max_entry = (idtr.limit + 1) / 8;
1642   if (max_entry > 0x100)        /* no more than 256 entries */
1643     max_entry = 0x100;
1644
1645   if (idt_entry >= 0)
1646     {
1647       if (idt_entry > idtr.limit)
1648         error (_("Invalid IDT entry %#lx: outside valid limits [0..%#x]"),
1649                (unsigned long)idt_entry, idtr.limit);
1650
1651       display_descriptor (1, idtr.base, idt_entry, 1);
1652     }
1653   else
1654     {
1655       int i;
1656
1657       for (i = 0; i < max_entry; i++)
1658         display_descriptor (1, idtr.base, i, 0);
1659     }
1660 }
1661
1662 /* Cached linear address of the base of the page directory.  For
1663    now, available only under CWSDPMI.  Code based on ideas and
1664    suggestions from Charles Sandmann <sandmann@clio.rice.edu>.  */
1665 static unsigned long pdbr;
1666
1667 static unsigned long
1668 get_cr3 (void)
1669 {
1670   unsigned offset;
1671   unsigned taskreg;
1672   unsigned long taskbase, cr3;
1673   struct dtr_reg gdtr;
1674
1675   if (pdbr > 0 && pdbr <= 0xfffff)
1676     return pdbr;
1677
1678   /* Get the linear address of GDT and the Task Register.  */
1679   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
1680   __asm__ __volatile__ ("str    %0" : "=m" (taskreg) : /* no inputs */ );
1681
1682   /* Task Register is a segment selector for the TSS of the current
1683      task.  Therefore, it can be used as an index into the GDT to get
1684      at the segment descriptor for the TSS.  To get the index, reset
1685      the low 3 bits of the selector (which give the CPL).  Add 2 to the
1686      offset to point to the 3 low bytes of the base address.  */
1687   offset = gdtr.base + (taskreg & 0xfff8) + 2;
1688
1689
1690   /* CWSDPMI's task base is always under the 1MB mark.  */
1691   if (offset > 0xfffff)
1692     return 0;
1693
1694   _farsetsel (_dos_ds);
1695   taskbase  = _farnspeekl (offset) & 0xffffffU;
1696   taskbase += _farnspeekl (offset + 2) & 0xff000000U;
1697   if (taskbase > 0xfffff)
1698     return 0;
1699
1700   /* CR3 (a.k.a. PDBR, the Page Directory Base Register) is stored at
1701      offset 1Ch in the TSS.  */
1702   cr3 = _farnspeekl (taskbase + 0x1c) & ~0xfff;
1703   if (cr3 > 0xfffff)
1704     {
1705 #if 0  /* not fullly supported yet */
1706       /* The Page Directory is in UMBs.  In that case, CWSDPMI puts
1707          the first Page Table right below the Page Directory.  Thus,
1708          the first Page Table's entry for its own address and the Page
1709          Directory entry for that Page Table will hold the same
1710          physical address.  The loop below searches the entire UMB
1711          range of addresses for such an occurence.  */
1712       unsigned long addr, pte_idx;
1713
1714       for (addr = 0xb0000, pte_idx = 0xb0;
1715            pte_idx < 0xff;
1716            addr += 0x1000, pte_idx++)
1717         {
1718           if (((_farnspeekl (addr + 4 * pte_idx) & 0xfffff027) ==
1719                (_farnspeekl (addr + 0x1000) & 0xfffff027))
1720               && ((_farnspeekl (addr + 4 * pte_idx + 4) & 0xfffff000) == cr3))
1721             {
1722               cr3 = addr + 0x1000;
1723               break;
1724             }
1725         }
1726 #endif
1727
1728       if (cr3 > 0xfffff)
1729         cr3 = 0;
1730     }
1731
1732   return cr3;
1733 }
1734
1735 /* Return the N'th Page Directory entry.  */
1736 static unsigned long
1737 get_pde (int n)
1738 {
1739   unsigned long pde = 0;
1740
1741   if (pdbr && n >= 0 && n < 1024)
1742     {
1743       pde = _farpeekl (_dos_ds, pdbr + 4*n);
1744     }
1745   return pde;
1746 }
1747
1748 /* Return the N'th entry of the Page Table whose Page Directory entry
1749    is PDE.  */
1750 static unsigned long
1751 get_pte (unsigned long pde, int n)
1752 {
1753   unsigned long pte = 0;
1754
1755   /* pde & 0x80 tests the 4MB page bit.  We don't support 4MB
1756      page tables, for now.  */
1757   if ((pde & 1) && !(pde & 0x80) && n >= 0 && n < 1024)
1758     {
1759       pde &= ~0xfff;    /* clear non-address bits */
1760       pte = _farpeekl (_dos_ds, pde + 4*n);
1761     }
1762   return pte;
1763 }
1764
1765 /* Display a Page Directory or Page Table entry.  IS_DIR, if non-zero,
1766    says this is a Page Directory entry.  If FORCE is non-zero, display
1767    the entry even if its Present flag is off.  OFF is the offset of the
1768    address from the page's base address.  */
1769 static void
1770 display_ptable_entry (unsigned long entry, int is_dir, int force, unsigned off)
1771 {
1772   if ((entry & 1) != 0)
1773     {
1774       printf_filtered ("Base=0x%05lx000", entry >> 12);
1775       if ((entry & 0x100) && !is_dir)
1776         puts_filtered (" Global");
1777       if ((entry & 0x40) && !is_dir)
1778         puts_filtered (" Dirty");
1779       printf_filtered (" %sAcc.", (entry & 0x20) ? "" : "Not-");
1780       printf_filtered (" %sCached", (entry & 0x10) ? "" : "Not-");
1781       printf_filtered (" Write-%s", (entry & 8) ? "Thru" : "Back");
1782       printf_filtered (" %s", (entry & 4) ? "Usr" : "Sup");
1783       printf_filtered (" Read-%s", (entry & 2) ? "Write" : "Only");
1784       if (off)
1785         printf_filtered (" +0x%x", off);
1786       puts_filtered ("\n");
1787     }
1788   else if (force)
1789     printf_filtered ("Page%s not present or not supported; value=0x%lx.\n",
1790                      is_dir ? " Table" : "", entry >> 1);
1791 }
1792
1793 static void
1794 go32_pde (char *arg, int from_tty)
1795 {
1796   long pde_idx = -1, i;
1797
1798   if (arg && *arg)
1799     {
1800       while (*arg && isspace(*arg))
1801         arg++;
1802
1803       if (*arg)
1804         {
1805           pde_idx = parse_and_eval_long (arg);
1806           if (pde_idx < 0 || pde_idx >= 1024)
1807             error (_("Entry %ld is outside valid limits [0..1023]."), pde_idx);
1808         }
1809     }
1810
1811   pdbr = get_cr3 ();
1812   if (!pdbr)
1813     puts_filtered ("Access to Page Directories is not supported on this system.\n");
1814   else if (pde_idx >= 0)
1815     display_ptable_entry (get_pde (pde_idx), 1, 1, 0);
1816   else
1817     for (i = 0; i < 1024; i++)
1818       display_ptable_entry (get_pde (i), 1, 0, 0);
1819 }
1820
1821 /* A helper function to display entries in a Page Table pointed to by
1822    the N'th entry in the Page Directory.  If FORCE is non-zero, say
1823    something even if the Page Table is not accessible.  */
1824 static void
1825 display_page_table (long n, int force)
1826 {
1827   unsigned long pde = get_pde (n);
1828
1829   if ((pde & 1) != 0)
1830     {
1831       int i;
1832
1833       printf_filtered ("Page Table pointed to by Page Directory entry 0x%lx:\n", n);
1834       for (i = 0; i < 1024; i++)
1835         display_ptable_entry (get_pte (pde, i), 0, 0, 0);
1836       puts_filtered ("\n");
1837     }
1838   else if (force)
1839     printf_filtered ("Page Table not present; value=0x%lx.\n", pde >> 1);
1840 }
1841
1842 static void
1843 go32_pte (char *arg, int from_tty)
1844 {
1845   long pde_idx = -1L, i;
1846
1847   if (arg && *arg)
1848     {
1849       while (*arg && isspace(*arg))
1850         arg++;
1851
1852       if (*arg)
1853         {
1854           pde_idx = parse_and_eval_long (arg);
1855           if (pde_idx < 0 || pde_idx >= 1024)
1856             error (_("Entry %ld is outside valid limits [0..1023]."), pde_idx);
1857         }
1858     }
1859
1860   pdbr = get_cr3 ();
1861   if (!pdbr)
1862     puts_filtered ("Access to Page Tables is not supported on this system.\n");
1863   else if (pde_idx >= 0)
1864     display_page_table (pde_idx, 1);
1865   else
1866     for (i = 0; i < 1024; i++)
1867       display_page_table (i, 0);
1868 }
1869
1870 static void
1871 go32_pte_for_address (char *arg, int from_tty)
1872 {
1873   CORE_ADDR addr = 0, i;
1874
1875   if (arg && *arg)
1876     {
1877       while (*arg && isspace(*arg))
1878         arg++;
1879
1880       if (*arg)
1881         addr = parse_and_eval_address (arg);
1882     }
1883   if (!addr)
1884     error_no_arg (_("linear address"));
1885
1886   pdbr = get_cr3 ();
1887   if (!pdbr)
1888     puts_filtered ("Access to Page Tables is not supported on this system.\n");
1889   else
1890     {
1891       int pde_idx = (addr >> 22) & 0x3ff;
1892       int pte_idx = (addr >> 12) & 0x3ff;
1893       unsigned offs = addr & 0xfff;
1894
1895       printf_filtered ("Page Table entry for address 0x%llx:\n",
1896                        (unsigned long long)addr);
1897       display_ptable_entry (get_pte (get_pde (pde_idx), pte_idx), 0, 1, offs);
1898     }
1899 }
1900
1901 static struct cmd_list_element *info_dos_cmdlist = NULL;
1902
1903 static void
1904 go32_info_dos_command (char *args, int from_tty)
1905 {
1906   help_list (info_dos_cmdlist, "info dos ", class_info, gdb_stdout);
1907 }
1908
1909 void
1910 _initialize_go32_nat (void)
1911 {
1912   init_go32_ops ();
1913   add_target (&go32_ops);
1914
1915   add_prefix_cmd ("dos", class_info, go32_info_dos_command, _("\
1916 Print information specific to DJGPP (aka MS-DOS) debugging."),
1917                   &info_dos_cmdlist, "info dos ", 0, &infolist);
1918
1919   add_cmd ("sysinfo", class_info, go32_sysinfo, _("\
1920 Display information about the target system, including CPU, OS, DPMI, etc."),
1921            &info_dos_cmdlist);
1922   add_cmd ("ldt", class_info, go32_sldt, _("\
1923 Display entries in the LDT (Local Descriptor Table).\n\
1924 Entry number (an expression) as an argument means display only that entry."),
1925            &info_dos_cmdlist);
1926   add_cmd ("gdt", class_info, go32_sgdt, _("\
1927 Display entries in the GDT (Global Descriptor Table).\n\
1928 Entry number (an expression) as an argument means display only that entry."),
1929            &info_dos_cmdlist);
1930   add_cmd ("idt", class_info, go32_sidt, _("\
1931 Display entries in the IDT (Interrupt Descriptor Table).\n\
1932 Entry number (an expression) as an argument means display only that entry."),
1933            &info_dos_cmdlist);
1934   add_cmd ("pde", class_info, go32_pde, _("\
1935 Display entries in the Page Directory.\n\
1936 Entry number (an expression) as an argument means display only that entry."),
1937            &info_dos_cmdlist);
1938   add_cmd ("pte", class_info, go32_pte, _("\
1939 Display entries in Page Tables.\n\
1940 Entry number (an expression) as an argument means display only entries\n\
1941 from the Page Table pointed to by the specified Page Directory entry."),
1942            &info_dos_cmdlist);
1943   add_cmd ("address-pte", class_info, go32_pte_for_address, _("\
1944 Display a Page Table entry for a linear address.\n\
1945 The address argument must be a linear address, after adding to\n\
1946 it the base address of the appropriate segment.\n\
1947 The base address of variables and functions in the debuggee's data\n\
1948 or code segment is stored in the variable __djgpp_base_address,\n\
1949 so use `__djgpp_base_address + (char *)&var' as the argument.\n\
1950 For other segments, look up their base address in the output of\n\
1951 the `info dos ldt' command."),
1952            &info_dos_cmdlist);
1953 }
1954
1955 pid_t
1956 tcgetpgrp (int fd)
1957 {
1958   if (isatty (fd))
1959     return SOME_PID;
1960   errno = ENOTTY;
1961   return -1;
1962 }
1963
1964 int
1965 tcsetpgrp (int fd, pid_t pgid)
1966 {
1967   if (isatty (fd) && pgid == SOME_PID)
1968     return 0;
1969   errno = pgid == SOME_PID ? ENOTTY : ENOSYS;
1970   return -1;
1971 }