gdb/go32-nat.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Native debugging support for Intel x86 running DJGPP.
  2.    Copyright (C) 1997-2015 Free Software Foundation, Inc.
  3.    Written by Robert Hoehne.

  4.    This file is part of GDB.

  5.    This program is free software; you can redistribute it and/or modify
  6.    it under the terms of the GNU General Public License as published by
  7.    the Free Software Foundation; either version 3 of the License, or
  8.    (at your option) any later version.

  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.

  13.    You should have received a copy of the GNU General Public License
  14.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  15. /* To whomever it may concern, here's a general description of how
  16.    debugging in DJGPP works, and the special quirks GDB does to
  17.    support that.

  18.    When the DJGPP port of GDB is debugging a DJGPP program natively,
  19.    there aren't 2 separate processes, the debuggee and GDB itself, as
  20.    on other systems.  (This is DOS, where there can only be one active
  21.    process at any given time, remember?)  Instead, GDB and the
  22.    debuggee live in the same process.  So when GDB calls
  23.    go32_create_inferior below, and that function calls edi_init from
  24.    the DJGPP debug support library libdbg.a, we load the debuggee's
  25.    executable file into GDB's address space, set it up for execution
  26.    as the stub loader (a short real-mode program prepended to each
  27.    DJGPP executable) normally would, and do a lot of preparations for
  28.    swapping between GDB's and debuggee's internal state, primarily wrt
  29.    the exception handlers.  This swapping happens every time we resume
  30.    the debuggee or switch back to GDB's code, and it includes:

  31.     . swapping all the segment registers
  32.     . swapping the PSP (the Program Segment Prefix)
  33.     . swapping the signal handlers
  34.     . swapping the exception handlers
  35.     . swapping the FPU status
  36.     . swapping the 3 standard file handles (more about this below)

  37.    Then running the debuggee simply means longjmp into it where its PC
  38.    is and let it run until it stops for some reason.  When it stops,
  39.    GDB catches the exception that stopped it and longjmp's back into
  40.    its own code.  All the possible exit points of the debuggee are
  41.    watched; for example, the normal exit point is recognized because a
  42.    DOS program issues a special system call to exit.  If one of those
  43.    exit points is hit, we mourn the inferior and clean up after it.
  44.    Cleaning up is very important, even if the process exits normally,
  45.    because otherwise we might leave behind traces of previous
  46.    execution, and in several cases GDB itself might be left hosed,
  47.    because all the exception handlers were not restored.

  48.    Swapping of the standard handles (in redir_to_child and
  49.    redir_to_debugger) is needed because, since both GDB and the
  50.    debuggee live in the same process, as far as the OS is concerned,
  51.    the share the same file table.  This means that the standard
  52.    handles 0, 1, and 2 point to the same file table entries, and thus
  53.    are connected to the same devices.  Therefore, if the debugger
  54.    redirects its standard output, the standard output of the debuggee
  55.    is also automagically redirected to the same file/device!
  56.    Similarly, if the debuggee redirects its stdout to a file, you
  57.    won't be able to see debugger's output (it will go to the same file
  58.    where the debuggee has its output); and if the debuggee closes its
  59.    standard input, you will lose the ability to talk to debugger!

  60.    For this reason, every time the debuggee is about to be resumed, we
  61.    call redir_to_child, which redirects the standard handles to where
  62.    the debuggee expects them to be.  When the debuggee stops and GDB
  63.    regains control, we call redir_to_debugger, which redirects those 3
  64.    handles back to where GDB expects.

  65.    Note that only the first 3 handles are swapped, so if the debuggee
  66.    redirects or closes any other handles, GDB will not notice.  In
  67.    particular, the exit code of a DJGPP program forcibly closes all
  68.    file handles beyond the first 3 ones, so when the debuggee exits,
  69.    GDB currently loses its stdaux and stdprn streams.  Fortunately,
  70.    GDB does not use those as of this writing, and will never need
  71.    to.  */

  72. #include "defs.h"

  73. #include <fcntl.h>

  74. #include "x86-nat.h"
  75. #include "inferior.h"
  76. #include "infrun.h"
  77. #include "gdbthread.h"
  78. #include "gdb_wait.h"
  79. #include "gdbcore.h"
  80. #include "command.h"
  81. #include "gdbcmd.h"
  82. #include "floatformat.h"
  83. #include "buildsym.h"
  84. #include "i387-tdep.h"
  85. #include "i386-tdep.h"
  86. #include "nat/x86-cpuid.h"
  87. #include "value.h"
  88. #include "regcache.h"
  89. #include "top.h"
  90. #include "cli/cli-utils.h"
  91. #include "inf-child.h"

  92. #include <ctype.h>
  93. #include <unistd.h>
  94. #include <sys/utsname.h>
  95. #include <io.h>
  96. #include <dos.h>
  97. #include <dpmi.h>
  98. #include <go32.h>
  99. #include <sys/farptr.h>
  100. #include <debug/v2load.h>
  101. #include <debug/dbgcom.h>
  102. #if __DJGPP_MINOR__ > 2
  103. #include <debug/redir.h>
  104. #endif

  105. #include <langinfo.h>

  106. #if __DJGPP_MINOR__ < 3
  107. /* This code will be provided from DJGPP 2.03 on.  Until then I code it
  108.    here.  */
  109. typedef struct
  110.   {
  111.     unsigned short sig0;
  112.     unsigned short sig1;
  113.     unsigned short sig2;
  114.     unsigned short sig3;
  115.     unsigned short exponent:15;
  116.     unsigned short sign:1;
  117.   }
  118. NPXREG;

  119. typedef struct
  120.   {
  121.     unsigned int control;
  122.     unsigned int status;
  123.     unsigned int tag;
  124.     unsigned int eip;
  125.     unsigned int cs;
  126.     unsigned int dataptr;
  127.     unsigned int datasel;
  128.     NPXREG reg[8];
  129.   }
  130. NPX;

  131. static NPX npx;

  132. static void save_npx (void);        /* Save the FPU of the debugged program.  */
  133. static void load_npx (void);        /* Restore the FPU of the debugged program.  */

  134. /* ------------------------------------------------------------------------- */
  135. /* Store the contents of the NPX in the global variable `npx'.  */
  136. /* *INDENT-OFF* */

  137. static void
  138. save_npx (void)
  139. {
  140.   asm ("inb    $0xa0, %%al  \n\
  141.        testb $0x20, %%al    \n\
  142.        jz 1f                         \n\
  143.        xorb %%al, %%al            \n\
  144.        outb %%al, $0xf0     \n\
  145.        movb $0x20, %%al            \n\
  146.        outb %%al, $0xa0     \n\
  147.        outb %%al, $0x20     \n\
  148. 1:                                           \n\
  149.        fnsave %0            \n\
  150.        fwait "
  151. :     "=m" (npx)
  152. :                                /* No input */
  153. :     "%eax");
  154. }

  155. /* *INDENT-ON* */


  156. /* ------------------------------------------------------------------------- */
  157. /* Reload the contents of the NPX from the global variable `npx'.  */

  158. static void
  159. load_npx (void)
  160. {
  161.   asm ("frstor %0":"=m" (npx));
  162. }
  163. /* ------------------------------------------------------------------------- */
  164. /* Stubs for the missing redirection functions.  */
  165. typedef struct {
  166.   char *command;
  167.   int redirected;
  168. } cmdline_t;

  169. void
  170. redir_cmdline_delete (cmdline_t *ptr)
  171. {
  172.   ptr->redirected = 0;
  173. }

  174. int
  175. redir_cmdline_parse (const char *args, cmdline_t *ptr)
  176. {
  177.   return -1;
  178. }

  179. int
  180. redir_to_child (cmdline_t *ptr)
  181. {
  182.   return 1;
  183. }

  184. int
  185. redir_to_debugger (cmdline_t *ptr)
  186. {
  187.   return 1;
  188. }

  189. int
  190. redir_debug_init (cmdline_t *ptr)
  191. {
  192.   return 0;
  193. }
  194. #endif /* __DJGPP_MINOR < 3 */

  195. typedef enum { wp_insert, wp_remove, wp_count } wp_op;

  196. /* This holds the current reference counts for each debug register.  */
  197. static int dr_ref_count[4];

  198. #define SOME_PID 42

  199. static int prog_has_started = 0;
  200. static void go32_mourn_inferior (struct target_ops *ops);

  201. #define r_ofs(x) (offsetof(TSS,x))

  202. static struct
  203. {
  204.   size_t tss_ofs;
  205.   size_t size;
  206. }
  207. regno_mapping[] =
  208. {
  209.   {r_ofs (tss_eax), 4},        /* normal registers, from a_tss */
  210.   {r_ofs (tss_ecx), 4},
  211.   {r_ofs (tss_edx), 4},
  212.   {r_ofs (tss_ebx), 4},
  213.   {r_ofs (tss_esp), 4},
  214.   {r_ofs (tss_ebp), 4},
  215.   {r_ofs (tss_esi), 4},
  216.   {r_ofs (tss_edi), 4},
  217.   {r_ofs (tss_eip), 4},
  218.   {r_ofs (tss_eflags), 4},
  219.   {r_ofs (tss_cs), 2},
  220.   {r_ofs (tss_ss), 2},
  221.   {r_ofs (tss_ds), 2},
  222.   {r_ofs (tss_es), 2},
  223.   {r_ofs (tss_fs), 2},
  224.   {r_ofs (tss_gs), 2},
  225.   {0, 10},                /* 8 FP registers, from npx.reg[] */
  226.   {1, 10},
  227.   {2, 10},
  228.   {3, 10},
  229.   {4, 10},
  230.   {5, 10},
  231.   {6, 10},
  232.   {7, 10},
  233.         /* The order of the next 7 registers must be consistent
  234.            with their numbering in config/i386/tm-i386.h, which see.  */
  235.   {0, 2},                /* control word, from npx */
  236.   {4, 2},                /* status word, from npx */
  237.   {8, 2},                /* tag word, from npx */
  238.   {16, 2},                /* last FP exception CS from npx */
  239.   {12, 4},                /* last FP exception EIP from npx */
  240.   {24, 2},                /* last FP exception operand selector from npx */
  241.   {20, 4},                /* last FP exception operand offset from npx */
  242.   {18, 2}                /* last FP opcode from npx */
  243. };

  244. static struct
  245.   {
  246.     int go32_sig;
  247.     enum gdb_signal gdb_sig;
  248.   }
  249. sig_map[] =
  250. {
  251.   {0, GDB_SIGNAL_FPE},
  252.   {1, GDB_SIGNAL_TRAP},
  253.   /* Exception 2 is triggered by the NMI.  DJGPP handles it as SIGILL,
  254.      but I think SIGBUS is better, since the NMI is usually activated
  255.      as a result of a memory parity check failure.  */
  256.   {2, GDB_SIGNAL_BUS},
  257.   {3, GDB_SIGNAL_TRAP},
  258.   {4, GDB_SIGNAL_FPE},
  259.   {5, GDB_SIGNAL_SEGV},
  260.   {6, GDB_SIGNAL_ILL},
  261.   {7, GDB_SIGNAL_EMT},        /* no-coprocessor exception */
  262.   {8, GDB_SIGNAL_SEGV},
  263.   {9, GDB_SIGNAL_SEGV},
  264.   {10, GDB_SIGNAL_BUS},
  265.   {11, GDB_SIGNAL_SEGV},
  266.   {12, GDB_SIGNAL_SEGV},
  267.   {13, GDB_SIGNAL_SEGV},
  268.   {14, GDB_SIGNAL_SEGV},
  269.   {16, GDB_SIGNAL_FPE},
  270.   {17, GDB_SIGNAL_BUS},
  271.   {31, GDB_SIGNAL_ILL},
  272.   {0x1b, GDB_SIGNAL_INT},
  273.   {0x75, GDB_SIGNAL_FPE},
  274.   {0x78, GDB_SIGNAL_ALRM},
  275.   {0x79, GDB_SIGNAL_INT},
  276.   {0x7a, GDB_SIGNAL_QUIT},
  277.   {-1, GDB_SIGNAL_LAST}
  278. };

  279. static struct {
  280.   enum gdb_signal gdb_sig;
  281.   int djgpp_excepno;
  282. } excepn_map[] = {
  283.   {GDB_SIGNAL_0, -1},
  284.   {GDB_SIGNAL_ILL, 6},        /* Invalid Opcode */
  285.   {GDB_SIGNAL_EMT, 7},        /* triggers SIGNOFP */
  286.   {GDB_SIGNAL_SEGV, 13},        /* GPF */
  287.   {GDB_SIGNAL_BUS, 17},        /* Alignment Check */
  288.   /* The rest are fake exceptions, see dpmiexcp.c in djlsr*.zip for
  289.      details.  */
  290.   {GDB_SIGNAL_TERM, 0x1b},        /* triggers Ctrl-Break type of SIGINT */
  291.   {GDB_SIGNAL_FPE, 0x75},
  292.   {GDB_SIGNAL_INT, 0x79},
  293.   {GDB_SIGNAL_QUIT, 0x7a},
  294.   {GDB_SIGNAL_ALRM, 0x78},        /* triggers SIGTIMR */
  295.   {GDB_SIGNAL_PROF, 0x78},
  296.   {GDB_SIGNAL_LAST, -1}
  297. };

  298. static void
  299. go32_attach (struct target_ops *ops, const char *args, int from_tty)
  300. {
  301.   error (_("\
  302. You cannot attach to a running program on this platform.\n\
  303. Use the `run' command to run DJGPP programs."));
  304. }

  305. static int resume_is_step;
  306. static int resume_signal = -1;

  307. static void
  308. go32_resume (struct target_ops *ops,
  309.              ptid_t ptid, int step, enum gdb_signal siggnal)
  310. {
  311.   int i;

  312.   resume_is_step = step;

  313.   if (siggnal != GDB_SIGNAL_0 && siggnal != GDB_SIGNAL_TRAP)
  314.   {
  315.     for (i = 0, resume_signal = -1;
  316.          excepn_map[i].gdb_sig != GDB_SIGNAL_LAST; i++)
  317.       if (excepn_map[i].gdb_sig == siggnal)
  318.       {
  319.         resume_signal = excepn_map[i].djgpp_excepno;
  320.         break;
  321.       }
  322.     if (resume_signal == -1)
  323.       printf_unfiltered ("Cannot deliver signal %s on this platform.\n",
  324.                          gdb_signal_to_name (siggnal));
  325.   }
  326. }

  327. static char child_cwd[FILENAME_MAX];

  328. static ptid_t
  329. go32_wait (struct target_ops *ops,
  330.            ptid_t ptid, struct target_waitstatus *status, int options)
  331. {
  332.   int i;
  333.   unsigned char saved_opcode;
  334.   unsigned long INT3_addr = 0;
  335.   int stepping_over_INT = 0;

  336.   a_tss.tss_eflags &= 0xfeff;        /* Reset the single-step flag (TF).  */
  337.   if (resume_is_step)
  338.     {
  339.       /* If the next instruction is INT xx or INTO, we need to handle
  340.          them specially.  Intel manuals say that these instructions
  341.          reset the single-step flag (a.k.a. TF).  However, it seems
  342.          that, at least in the DPMI environment, and at least when
  343.          stepping over the DPMI interrupt 31h, the problem is having
  344.          TF set at all when INT 31h is executed: the debuggee either
  345.          crashes (and takes the system with it) or is killed by a
  346.          SIGTRAP.

  347.          So we need to emulate single-step mode: we put an INT3 opcode
  348.          right after the INT xx instruction, let the debuggee run
  349.          until it hits INT3 and stops, then restore the original
  350.          instruction which we overwrote with the INT3 opcode, and back
  351.          up the debuggee's EIP to that instruction.  */
  352.       read_child (a_tss.tss_eip, &saved_opcode, 1);
  353.       if (saved_opcode == 0xCD || saved_opcode == 0xCE)
  354.         {
  355.           unsigned char INT3_opcode = 0xCC;

  356.           INT3_addr
  357.             = saved_opcode == 0xCD ? a_tss.tss_eip + 2 : a_tss.tss_eip + 1;
  358.           stepping_over_INT = 1;
  359.           read_child (INT3_addr, &saved_opcode, 1);
  360.           write_child (INT3_addr, &INT3_opcode, 1);
  361.         }
  362.       else
  363.         a_tss.tss_eflags |= 0x0100; /* normal instruction: set TF */
  364.     }

  365.   /* The special value FFFFh in tss_trap indicates to run_child that
  366.      tss_irqn holds a signal to be delivered to the debuggee.  */
  367.   if (resume_signal <= -1)
  368.     {
  369.       a_tss.tss_trap = 0;
  370.       a_tss.tss_irqn = 0xff;
  371.     }
  372.   else
  373.     {
  374.       a_tss.tss_trap = 0xffff;        /* run_child looks for this.  */
  375.       a_tss.tss_irqn = resume_signal;
  376.     }

  377.   /* The child might change working directory behind our back.  The
  378.      GDB users won't like the side effects of that when they work with
  379.      relative file names, and GDB might be confused by its current
  380.      directory not being in sync with the truth.  So we always make a
  381.      point of changing back to where GDB thinks is its cwd, when we
  382.      return control to the debugger, but restore child's cwd before we
  383.      run it.  */
  384.   /* Initialize child_cwd, before the first call to run_child and not
  385.      in the initialization, so the child get also the changed directory
  386.      set with the gdb-command "cd ..."  */
  387.   if (!*child_cwd)
  388.     /* Initialize child's cwd with the current one.  */
  389.     getcwd (child_cwd, sizeof (child_cwd));

  390.   chdir (child_cwd);

  391. #if __DJGPP_MINOR__ < 3
  392.   load_npx ();
  393. #endif
  394.   run_child ();
  395. #if __DJGPP_MINOR__ < 3
  396.   save_npx ();
  397. #endif

  398.   /* Did we step over an INT xx instruction?  */
  399.   if (stepping_over_INT && a_tss.tss_eip == INT3_addr + 1)
  400.     {
  401.       /* Restore the original opcode.  */
  402.       a_tss.tss_eip--;        /* EIP points *after* the INT3 instruction.  */
  403.       write_child (a_tss.tss_eip, &saved_opcode, 1);
  404.       /* Simulate a TRAP exception.  */
  405.       a_tss.tss_irqn = 1;
  406.       a_tss.tss_eflags |= 0x0100;
  407.     }

  408.   getcwd (child_cwd, sizeof (child_cwd)); /* in case it has changed */
  409.   chdir (current_directory);

  410.   if (a_tss.tss_irqn == 0x21)
  411.     {
  412.       status->kind = TARGET_WAITKIND_EXITED;
  413.       status->value.integer = a_tss.tss_eax & 0xff;
  414.     }
  415.   else
  416.     {
  417.       status->value.sig = GDB_SIGNAL_UNKNOWN;
  418.       status->kind = TARGET_WAITKIND_STOPPED;
  419.       for (i = 0; sig_map[i].go32_sig != -1; i++)
  420.         {
  421.           if (a_tss.tss_irqn == sig_map[i].go32_sig)
  422.             {
  423. #if __DJGPP_MINOR__ < 3
  424.               if ((status->value.sig = sig_map[i].gdb_sig) !=
  425.                   GDB_SIGNAL_TRAP)
  426.                 status->kind = TARGET_WAITKIND_SIGNALLED;
  427. #else
  428.               status->value.sig = sig_map[i].gdb_sig;
  429. #endif
  430.               break;
  431.             }
  432.         }
  433.     }
  434.   return pid_to_ptid (SOME_PID);
  435. }

  436. static void
  437. fetch_register (struct regcache *regcache, int regno)
  438. {
  439.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  440.   if (regno < gdbarch_fp0_regnum (gdbarch))
  441.     regcache_raw_supply (regcache, regno,
  442.                          (char *) &a_tss + regno_mapping[regno].tss_ofs);
  443.   else if (i386_fp_regnum_p (gdbarch, regno) || i386_fpc_regnum_p (gdbarch,
  444.                                                                    regno))
  445.     i387_supply_fsave (regcache, regno, &npx);
  446.   else
  447.     internal_error (__FILE__, __LINE__,
  448.                     _("Invalid register no. %d in fetch_register."), regno);
  449. }

  450. static void
  451. go32_fetch_registers (struct target_ops *ops,
  452.                       struct regcache *regcache, int regno)
  453. {
  454.   if (regno >= 0)
  455.     fetch_register (regcache, regno);
  456.   else
  457.     {
  458.       for (regno = 0;
  459.            regno < gdbarch_fp0_regnum (get_regcache_arch (regcache));
  460.            regno++)
  461.         fetch_register (regcache, regno);
  462.       i387_supply_fsave (regcache, -1, &npx);
  463.     }
  464. }

  465. static void
  466. store_register (const struct regcache *regcache, int regno)
  467. {
  468.   struct gdbarch *gdbarch = get_regcache_arch (regcache);
  469.   if (regno < gdbarch_fp0_regnum (gdbarch))
  470.     regcache_raw_collect (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,
  473.                                                                    regno))
  474.     i387_collect_fsave (regcache, regno, &npx);
  475.   else
  476.     internal_error (__FILE__, __LINE__,
  477.                     _("Invalid register no. %d in store_register."), regno);
  478. }

  479. static void
  480. go32_store_registers (struct target_ops *ops,
  481.                       struct regcache *regcache, int regno)
  482. {
  483.   unsigned r;

  484.   if (regno >= 0)
  485.     store_register (regcache, regno);
  486.   else
  487.     {
  488.       for (r = 0; r < gdbarch_fp0_regnum (get_regcache_arch (regcache)); r++)
  489.         store_register (regcache, r);
  490.       i387_collect_fsave (regcache, -1, &npx);
  491.     }
  492. }

  493. /* Const-correct version of DJGPP's write_child, which unfortunately
  494.    takes a non-const buffer pointer.  */

  495. static int
  496. my_write_child (unsigned child_addr, const void *buf, unsigned len)
  497. {
  498.   static void *buffer = NULL;
  499.   static unsigned buffer_len = 0;
  500.   int res;

  501.   if (buffer_len < len)
  502.     {
  503.       buffer = xrealloc (buffer, len);
  504.       buffer_len = len;
  505.     }

  506.   memcpy (buffer, buf, len);
  507.   res = write_child (child_addr, buffer, len);
  508.   return res;
  509. }

  510. /* Helper for go32_xfer_partial that handles memory transfers.
  511.    Arguments are like target_xfer_partial.  */

  512. static enum target_xfer_status
  513. go32_xfer_memory (gdb_byte *readbuf, const gdb_byte *writebuf,
  514.                   ULONGEST memaddr, ULONGEST len, ULONGEST *xfered_len)
  515. {
  516.   int res;

  517.   if (writebuf != NULL)
  518.     res = my_write_child (memaddr, writebuf, len);
  519.   else
  520.     res = read_child (memaddr, readbuf, len);

  521.   if (res <= 0)
  522.     return TARGET_XFER_E_IO;

  523.   *xfered_len = res;
  524.   return TARGET_XFER_OK;
  525. }

  526. /* Target to_xfer_partial implementation.  */

  527. static enum target_xfer_status
  528. go32_xfer_partial (struct target_ops *ops, enum target_object object,
  529.                    const char *annex, gdb_byte *readbuf,
  530.                    const gdb_byte *writebuf, ULONGEST offset, ULONGEST len,
  531.                    ULONGEST *xfered_len)
  532. {
  533.   switch (object)
  534.     {
  535.     case TARGET_OBJECT_MEMORY:
  536.       return go32_xfer_memory (readbuf, writebuf, offset, len, xfered_len);

  537.     default:
  538.       return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
  539.                                             readbuf, writebuf, offset, len,
  540.                                             xfered_len);
  541.     }
  542. }

  543. static cmdline_t child_cmd;        /* Parsed child's command line kept here.  */

  544. static void
  545. go32_files_info (struct target_ops *target)
  546. {
  547.   printf_unfiltered ("You are running a DJGPP V2 program.\n");
  548. }

  549. static void
  550. go32_kill_inferior (struct target_ops *ops)
  551. {
  552.   go32_mourn_inferior (ops);
  553. }

  554. static void
  555. go32_create_inferior (struct target_ops *ops, char *exec_file,
  556.                       char *args, char **env, int from_tty)
  557. {
  558.   extern char **environ;
  559.   jmp_buf start_state;
  560.   char *cmdline;
  561.   char **env_save = environ;
  562.   size_t cmdlen;
  563.   struct inferior *inf;
  564.   int result;

  565.   /* If no exec file handed to us, get it from the exec-file command -- with
  566.      a good, common error message if none is specified.  */
  567.   if (exec_file == 0)
  568.     exec_file = get_exec_file (1);

  569.   resume_signal = -1;
  570.   resume_is_step = 0;

  571.   /* Initialize child's cwd as empty to be initialized when starting
  572.      the child.  */
  573.   *child_cwd = 0;

  574.   /* Init command line storage.  */
  575.   if (redir_debug_init (&child_cmd) == -1)
  576.     internal_error (__FILE__, __LINE__,
  577.                     _("Cannot allocate redirection storage: "
  578.                       "not enough memory.\n"));

  579.   /* Parse the command line and create redirections.  */
  580.   if (strpbrk (args, "<>"))
  581.     {
  582.       if (redir_cmdline_parse (args, &child_cmd) == 0)
  583.         args = child_cmd.command;
  584.       else
  585.         error (_("Syntax error in command line."));
  586.     }
  587.   else
  588.     child_cmd.command = xstrdup (args);

  589.   cmdlen = strlen (args);
  590.   /* v2loadimage passes command lines via DOS memory, so it cannot
  591.      possibly handle commands longer than 1MB.  */
  592.   if (cmdlen > 1024*1024)
  593.     error (_("Command line too long."));

  594.   cmdline = xmalloc (cmdlen + 4);
  595.   strcpy (cmdline + 1, args);
  596.   /* If the command-line length fits into DOS 126-char limits, use the
  597.      DOS command tail format; otherwise, tell v2loadimage to pass it
  598.      through a buffer in conventional memory.  */
  599.   if (cmdlen < 127)
  600.     {
  601.       cmdline[0] = strlen (args);
  602.       cmdline[cmdlen + 1] = 13;
  603.     }
  604.   else
  605.     cmdline[0] = 0xff;        /* Signal v2loadimage it's a long command.  */

  606.   environ = env;

  607.   result = v2loadimage (exec_file, cmdline, start_state);

  608.   environ = env_save;
  609.   xfree (cmdline);

  610.   if (result != 0)
  611.     error (_("Load failed for image %s"), exec_file);

  612.   edi_init (start_state);
  613. #if __DJGPP_MINOR__ < 3
  614.   save_npx ();
  615. #endif

  616.   inferior_ptid = pid_to_ptid (SOME_PID);
  617.   inf = current_inferior ();
  618.   inferior_appeared (inf, SOME_PID);

  619.   if (!target_is_pushed (ops))
  620.     push_target (ops);

  621.   add_thread_silent (inferior_ptid);

  622.   clear_proceed_status (0);
  623.   insert_breakpoints ();
  624.   prog_has_started = 1;
  625. }

  626. static void
  627. go32_mourn_inferior (struct target_ops *ops)
  628. {
  629.   ptid_t ptid;

  630.   redir_cmdline_delete (&child_cmd);
  631.   resume_signal = -1;
  632.   resume_is_step = 0;

  633.   cleanup_client ();

  634.   /* We need to make sure all the breakpoint enable bits in the DR7
  635.      register are reset when the inferior exits.  Otherwise, if they
  636.      rerun the inferior, the uncleared bits may cause random SIGTRAPs,
  637.      failure to set more watchpoints, and other calamities.  It would
  638.      be nice if GDB itself would take care to remove all breakpoints
  639.      at all times, but it doesn't, probably under an assumption that
  640.      the OS cleans up when the debuggee exits.  */
  641.   x86_cleanup_dregs ();

  642.   ptid = inferior_ptid;
  643.   inferior_ptid = null_ptid;
  644.   delete_thread_silent (ptid);
  645.   prog_has_started = 0;

  646.   generic_mourn_inferior ();
  647.   inf_child_maybe_unpush_target (ops);
  648. }

  649. /* Hardware watchpoint support.  */

  650. #define D_REGS edi.dr
  651. #define CONTROL D_REGS[7]
  652. #define STATUS D_REGS[6]

  653. /* Pass the address ADDR to the inferior in the I'th debug register.
  654.    Here we just store the address in D_REGS, the watchpoint will be
  655.    actually set up when go32_wait runs the debuggee.  */
  656. static void
  657. go32_set_dr (int i, CORE_ADDR addr)
  658. {
  659.   if (i < 0 || i > 3)
  660.     internal_error (__FILE__, __LINE__,
  661.                     _("Invalid register %d in go32_set_dr.\n"), i);
  662.   D_REGS[i] = addr;
  663. }

  664. /* Pass the value VAL to the inferior in the DR7 debug control
  665.    register.  Here we just store the address in D_REGS, the watchpoint
  666.    will be actually set up when go32_wait runs the debuggee.  */
  667. static void
  668. go32_set_dr7 (unsigned long val)
  669. {
  670.   CONTROL = val;
  671. }

  672. /* Get the value of the DR6 debug status register from the inferior.
  673.    Here we just return the value stored in D_REGS, as we've got it
  674.    from the last go32_wait call.  */
  675. static unsigned long
  676. go32_get_dr6 (void)
  677. {
  678.   return STATUS;
  679. }

  680. /* Get the value of the DR7 debug status register from the inferior.
  681.    Here we just return the value stored in D_REGS, as we've got it
  682.    from the last go32_wait call.  */

  683. static unsigned long
  684. go32_get_dr7 (void)
  685. {
  686.   return CONTROL;
  687. }

  688. /* Get the value of the DR debug register I from the inferior.  Here
  689.    we just return the value stored in D_REGS, as we've got it from the
  690.    last go32_wait call.  */

  691. static CORE_ADDR
  692. go32_get_dr (int i)
  693. {
  694.   if (i < 0 || i > 3)
  695.     internal_error (__FILE__, __LINE__,
  696.                     _("Invalid register %d in go32_get_dr.\n"), i);
  697.   return D_REGS[i];
  698. }

  699. /* Put the device open on handle FD into either raw or cooked
  700.    mode, return 1 if it was in raw mode, zero otherwise.  */

  701. static int
  702. device_mode (int fd, int raw_p)
  703. {
  704.   int oldmode, newmode;
  705.   __dpmi_regs regs;

  706.   regs.x.ax = 0x4400;
  707.   regs.x.bx = fd;
  708.   __dpmi_int (0x21, &regs);
  709.   if (regs.x.flags & 1)
  710.     return -1;
  711.   newmode = oldmode = regs.x.dx;

  712.   if (raw_p)
  713.     newmode |= 0x20;
  714.   else
  715.     newmode &= ~0x20;

  716.   if (oldmode & 0x80)        /* Only for character dev.  */
  717.   {
  718.     regs.x.ax = 0x4401;
  719.     regs.x.bx = fd;
  720.     regs.x.dx = newmode & 0xff;   /* Force upper byte zero, else it fails.  */
  721.     __dpmi_int (0x21, &regs);
  722.     if (regs.x.flags & 1)
  723.       return -1;
  724.   }
  725.   return (oldmode & 0x20) == 0x20;
  726. }


  727. static int inf_mode_valid = 0;
  728. static int inf_terminal_mode;

  729. /* This semaphore is needed because, amazingly enough, GDB calls
  730.    target.to_terminal_ours more than once after the inferior stops.
  731.    But we need the information from the first call only, since the
  732.    second call will always see GDB's own cooked terminal.  */
  733. static int terminal_is_ours = 1;

  734. static void
  735. go32_terminal_init (struct target_ops *self)
  736. {
  737.   inf_mode_valid = 0;        /* Reinitialize, in case they are restarting child.  */
  738.   terminal_is_ours = 1;
  739. }

  740. static void
  741. go32_terminal_info (struct target_ops *self, const char *args, int from_tty)
  742. {
  743.   printf_unfiltered ("Inferior's terminal is in %s mode.\n",
  744.                      !inf_mode_valid
  745.                      ? "default" : inf_terminal_mode ? "raw" : "cooked");

  746. #if __DJGPP_MINOR__ > 2
  747.   if (child_cmd.redirection)
  748.   {
  749.     int i;

  750.     for (i = 0; i < DBG_HANDLES; i++)
  751.     {
  752.       if (child_cmd.redirection[i]->file_name)
  753.         printf_unfiltered ("\tFile handle %d is redirected to `%s'.\n",
  754.                            i, child_cmd.redirection[i]->file_name);
  755.       else if (_get_dev_info (child_cmd.redirection[i]->inf_handle) == -1)
  756.         printf_unfiltered
  757.           ("\tFile handle %d appears to be closed by inferior.\n", i);
  758.       /* Mask off the raw/cooked bit when comparing device info words.  */
  759.       else if ((_get_dev_info (child_cmd.redirection[i]->inf_handle) & 0xdf)
  760.                != (_get_dev_info (i) & 0xdf))
  761.         printf_unfiltered
  762.           ("\tFile handle %d appears to be redirected by inferior.\n", i);
  763.     }
  764.   }
  765. #endif
  766. }

  767. static void
  768. go32_terminal_inferior (struct target_ops *self)
  769. {
  770.   /* Redirect standard handles as child wants them.  */
  771.   errno = 0;
  772.   if (redir_to_child (&child_cmd) == -1)
  773.   {
  774.     redir_to_debugger (&child_cmd);
  775.     error (_("Cannot redirect standard handles for program: %s."),
  776.            safe_strerror (errno));
  777.   }
  778.   /* Set the console device of the inferior to whatever mode
  779.      (raw or cooked) we found it last time.  */
  780.   if (terminal_is_ours)
  781.   {
  782.     if (inf_mode_valid)
  783.       device_mode (0, inf_terminal_mode);
  784.     terminal_is_ours = 0;
  785.   }
  786. }

  787. static void
  788. go32_terminal_ours (struct target_ops *self)
  789. {
  790.   /* Switch to cooked mode on the gdb terminal and save the inferior
  791.      terminal mode to be restored when it is resumed.  */
  792.   if (!terminal_is_ours)
  793.   {
  794.     inf_terminal_mode = device_mode (0, 0);
  795.     if (inf_terminal_mode != -1)
  796.       inf_mode_valid = 1;
  797.     else
  798.       /* If device_mode returned -1, we don't know what happens with
  799.          handle 0 anymore, so make the info invalid.  */
  800.       inf_mode_valid = 0;
  801.     terminal_is_ours = 1;

  802.     /* Restore debugger's standard handles.  */
  803.     errno = 0;
  804.     if (redir_to_debugger (&child_cmd) == -1)
  805.     {
  806.       redir_to_child (&child_cmd);
  807.       error (_("Cannot redirect standard handles for debugger: %s."),
  808.              safe_strerror (errno));
  809.     }
  810.   }
  811. }

  812. static int
  813. go32_thread_alive (struct target_ops *ops, ptid_t ptid)
  814. {
  815.   return !ptid_equal (inferior_ptid, null_ptid);
  816. }

  817. static char *
  818. go32_pid_to_str (struct target_ops *ops, ptid_t ptid)
  819. {
  820.   return normal_pid_to_str (ptid);
  821. }

  822. /* Create a go32 target.  */

  823. static struct target_ops *
  824. go32_target (void)
  825. {
  826.   struct target_ops *t = inf_child_target ();

  827.   t->to_attach = go32_attach;
  828.   t->to_resume = go32_resume;
  829.   t->to_wait = go32_wait;
  830.   t->to_fetch_registers = go32_fetch_registers;
  831.   t->to_store_registers = go32_store_registers;
  832.   t->to_xfer_partial = go32_xfer_partial;
  833.   t->to_files_info = go32_files_info;
  834.   t->to_terminal_init = go32_terminal_init;
  835.   t->to_terminal_inferior = go32_terminal_inferior;
  836.   t->to_terminal_ours_for_output = go32_terminal_ours;
  837.   t->to_terminal_ours = go32_terminal_ours;
  838.   t->to_terminal_info = go32_terminal_info;
  839.   t->to_kill = go32_kill_inferior;
  840.   t->to_create_inferior = go32_create_inferior;
  841.   t->to_mourn_inferior = go32_mourn_inferior;
  842.   t->to_thread_alive = go32_thread_alive;
  843.   t->to_pid_to_str = go32_pid_to_str;

  844.   return t;
  845. }

  846. /* Return the current DOS codepage number.  */
  847. static int
  848. dos_codepage (void)
  849. {
  850.   __dpmi_regs regs;

  851.   regs.x.ax = 0x6601;
  852.   __dpmi_int (0x21, &regs);
  853.   if (!(regs.x.flags & 1))
  854.     return regs.x.bx & 0xffff;
  855.   else
  856.     return 437;        /* default */
  857. }

  858. /* Limited emulation of `nl_langinfo', for charset.c.  */
  859. char *
  860. nl_langinfo (nl_item item)
  861. {
  862.   char *retval;

  863.   switch (item)
  864.     {
  865.       case CODESET:
  866.         {
  867.           /* 8 is enough for SHORT_MAX + "CP" + null.  */
  868.           char buf[8];
  869.           int blen = sizeof (buf);
  870.           int needed = snprintf (buf, blen, "CP%d", dos_codepage ());

  871.           if (needed > blen)        /* Should never happen.  */
  872.             buf[0] = 0;
  873.           retval = xstrdup (buf);
  874.         }
  875.         break;
  876.       default:
  877.         retval = xstrdup ("");
  878.         break;
  879.     }
  880.   return retval;
  881. }

  882. unsigned short windows_major, windows_minor;

  883. /* Compute the version Windows reports via Int 2Fh/AX=1600h.  */
  884. static void
  885. go32_get_windows_version(void)
  886. {
  887.   __dpmi_regs r;

  888.   r.x.ax = 0x1600;
  889.   __dpmi_int(0x2f, &r);
  890.   if (r.h.al > 2 && r.h.al != 0x80 && r.h.al != 0xff
  891.       && (r.h.al > 3 || r.h.ah > 0))
  892.     {
  893.       windows_major = r.h.al;
  894.       windows_minor = r.h.ah;
  895.     }
  896.   else
  897.     windows_major = 0xff;        /* meaning no Windows */
  898. }

  899. /* A subroutine of go32_sysinfo to display memory info.  */
  900. static void
  901. print_mem (unsigned long datum, const char *header, int in_pages_p)
  902. {
  903.   if (datum != 0xffffffffUL)
  904.     {
  905.       if (in_pages_p)
  906.         datum <<= 12;
  907.       puts_filtered (header);
  908.       if (datum > 1024)
  909.         {
  910.           printf_filtered ("%lu KB", datum >> 10);
  911.           if (datum > 1024 * 1024)
  912.             printf_filtered (" (%lu MB)", datum >> 20);
  913.         }
  914.       else
  915.         printf_filtered ("%lu Bytes", datum);
  916.       puts_filtered ("\n");
  917.     }
  918. }

  919. /* Display assorted information about the underlying OS.  */
  920. static void
  921. go32_sysinfo (char *arg, int from_tty)
  922. {
  923.   static const char test_pattern[] =
  924.     "deadbeafdeadbeafdeadbeafdeadbeafdeadbeaf"
  925.     "deadbeafdeadbeafdeadbeafdeadbeafdeadbeaf"
  926.     "deadbeafdeadbeafdeadbeafdeadbeafdeadbeafdeadbeaf";
  927.   struct utsname u;
  928.   char cpuid_vendor[13];
  929.   unsigned cpuid_max = 0, cpuid_eax, cpuid_ebx, cpuid_ecx, cpuid_edx;
  930.   unsigned true_dos_version = _get_dos_version (1);
  931.   unsigned advertized_dos_version = ((unsigned int)_osmajor << 8) | _osminor;
  932.   int dpmi_flags;
  933.   char dpmi_vendor_info[129];
  934.   int dpmi_vendor_available;
  935.   __dpmi_version_ret dpmi_version_data;
  936.   long eflags;
  937.   __dpmi_free_mem_info mem_info;
  938.   __dpmi_regs regs;

  939.   cpuid_vendor[0] = '\0';
  940.   if (uname (&u))
  941.     strcpy (u.machine, "Unknown x86");
  942.   else if (u.machine[0] == 'i' && u.machine[1] > 4)
  943.     {
  944.       /* CPUID with EAX = 0 returns the Vendor ID.  */
  945. #if 0
  946.       /* Ideally we would use x86_cpuid(), but it needs someone to run
  947.          native tests first to make sure things actually work.  They should.
  948.          http://sourceware.org/ml/gdb-patches/2013-05/msg00164.html  */
  949.       unsigned int eax, ebx, ecx, edx;

  950.       if (x86_cpuid (0, &eax, &ebx, &ecx, &edx))
  951.         {
  952.           cpuid_max = eax;
  953.           memcpy (&vendor[0], &ebx, 4);
  954.           memcpy (&vendor[4], &ecx, 4);
  955.           memcpy (&vendor[8], &edx, 4);
  956.           cpuid_vendor[12] = '\0';
  957.         }
  958. #else
  959.       __asm__ __volatile__ ("xorl   %%ebx, %%ebx;"
  960.                             "xorl   %%ecx, %%ecx;"
  961.                             "xorl   %%edx, %%edx;"
  962.                             "movl   $0,    %%eax;"
  963.                             "cpuid;"
  964.                             "movl   %%ebx,  %0;"
  965.                             "movl   %%edx,  %1;"
  966.                             "movl   %%ecx,  %2;"
  967.                             "movl   %%eax,  %3;"
  968.                             : "=m" (cpuid_vendor[0]),
  969.                               "=m" (cpuid_vendor[4]),
  970.                               "=m" (cpuid_vendor[8]),
  971.                               "=m" (cpuid_max)
  972.                             :
  973.                             : "%eax", "%ebx", "%ecx", "%edx");
  974.       cpuid_vendor[12] = '\0';
  975. #endif
  976.     }

  977.   printf_filtered ("CPU Type.......................%s", u.machine);
  978.   if (cpuid_vendor[0])
  979.     printf_filtered (" (%s)", cpuid_vendor);
  980.   puts_filtered ("\n");

  981.   /* CPUID with EAX = 1 returns processor signature and features.  */
  982.   if (cpuid_max >= 1)
  983.     {
  984.       static char *brand_name[] = {
  985.         "",
  986.         " Celeron",
  987.         " III",
  988.         " III Xeon",
  989.         "", "", "", "",
  990.         " 4"
  991.       };
  992.       char cpu_string[80];
  993.       char cpu_brand[20];
  994.       unsigned brand_idx;
  995.       int intel_p = strcmp (cpuid_vendor, "GenuineIntel") == 0;
  996.       int amd_p = strcmp (cpuid_vendor, "AuthenticAMD") == 0;
  997.       unsigned cpu_family, cpu_model;

  998. #if 0
  999.       /* See comment above about cpuid usage.  */
  1000.       x86_cpuid (1, &cpuid_eax, &cpuid_ebx, NULL, &cpuid_edx);
  1001. #else
  1002.       __asm__ __volatile__ ("movl   $1, %%eax;"
  1003.                             "cpuid;"
  1004.                             : "=a" (cpuid_eax),
  1005.                               "=b" (cpuid_ebx),
  1006.                               "=d" (cpuid_edx)
  1007.                             :
  1008.                             : "%ecx");
  1009. #endif
  1010.       brand_idx = cpuid_ebx & 0xff;
  1011.       cpu_family = (cpuid_eax >> 8) & 0xf;
  1012.       cpu_model  = (cpuid_eax >> 4) & 0xf;
  1013.       cpu_brand[0] = '\0';
  1014.       if (intel_p)
  1015.         {
  1016.           if (brand_idx > 0
  1017.               && brand_idx < sizeof(brand_name)/sizeof(brand_name[0])
  1018.               && *brand_name[brand_idx])
  1019.             strcpy (cpu_brand, brand_name[brand_idx]);
  1020.           else if (cpu_family == 5)
  1021.             {
  1022.               if (((cpuid_eax >> 12) & 3) == 0 && cpu_model == 4)
  1023.                 strcpy (cpu_brand, " MMX");
  1024.               else if (cpu_model > 1 && ((cpuid_eax >> 12) & 3) == 1)
  1025.                 strcpy (cpu_brand, " OverDrive");
  1026.               else if (cpu_model > 1 && ((cpuid_eax >> 12) & 3) == 2)
  1027.                 strcpy (cpu_brand, " Dual");
  1028.             }
  1029.           else if (cpu_family == 6 && cpu_model < 8)
  1030.             {
  1031.               switch (cpu_model)
  1032.                 {
  1033.                   case 1:
  1034.                     strcpy (cpu_brand, " Pro");
  1035.                     break;
  1036.                   case 3:
  1037.                     strcpy (cpu_brand, " II");
  1038.                     break;
  1039.                   case 5:
  1040.                     strcpy (cpu_brand, " II Xeon");
  1041.                     break;
  1042.                   case 6:
  1043.                     strcpy (cpu_brand, " Celeron");
  1044.                     break;
  1045.                   case 7:
  1046.                     strcpy (cpu_brand, " III");
  1047.                     break;
  1048.                 }
  1049.             }
  1050.         }
  1051.       else if (amd_p)
  1052.         {
  1053.           switch (cpu_family)
  1054.             {
  1055.               case 4:
  1056.                 strcpy (cpu_brand, "486/5x86");
  1057.                 break;
  1058.               case 5:
  1059.                 switch (cpu_model)
  1060.                   {
  1061.                     case 0:
  1062.                     case 1:
  1063.                     case 2:
  1064.                     case 3:
  1065.                       strcpy (cpu_brand, "-K5");
  1066.                       break;
  1067.                     case 6:
  1068.                     case 7:
  1069.                       strcpy (cpu_brand, "-K6");
  1070.                       break;
  1071.                     case 8:
  1072.                       strcpy (cpu_brand, "-K6-2");
  1073.                       break;
  1074.                     case 9:
  1075.                       strcpy (cpu_brand, "-K6-III");
  1076.                       break;
  1077.                   }
  1078.                 break;
  1079.               case 6:
  1080.                 switch (cpu_model)
  1081.                   {
  1082.                     case 1:
  1083.                     case 2:
  1084.                     case 4:
  1085.                       strcpy (cpu_brand, " Athlon");
  1086.                       break;
  1087.                     case 3:
  1088.                       strcpy (cpu_brand, " Duron");
  1089.                       break;
  1090.                   }
  1091.                 break;
  1092.             }
  1093.         }
  1094.       xsnprintf (cpu_string, sizeof (cpu_string), "%s%s Model %d Stepping %d",
  1095.                  intel_p ? "Pentium" : (amd_p ? "AMD" : "ix86"),
  1096.                  cpu_brand, cpu_model, cpuid_eax & 0xf);
  1097.       printfi_filtered (31, "%s\n", cpu_string);
  1098.       if (((cpuid_edx & (6 | (0x0d << 23))) != 0)
  1099.           || ((cpuid_edx & 1) == 0)
  1100.           || (amd_p && (cpuid_edx & (3 << 30)) != 0))
  1101.         {
  1102.           puts_filtered ("CPU Features...................");
  1103.           /* We only list features which might be useful in the DPMI
  1104.              environment.  */
  1105.           if ((cpuid_edx & 1) == 0)
  1106.             puts_filtered ("No FPU "); /* It's unusual to not have an FPU.  */
  1107.           if ((cpuid_edx & (1 << 1)) != 0)
  1108.             puts_filtered ("VME ");
  1109.           if ((cpuid_edx & (1 << 2)) != 0)
  1110.             puts_filtered ("DE ");
  1111.           if ((cpuid_edx & (1 << 4)) != 0)
  1112.             puts_filtered ("TSC ");
  1113.           if ((cpuid_edx & (1 << 23)) != 0)
  1114.             puts_filtered ("MMX ");
  1115.           if ((cpuid_edx & (1 << 25)) != 0)
  1116.             puts_filtered ("SSE ");
  1117.           if ((cpuid_edx & (1 << 26)) != 0)
  1118.             puts_filtered ("SSE2 ");
  1119.           if (amd_p)
  1120.             {
  1121.               if ((cpuid_edx & (1 << 31)) != 0)
  1122.                 puts_filtered ("3DNow! ");
  1123.               if ((cpuid_edx & (1 << 30)) != 0)
  1124.                 puts_filtered ("3DNow!Ext");
  1125.             }
  1126.           puts_filtered ("\n");
  1127.         }
  1128.     }
  1129.   puts_filtered ("\n");
  1130.   printf_filtered ("DOS Version....................%s %s.%s",
  1131.                    _os_flavor, u.release, u.version);
  1132.   if (true_dos_version != advertized_dos_version)
  1133.     printf_filtered (" (disguised as v%d.%d)", _osmajor, _osminor);
  1134.   puts_filtered ("\n");
  1135.   if (!windows_major)
  1136.     go32_get_windows_version ();
  1137.   if (windows_major != 0xff)
  1138.     {
  1139.       const char *windows_flavor;

  1140.       printf_filtered ("Windows Version................%d.%02d (Windows ",
  1141.                        windows_major, windows_minor);
  1142.       switch (windows_major)
  1143.         {
  1144.           case 3:
  1145.             windows_flavor = "3.X";
  1146.             break;
  1147.           case 4:
  1148.             switch (windows_minor)
  1149.               {
  1150.                 case 0:
  1151.                   windows_flavor = "95, 95A, or 95B";
  1152.                   break;
  1153.                 case 3:
  1154.                   windows_flavor = "95B OSR2.1 or 95C OSR2.5";
  1155.                   break;
  1156.                 case 10:
  1157.                   windows_flavor = "98 or 98 SE";
  1158.                   break;
  1159.                 case 90:
  1160.                   windows_flavor = "ME";
  1161.                   break;
  1162.                 default:
  1163.                   windows_flavor = "9X";
  1164.                   break;
  1165.               }
  1166.             break;
  1167.           default:
  1168.             windows_flavor = "??";
  1169.             break;
  1170.         }
  1171.       printf_filtered ("%s)\n", windows_flavor);
  1172.     }
  1173.   else if (true_dos_version == 0x532 && advertized_dos_version == 0x500)
  1174.     printf_filtered ("Windows Version................"
  1175.                      "Windows NT family (W2K/XP/W2K3/Vista/W2K8)\n");
  1176.   puts_filtered ("\n");
  1177.   /* On some versions of Windows, __dpmi_get_capabilities returns
  1178.      zero, but the buffer is not filled with info, so we fill the
  1179.      buffer with a known pattern and test for it afterwards.  */
  1180.   memcpy (dpmi_vendor_info, test_pattern, sizeof(dpmi_vendor_info));
  1181.   dpmi_vendor_available =
  1182.     __dpmi_get_capabilities (&dpmi_flags, dpmi_vendor_info);
  1183.   if (dpmi_vendor_available == 0
  1184.       && memcmp (dpmi_vendor_info, test_pattern,
  1185.                  sizeof(dpmi_vendor_info)) != 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......................"
  1192.                        "%s v%d.%d (capabilities: %#x)\n",
  1193.                        &dpmi_vendor_info[2],
  1194.                        (unsigned)dpmi_vendor_info[0],
  1195.                        (unsigned)dpmi_vendor_info[1],
  1196.                        ((unsigned)dpmi_flags & 0x7f));
  1197.     }
  1198.   else
  1199.     printf_filtered ("DPMI Host......................(Info not available)\n");
  1200.   __dpmi_get_version (&dpmi_version_data);
  1201.   printf_filtered ("DPMI Version...................%d.%02d\n",
  1202.                    dpmi_version_data.major, dpmi_version_data.minor);
  1203.   printf_filtered ("DPMI Info......................"
  1204.                    "%s-bit DPMI, with%s Virtual Memory support\n",
  1205.                    (dpmi_version_data.flags & 1) ? "32" : "16",
  1206.                    (dpmi_version_data.flags & 4) ? "" : "out");
  1207.   printfi_filtered (31, "Interrupts reflected to %s mode\n",
  1208.                    (dpmi_version_data.flags & 2) ? "V86" : "Real");
  1209.   printfi_filtered (31, "Processor type: i%d86\n",
  1210.                    dpmi_version_data.cpu);
  1211.   printfi_filtered (31, "PIC base interrupt: Master: %#x  Slave: %#x\n",
  1212.                    dpmi_version_data.master_pic, dpmi_version_data.slave_pic);

  1213.   /* a_tss is only initialized when the debuggee is first run.  */
  1214.   if (prog_has_started)
  1215.     {
  1216.       __asm__ __volatile__ ("pushfl ; popl %0" : "=g" (eflags));
  1217.       printf_filtered ("Protection....................."
  1218.                        "Ring %d (in %s), with%s I/O protection\n",
  1219.                        a_tss.tss_cs & 3, (a_tss.tss_cs & 4) ? "LDT" : "GDT",
  1220.                        (a_tss.tss_cs & 3) > ((eflags >> 12) & 3) ? "" : "out");
  1221.     }
  1222.   puts_filtered ("\n");
  1223.   __dpmi_get_free_memory_information (&mem_info);
  1224.   print_mem (mem_info.total_number_of_physical_pages,
  1225.              "DPMI Total Physical Memory.....", 1);
  1226.   print_mem (mem_info.total_number_of_free_pages,
  1227.              "DPMI Free Physical Memory......", 1);
  1228.   print_mem (mem_info.size_of_paging_file_partition_in_pages,
  1229.              "DPMI Swap Space................", 1);
  1230.   print_mem (mem_info.linear_address_space_size_in_pages,
  1231.              "DPMI Total Linear Address Size.", 1);
  1232.   print_mem (mem_info.free_linear_address_space_in_pages,
  1233.              "DPMI Free Linear Address Size..", 1);
  1234.   print_mem (mem_info.largest_available_free_block_in_bytes,
  1235.              "DPMI Largest Free Memory Block.", 0);

  1236.   regs.h.ah = 0x48;
  1237.   regs.x.bx = 0xffff;
  1238.   __dpmi_int (0x21, &regs);
  1239.   print_mem (regs.x.bx << 4, "Free DOS Memory................", 0);
  1240.   regs.x.ax = 0x5800;
  1241.   __dpmi_int (0x21, &regs);
  1242.   if ((regs.x.flags & 1) == 0)
  1243.     {
  1244.       static const char *dos_hilo[] = {
  1245.         "Low", "", "", "", "High", "", "", "", "High, then Low"
  1246.       };
  1247.       static const char *dos_fit[] = {
  1248.         "First", "Best", "Last"
  1249.       };
  1250.       int hilo_idx = (regs.x.ax >> 4) & 0x0f;
  1251.       int fit_idx  = regs.x.ax & 0x0f;

  1252.       if (hilo_idx > 8)
  1253.         hilo_idx = 0;
  1254.       if (fit_idx > 2)
  1255.         fit_idx = 0;
  1256.       printf_filtered ("DOS Memory Allocation..........%s memory, %s fit\n",
  1257.                        dos_hilo[hilo_idx], dos_fit[fit_idx]);
  1258.       regs.x.ax = 0x5802;
  1259.       __dpmi_int (0x21, &regs);
  1260.       if ((regs.x.flags & 1) != 0)
  1261.         regs.h.al = 0;
  1262.       printfi_filtered (31, "UMBs %sin DOS memory chain\n",
  1263.                         regs.h.al == 0 ? "not " : "");
  1264.     }
  1265. }

  1266. struct seg_descr {
  1267.   unsigned short limit0;
  1268.   unsigned short base0;
  1269.   unsigned char  base1;
  1270.   unsigned       stype:5;
  1271.   unsigned       dpl:2;
  1272.   unsigned       present:1;
  1273.   unsigned       limit1:4;
  1274.   unsigned       available:1;
  1275.   unsigned       dummy:1;
  1276.   unsigned       bit32:1;
  1277.   unsigned       page_granular:1;
  1278.   unsigned char  base2;
  1279. } __attribute__ ((packed));

  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. /* Read LEN bytes starting at logical address ADDR, and put the result
  1291.    into DEST.  Return 1 if success, zero if not.  */
  1292. static int
  1293. read_memory_region (unsigned long addr, void *dest, size_t len)
  1294. {
  1295.   unsigned long dos_ds_limit = __dpmi_get_segment_limit (_dos_ds);
  1296.   int retval = 1;

  1297.   /* For the low memory, we can simply use _dos_ds.  */
  1298.   if (addr <= dos_ds_limit - len)
  1299.     dosmemget (addr, len, dest);
  1300.   else
  1301.     {
  1302.       /* For memory above 1MB we need to set up a special segment to
  1303.          be able to access that memory.  */
  1304.       int sel = __dpmi_allocate_ldt_descriptors (1);

  1305.       if (sel <= 0)
  1306.         retval = 0;
  1307.       else
  1308.         {
  1309.           int access_rights = __dpmi_get_descriptor_access_rights (sel);
  1310.           size_t segment_limit = len - 1;

  1311.           /* Make sure the crucial bits in the descriptor access
  1312.              rights are set correctly.  Some DPMI providers might barf
  1313.              if we set the segment limit to something that is not an
  1314.              integral multiple of 4KB pages if the granularity bit is
  1315.              not set to byte-granular, even though the DPMI spec says
  1316.              it's the host's responsibility to set that bit correctly.  */
  1317.           if (len > 1024 * 1024)
  1318.             {
  1319.               access_rights |= 0x8000;
  1320.               /* Page-granular segments should have the low 12 bits of
  1321.                  the limit set.  */
  1322.               segment_limit |= 0xfff;
  1323.             }
  1324.           else
  1325.             access_rights &= ~0x8000;

  1326.           if (__dpmi_set_segment_base_address (sel, addr) != -1
  1327.               && __dpmi_set_descriptor_access_rights (sel, access_rights) != -1
  1328.               && __dpmi_set_segment_limit (sel, segment_limit) != -1
  1329.               /* W2K silently fails to set the segment limit, leaving
  1330.                  it at zero; this test avoids the resulting crash.  */
  1331.               && __dpmi_get_segment_limit (sel) >= segment_limit)
  1332.             movedata (sel, 0, _my_ds (), (unsigned)dest, len);
  1333.           else
  1334.             retval = 0;

  1335.           __dpmi_free_ldt_descriptor (sel);
  1336.         }
  1337.     }
  1338.   return retval;
  1339. }

  1340. /* Get a segment descriptor stored at index IDX in the descriptor
  1341.    table whose base address is TABLE_BASE.  Return the descriptor
  1342.    type, or -1 if failure.  */
  1343. static int
  1344. get_descriptor (unsigned long table_base, int idx, void *descr)
  1345. {
  1346.   unsigned long addr = table_base + idx * 8; /* 8 bytes per entry */

  1347.   if (read_memory_region (addr, descr, 8))
  1348.     return (int)((struct seg_descr *)descr)->stype;
  1349.   return -1;
  1350. }

  1351. struct dtr_reg {
  1352.   unsigned short limit __attribute__((packed));
  1353.   unsigned long  base  __attribute__((packed));
  1354. };

  1355. /* Display a segment descriptor stored at index IDX in a descriptor
  1356.    table whose type is TYPE and whose base address is BASE_ADDR.  If
  1357.    FORCE is non-zero, display even invalid descriptors.  */
  1358. static void
  1359. display_descriptor (unsigned type, unsigned long base_addr, int idx, int force)
  1360. {
  1361.   struct seg_descr descr;
  1362.   struct gate_descr gate;

  1363.   /* Get the descriptor from the table.  */
  1364.   if (idx == 0 && type == 0)
  1365.     puts_filtered ("0x000: null descriptor\n");
  1366.   else if (get_descriptor (base_addr, idx, &descr) != -1)
  1367.     {
  1368.       /* For each type of descriptor table, this has a bit set if the
  1369.          corresponding type of selectors is valid in that table.  */
  1370.       static unsigned allowed_descriptors[] = {
  1371.           0xffffdafeL,   /* GDT */
  1372.           0x0000c0e0L,   /* IDT */
  1373.           0xffffdafaL    /* LDT */
  1374.       };

  1375.       /* If the program hasn't started yet, assume the debuggee will
  1376.          have the same CPL as the debugger.  */
  1377.       int cpl = prog_has_started ? (a_tss.tss_cs & 3) : _my_cs () & 3;
  1378.       unsigned long limit = (descr.limit1 << 16) | descr.limit0;

  1379.       if (descr.present
  1380.           && (allowed_descriptors[type] & (1 << descr.stype)) != 0)
  1381.         {
  1382.           printf_filtered ("0x%03x: ",
  1383.                            type == 1
  1384.                            ? idx : (idx * 8) | (type ? (cpl | 4) : 0));
  1385.           if (descr.page_granular)
  1386.             limit = (limit << 12) | 0xfff; /* big segment: low 12 bit set */
  1387.           if (descr.stype == 1 || descr.stype == 2 || descr.stype == 3
  1388.               || descr.stype == 9 || descr.stype == 11
  1389.               || (descr.stype >= 16 && descr.stype < 32))
  1390.             printf_filtered ("base=0x%02x%02x%04x limit=0x%08lx",
  1391.                              descr.base2, descr.base1, descr.base0, limit);

  1392.           switch (descr.stype)
  1393.             {
  1394.               case 1:
  1395.               case 3:
  1396.                 printf_filtered (" 16-bit TSS  (task %sactive)",
  1397.                                  descr.stype == 3 ? "" : "in");
  1398.                 break;
  1399.               case 2:
  1400.                 puts_filtered (" LDT");
  1401.                 break;
  1402.               case 4:
  1403.                 memcpy (&gate, &descr, sizeof gate);
  1404.                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
  1405.                                  gate.selector, gate.offset1, gate.offset0);
  1406.                 printf_filtered (" 16-bit Call Gate (params=%d)",
  1407.                                  gate.param_count);
  1408.                 break;
  1409.               case 5:
  1410.                 printf_filtered ("TSS selector=0x%04x", descr.base0);
  1411.                 printfi_filtered (16, "Task Gate");
  1412.                 break;
  1413.               case 6:
  1414.               case 7:
  1415.                 memcpy (&gate, &descr, sizeof gate);
  1416.                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
  1417.                                  gate.selector, gate.offset1, gate.offset0);
  1418.                 printf_filtered (" 16-bit %s Gate",
  1419.                                  descr.stype == 6 ? "Interrupt" : "Trap");
  1420.                 break;
  1421.               case 9:
  1422.               case 11:
  1423.                 printf_filtered (" 32-bit TSS (task %sactive)",
  1424.                                  descr.stype == 3 ? "" : "in");
  1425.                 break;
  1426.               case 12:
  1427.                 memcpy (&gate, &descr, sizeof gate);
  1428.                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
  1429.                                  gate.selector, gate.offset1, gate.offset0);
  1430.                 printf_filtered (" 32-bit Call Gate (params=%d)",
  1431.                                  gate.param_count);
  1432.                 break;
  1433.               case 14:
  1434.               case 15:
  1435.                 memcpy (&gate, &descr, sizeof gate);
  1436.                 printf_filtered ("selector=0x%04x  offs=0x%04x%04x",
  1437.                                  gate.selector, gate.offset1, gate.offset0);
  1438.                 printf_filtered (" 32-bit %s Gate",
  1439.                                  descr.stype == 14 ? "Interrupt" : "Trap");
  1440.                 break;
  1441.               case 16:                /* data segments */
  1442.               case 17:
  1443.               case 18:
  1444.               case 19:
  1445.               case 20:
  1446.               case 21:
  1447.               case 22:
  1448.               case 23:
  1449.                 printf_filtered (" %s-bit Data (%s Exp-%s%s)",
  1450.                                  descr.bit32 ? "32" : "16",
  1451.                                  descr.stype & 2
  1452.                                  ? "Read/Write," : "Read-Only, ",
  1453.                                  descr.stype & 4 ? "down" : "up",
  1454.                                  descr.stype & 1 ? "" : ", N.Acc");
  1455.                 break;
  1456.               case 24:                /* code segments */
  1457.               case 25:
  1458.               case 26:
  1459.               case 27:
  1460.               case 28:
  1461.               case 29:
  1462.               case 30:
  1463.               case 31:
  1464.                 printf_filtered (" %s-bit Code (%s%sConf%s)",
  1465.                                  descr.bit32 ? "32" : "16",
  1466.                                  descr.stype & 2 ? "Exec/Read" : "Exec-Only",
  1467.                                  descr.stype & 4 ? "" : "N.",
  1468.                                  descr.stype & 1 ? "" : ", N.Acc");
  1469.                 break;
  1470.               default:
  1471.                 printf_filtered ("Unknown type 0x%02x", descr.stype);
  1472.                 break;
  1473.             }
  1474.           puts_filtered ("\n");
  1475.         }
  1476.       else if (force)
  1477.         {
  1478.           printf_filtered ("0x%03x: ",
  1479.                            type == 1
  1480.                            ? idx : (idx * 8) | (type ? (cpl | 4) : 0));
  1481.           if (!descr.present)
  1482.             puts_filtered ("Segment not present\n");
  1483.           else
  1484.             printf_filtered ("Segment type 0x%02x is invalid in this table\n",
  1485.                              descr.stype);
  1486.         }
  1487.     }
  1488.   else if (force)
  1489.     printf_filtered ("0x%03x: Cannot read this descriptor\n", idx);
  1490. }

  1491. static void
  1492. go32_sldt (char *arg, int from_tty)
  1493. {
  1494.   struct dtr_reg gdtr;
  1495.   unsigned short ldtr = 0;
  1496.   int ldt_idx;
  1497.   struct seg_descr ldt_descr;
  1498.   long ldt_entry = -1L;
  1499.   int cpl = (prog_has_started ? a_tss.tss_cs : _my_cs ()) & 3;

  1500.   if (arg && *arg)
  1501.     {
  1502.       arg = skip_spaces (arg);

  1503.       if (*arg)
  1504.         {
  1505.           ldt_entry = parse_and_eval_long (arg);
  1506.           if (ldt_entry < 0
  1507.               || (ldt_entry & 4) == 0
  1508.               || (ldt_entry & 3) != (cpl & 3))
  1509.             error (_("Invalid LDT entry 0x%03lx."), (unsigned long)ldt_entry);
  1510.         }
  1511.     }

  1512.   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
  1513.   __asm__ __volatile__ ("sldt   %0" : "=m" (ldtr) : /* no inputs */ );
  1514.   ldt_idx = ldtr / 8;
  1515.   if (ldt_idx == 0)
  1516.     puts_filtered ("There is no LDT.\n");
  1517.   /* LDT's entry in the GDT must have the type LDT, which is 2.  */
  1518.   else if (get_descriptor (gdtr.base, ldt_idx, &ldt_descr) != 2)
  1519.     printf_filtered ("LDT is present (at %#x), but unreadable by GDB.\n",
  1520.                      ldt_descr.base0
  1521.                      | (ldt_descr.base1 << 16)
  1522.                      | (ldt_descr.base2 << 24));
  1523.   else
  1524.     {
  1525.       unsigned base =
  1526.         ldt_descr.base0
  1527.         | (ldt_descr.base1 << 16)
  1528.         | (ldt_descr.base2 << 24);
  1529.       unsigned limit = ldt_descr.limit0 | (ldt_descr.limit1 << 16);
  1530.       int max_entry;

  1531.       if (ldt_descr.page_granular)
  1532.         /* Page-granular segments must have the low 12 bits of their
  1533.            limit set.  */
  1534.         limit = (limit << 12) | 0xfff;
  1535.       /* LDT cannot have more than 8K 8-byte entries, i.e. more than
  1536.          64KB.  */
  1537.       if (limit > 0xffff)
  1538.         limit = 0xffff;

  1539.       max_entry = (limit + 1) / 8;

  1540.       if (ldt_entry >= 0)
  1541.         {
  1542.           if (ldt_entry > limit)
  1543.             error (_("Invalid LDT entry %#lx: outside valid limits [0..%#x]"),
  1544.                    (unsigned long)ldt_entry, limit);

  1545.           display_descriptor (ldt_descr.stype, base, ldt_entry / 8, 1);
  1546.         }
  1547.       else
  1548.         {
  1549.           int i;

  1550.           for (i = 0; i < max_entry; i++)
  1551.             display_descriptor (ldt_descr.stype, base, i, 0);
  1552.         }
  1553.     }
  1554. }

  1555. static void
  1556. go32_sgdt (char *arg, int from_tty)
  1557. {
  1558.   struct dtr_reg gdtr;
  1559.   long gdt_entry = -1L;
  1560.   int max_entry;

  1561.   if (arg && *arg)
  1562.     {
  1563.       arg = skip_spaces (arg);

  1564.       if (*arg)
  1565.         {
  1566.           gdt_entry = parse_and_eval_long (arg);
  1567.           if (gdt_entry < 0 || (gdt_entry & 7) != 0)
  1568.             error (_("Invalid GDT entry 0x%03lx: "
  1569.                      "not an integral multiple of 8."),
  1570.                    (unsigned long)gdt_entry);
  1571.         }
  1572.     }

  1573.   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
  1574.   max_entry = (gdtr.limit + 1) / 8;

  1575.   if (gdt_entry >= 0)
  1576.     {
  1577.       if (gdt_entry > gdtr.limit)
  1578.         error (_("Invalid GDT entry %#lx: outside valid limits [0..%#x]"),
  1579.                (unsigned long)gdt_entry, gdtr.limit);

  1580.       display_descriptor (0, gdtr.base, gdt_entry / 8, 1);
  1581.     }
  1582.   else
  1583.     {
  1584.       int i;

  1585.       for (i = 0; i < max_entry; i++)
  1586.         display_descriptor (0, gdtr.base, i, 0);
  1587.     }
  1588. }

  1589. static void
  1590. go32_sidt (char *arg, int from_tty)
  1591. {
  1592.   struct dtr_reg idtr;
  1593.   long idt_entry = -1L;
  1594.   int max_entry;

  1595.   if (arg && *arg)
  1596.     {
  1597.       arg = skip_spaces (arg);

  1598.       if (*arg)
  1599.         {
  1600.           idt_entry = parse_and_eval_long (arg);
  1601.           if (idt_entry < 0)
  1602.             error (_("Invalid (negative) IDT entry %ld."), idt_entry);
  1603.         }
  1604.     }

  1605.   __asm__ __volatile__ ("sidt   %0" : "=m" (idtr) : /* no inputs */ );
  1606.   max_entry = (idtr.limit + 1) / 8;
  1607.   if (max_entry > 0x100)        /* No more than 256 entries.  */
  1608.     max_entry = 0x100;

  1609.   if (idt_entry >= 0)
  1610.     {
  1611.       if (idt_entry > idtr.limit)
  1612.         error (_("Invalid IDT entry %#lx: outside valid limits [0..%#x]"),
  1613.                (unsigned long)idt_entry, idtr.limit);

  1614.       display_descriptor (1, idtr.base, idt_entry, 1);
  1615.     }
  1616.   else
  1617.     {
  1618.       int i;

  1619.       for (i = 0; i < max_entry; i++)
  1620.         display_descriptor (1, idtr.base, i, 0);
  1621.     }
  1622. }

  1623. /* Cached linear address of the base of the page directory.  For
  1624.    now, available only under CWSDPMI.  Code based on ideas and
  1625.    suggestions from Charles Sandmann <sandmann@clio.rice.edu>.  */
  1626. static unsigned long pdbr;

  1627. static unsigned long
  1628. get_cr3 (void)
  1629. {
  1630.   unsigned offset;
  1631.   unsigned taskreg;
  1632.   unsigned long taskbase, cr3;
  1633.   struct dtr_reg gdtr;

  1634.   if (pdbr > 0 && pdbr <= 0xfffff)
  1635.     return pdbr;

  1636.   /* Get the linear address of GDT and the Task Register.  */
  1637.   __asm__ __volatile__ ("sgdt   %0" : "=m" (gdtr) : /* no inputs */ );
  1638.   __asm__ __volatile__ ("str    %0" : "=m" (taskreg) : /* no inputs */ );

  1639.   /* Task Register is a segment selector for the TSS of the current
  1640.      task.  Therefore, it can be used as an index into the GDT to get
  1641.      at the segment descriptor for the TSS.  To get the index, reset
  1642.      the low 3 bits of the selector (which give the CPL).  Add 2 to the
  1643.      offset to point to the 3 low bytes of the base address.  */
  1644.   offset = gdtr.base + (taskreg & 0xfff8) + 2;


  1645.   /* CWSDPMI's task base is always under the 1MB mark.  */
  1646.   if (offset > 0xfffff)
  1647.     return 0;

  1648.   _farsetsel (_dos_ds);
  1649.   taskbase  = _farnspeekl (offset) & 0xffffffU;
  1650.   taskbase += _farnspeekl (offset + 2) & 0xff000000U;
  1651.   if (taskbase > 0xfffff)
  1652.     return 0;

  1653.   /* CR3 (a.k.a. PDBR, the Page Directory Base Register) is stored at
  1654.      offset 1Ch in the TSS.  */
  1655.   cr3 = _farnspeekl (taskbase + 0x1c) & ~0xfff;
  1656.   if (cr3 > 0xfffff)
  1657.     {
  1658. #if 0  /* Not fullly supported yet.  */
  1659.       /* The Page Directory is in UMBs.  In that case, CWSDPMI puts
  1660.          the first Page Table right below the Page Directory.  Thus,
  1661.          the first Page Table's entry for its own address and the Page
  1662.          Directory entry for that Page Table will hold the same
  1663.          physical address.  The loop below searches the entire UMB
  1664.          range of addresses for such an occurence.  */
  1665.       unsigned long addr, pte_idx;

  1666.       for (addr = 0xb0000, pte_idx = 0xb0;
  1667.            pte_idx < 0xff;
  1668.            addr += 0x1000, pte_idx++)
  1669.         {
  1670.           if (((_farnspeekl (addr + 4 * pte_idx) & 0xfffff027) ==
  1671.                (_farnspeekl (addr + 0x1000) & 0xfffff027))
  1672.               && ((_farnspeekl (addr + 4 * pte_idx + 4) & 0xfffff000) == cr3))
  1673.             {
  1674.               cr3 = addr + 0x1000;
  1675.               break;
  1676.             }
  1677.         }
  1678. #endif

  1679.       if (cr3 > 0xfffff)
  1680.         cr3 = 0;
  1681.     }

  1682.   return cr3;
  1683. }

  1684. /* Return the N'th Page Directory entry.  */
  1685. static unsigned long
  1686. get_pde (int n)
  1687. {
  1688.   unsigned long pde = 0;

  1689.   if (pdbr && n >= 0 && n < 1024)
  1690.     {
  1691.       pde = _farpeekl (_dos_ds, pdbr + 4*n);
  1692.     }
  1693.   return pde;
  1694. }

  1695. /* Return the N'th entry of the Page Table whose Page Directory entry
  1696.    is PDE.  */
  1697. static unsigned long
  1698. get_pte (unsigned long pde, int n)
  1699. {
  1700.   unsigned long pte = 0;

  1701.   /* pde & 0x80 tests the 4MB page bit.  We don't support 4MB
  1702.      page tables, for now.  */
  1703.   if ((pde & 1) && !(pde & 0x80) && n >= 0 && n < 1024)
  1704.     {
  1705.       pde &= ~0xfff;        /* Clear non-address bits.  */
  1706.       pte = _farpeekl (_dos_ds, pde + 4*n);
  1707.     }
  1708.   return pte;
  1709. }

  1710. /* Display a Page Directory or Page Table entry.  IS_DIR, if non-zero,
  1711.    says this is a Page Directory entry.  If FORCE is non-zero, display
  1712.    the entry even if its Present flag is off.  OFF is the offset of the
  1713.    address from the page's base address.  */
  1714. static void
  1715. display_ptable_entry (unsigned long entry, int is_dir, int force, unsigned off)
  1716. {
  1717.   if ((entry & 1) != 0)
  1718.     {
  1719.       printf_filtered ("Base=0x%05lx000", entry >> 12);
  1720.       if ((entry & 0x100) && !is_dir)
  1721.         puts_filtered (" Global");
  1722.       if ((entry & 0x40) && !is_dir)
  1723.         puts_filtered (" Dirty");
  1724.       printf_filtered (" %sAcc.", (entry & 0x20) ? "" : "Not-");
  1725.       printf_filtered (" %sCached", (entry & 0x10) ? "" : "Not-");
  1726.       printf_filtered (" Write-%s", (entry & 8) ? "Thru" : "Back");
  1727.       printf_filtered (" %s", (entry & 4) ? "Usr" : "Sup");
  1728.       printf_filtered (" Read-%s", (entry & 2) ? "Write" : "Only");
  1729.       if (off)
  1730.         printf_filtered (" +0x%x", off);
  1731.       puts_filtered ("\n");
  1732.     }
  1733.   else if (force)
  1734.     printf_filtered ("Page%s not present or not supported; value=0x%lx.\n",
  1735.                      is_dir ? " Table" : "", entry >> 1);
  1736. }

  1737. static void
  1738. go32_pde (char *arg, int from_tty)
  1739. {
  1740.   long pde_idx = -1, i;

  1741.   if (arg && *arg)
  1742.     {
  1743.       arg = skip_spaces (arg);

  1744.       if (*arg)
  1745.         {
  1746.           pde_idx = parse_and_eval_long (arg);
  1747.           if (pde_idx < 0 || pde_idx >= 1024)
  1748.             error (_("Entry %ld is outside valid limits [0..1023]."), pde_idx);
  1749.         }
  1750.     }

  1751.   pdbr = get_cr3 ();
  1752.   if (!pdbr)
  1753.     puts_filtered ("Access to Page Directories is "
  1754.                    "not supported on this system.\n");
  1755.   else if (pde_idx >= 0)
  1756.     display_ptable_entry (get_pde (pde_idx), 1, 1, 0);
  1757.   else
  1758.     for (i = 0; i < 1024; i++)
  1759.       display_ptable_entry (get_pde (i), 1, 0, 0);
  1760. }

  1761. /* A helper function to display entries in a Page Table pointed to by
  1762.    the N'th entry in the Page Directory.  If FORCE is non-zero, say
  1763.    something even if the Page Table is not accessible.  */
  1764. static void
  1765. display_page_table (long n, int force)
  1766. {
  1767.   unsigned long pde = get_pde (n);

  1768.   if ((pde & 1) != 0)
  1769.     {
  1770.       int i;

  1771.       printf_filtered ("Page Table pointed to by "
  1772.                        "Page Directory entry 0x%lx:\n", n);
  1773.       for (i = 0; i < 1024; i++)
  1774.         display_ptable_entry (get_pte (pde, i), 0, 0, 0);
  1775.       puts_filtered ("\n");
  1776.     }
  1777.   else if (force)
  1778.     printf_filtered ("Page Table not present; value=0x%lx.\n", pde >> 1);
  1779. }

  1780. static void
  1781. go32_pte (char *arg, int from_tty)
  1782. {
  1783.   long pde_idx = -1L, i;

  1784.   if (arg && *arg)
  1785.     {
  1786.       arg = skip_spaces (arg);

  1787.       if (*arg)
  1788.         {
  1789.           pde_idx = parse_and_eval_long (arg);
  1790.           if (pde_idx < 0 || pde_idx >= 1024)
  1791.             error (_("Entry %ld is outside valid limits [0..1023]."), pde_idx);
  1792.         }
  1793.     }

  1794.   pdbr = get_cr3 ();
  1795.   if (!pdbr)
  1796.     puts_filtered ("Access to Page Tables is not supported on this system.\n");
  1797.   else if (pde_idx >= 0)
  1798.     display_page_table (pde_idx, 1);
  1799.   else
  1800.     for (i = 0; i < 1024; i++)
  1801.       display_page_table (i, 0);
  1802. }

  1803. static void
  1804. go32_pte_for_address (char *arg, int from_tty)
  1805. {
  1806.   CORE_ADDR addr = 0, i;

  1807.   if (arg && *arg)
  1808.     {
  1809.       arg = skip_spaces (arg);

  1810.       if (*arg)
  1811.         addr = parse_and_eval_address (arg);
  1812.     }
  1813.   if (!addr)
  1814.     error_no_arg (_("linear address"));

  1815.   pdbr = get_cr3 ();
  1816.   if (!pdbr)
  1817.     puts_filtered ("Access to Page Tables is not supported on this system.\n");
  1818.   else
  1819.     {
  1820.       int pde_idx = (addr >> 22) & 0x3ff;
  1821.       int pte_idx = (addr >> 12) & 0x3ff;
  1822.       unsigned offs = addr & 0xfff;

  1823.       printf_filtered ("Page Table entry for address %s:\n",
  1824.                        hex_string(addr));
  1825.       display_ptable_entry (get_pte (get_pde (pde_idx), pte_idx), 0, 1, offs);
  1826.     }
  1827. }

  1828. static struct cmd_list_element *info_dos_cmdlist = NULL;

  1829. static void
  1830. go32_info_dos_command (char *args, int from_tty)
  1831. {
  1832.   help_list (info_dos_cmdlist, "info dos ", class_info, gdb_stdout);
  1833. }

  1834. /* -Wmissing-prototypes */
  1835. extern initialize_file_ftype _initialize_go32_nat;

  1836. void
  1837. _initialize_go32_nat (void)
  1838. {
  1839.   struct target_ops *t = go32_target ();

  1840.   x86_dr_low.set_control = go32_set_dr7;
  1841.   x86_dr_low.set_addr = go32_set_dr;
  1842.   x86_dr_low.get_status = go32_get_dr6;
  1843.   x86_dr_low.get_control = go32_get_dr7;
  1844.   x86_dr_low.get_addr = go32_get_dr;
  1845.   x86_set_debug_register_length (4);

  1846.   x86_use_watchpoints (t);
  1847.   add_target (t);

  1848.   /* Initialize child's cwd as empty to be initialized when starting
  1849.      the child.  */
  1850.   *child_cwd = 0;

  1851.   /* Initialize child's command line storage.  */
  1852.   if (redir_debug_init (&child_cmd) == -1)
  1853.     internal_error (__FILE__, __LINE__,
  1854.                     _("Cannot allocate redirection storage: "
  1855.                       "not enough memory.\n"));

  1856.   /* We are always processing GCC-compiled programs.  */
  1857.   processing_gcc_compilation = 2;

  1858.   add_prefix_cmd ("dos", class_info, go32_info_dos_command, _("\
  1859. Print information specific to DJGPP (aka MS-DOS) debugging."),
  1860.                   &info_dos_cmdlist, "info dos ", 0, &infolist);

  1861.   add_cmd ("sysinfo", class_info, go32_sysinfo, _("\
  1862. Display information about the target system, including CPU, OS, DPMI, etc."),
  1863.            &info_dos_cmdlist);
  1864.   add_cmd ("ldt", class_info, go32_sldt, _("\
  1865. Display entries in the LDT (Local Descriptor Table).\n\
  1866. Entry number (an expression) as an argument means display only that entry."),
  1867.            &info_dos_cmdlist);
  1868.   add_cmd ("gdt", class_info, go32_sgdt, _("\
  1869. Display entries in the GDT (Global Descriptor Table).\n\
  1870. Entry number (an expression) as an argument means display only that entry."),
  1871.            &info_dos_cmdlist);
  1872.   add_cmd ("idt", class_info, go32_sidt, _("\
  1873. Display entries in the IDT (Interrupt Descriptor Table).\n\
  1874. Entry number (an expression) as an argument means display only that entry."),
  1875.            &info_dos_cmdlist);
  1876.   add_cmd ("pde", class_info, go32_pde, _("\
  1877. Display entries in the Page Directory.\n\
  1878. Entry number (an expression) as an argument means display only that entry."),
  1879.            &info_dos_cmdlist);
  1880.   add_cmd ("pte", class_info, go32_pte, _("\
  1881. Display entries in Page Tables.\n\
  1882. Entry number (an expression) as an argument means display only entries\n\
  1883. from the Page Table pointed to by the specified Page Directory entry."),
  1884.            &info_dos_cmdlist);
  1885.   add_cmd ("address-pte", class_info, go32_pte_for_address, _("\
  1886. Display a Page Table entry for a linear address.\n\
  1887. The address argument must be a linear address, after adding to\n\
  1888. it the base address of the appropriate segment.\n\
  1889. The base address of variables and functions in the debuggee's data\n\
  1890. or code segment is stored in the variable __djgpp_base_address,\n\
  1891. so use `__djgpp_base_address + (char *)&var' as the argument.\n\
  1892. For other segments, look up their base address in the output of\n\
  1893. the `info dos ldt' command."),
  1894.            &info_dos_cmdlist);
  1895. }

  1896. pid_t
  1897. tcgetpgrp (int fd)
  1898. {
  1899.   if (isatty (fd))
  1900.     return SOME_PID;
  1901.   errno = ENOTTY;
  1902.   return -1;
  1903. }

  1904. int
  1905. tcsetpgrp (int fd, pid_t pgid)
  1906. {
  1907.   if (isatty (fd) && pgid == SOME_PID)
  1908.     return 0;
  1909.   errno = pgid == SOME_PID ? ENOTTY : ENOSYS;
  1910.   return -1;
  1911. }