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