* Makefile.in (ALLDEPFILES): Remove xcoffexec.c.
[platform/upstream/binutils.git] / gdb / remote-vx.c
1 /* Memory-access and commands for remote VxWorks processes, for GDB.
2    Copyright 1990, 1991, 1992 Free Software Foundation, Inc.
3    Contributed by Wind River Systems and Cygnus Support.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include "defs.h"
22 #include "frame.h"
23 #include "inferior.h"
24 #include "wait.h"
25 #include "target.h"
26 #include "gdbcore.h"
27 #include "command.h"
28 #include "symtab.h"
29 #include "complaints.h"
30 #include "gdbcmd.h"
31 #include "bfd.h" /* Required by objfiles.h.  */
32 #include "symfile.h" /* Required by objfiles.h.  */
33 #include "objfiles.h"
34 #include "gdb-stabs.h"
35
36 #include <string.h>
37 #include <errno.h>
38 #include <signal.h>
39 #include <fcntl.h>
40 #include <sys/types.h>
41 #include <sys/socket.h>
42 #define malloc bogon_malloc     /* Sun claims "char *malloc()" not void * */
43 #define free bogon_free         /* Sun claims "int free()" not void */
44 #define realloc bogon_realloc   /* Sun claims "char *realloc()", not void * */
45 #include <rpc/rpc.h>
46 #undef malloc
47 #undef free
48 #undef realloc
49 #include <sys/time.h>           /* UTek's <rpc/rpc.h> doesn't #incl this */
50 #include <netdb.h>
51 #include "vx-share/ptrace.h"
52 #include "vx-share/xdr_ptrace.h"
53 #include "vx-share/xdr_ld.h"
54 #include "vx-share/xdr_rdb.h"
55 #include "vx-share/dbgRpcLib.h"
56
57 #include <symtab.h>
58
59 extern void symbol_file_command ();
60 extern int stop_soon_quietly;           /* for wait_for_inferior */
61
62 static int net_ptrace_clnt_call ();     /* Forward decl */
63 static enum clnt_stat net_clnt_call (); /* Forward decl */
64 extern struct target_ops vx_ops, vx_run_ops;    /* Forward declaration */
65
66 /* Saved name of target host and called function for "info files".
67    Both malloc'd.  */
68
69 static char *vx_host;
70 static char *vx_running;                /* Called function */
71
72 /* Nonzero means target that is being debugged remotely has a floating
73    point processor.  */
74
75 static int target_has_fp;
76
77 /* Default error message when the network is forking up.  */
78
79 static const char rpcerr[] = "network target debugging:  rpc error";
80
81 CLIENT *pClient;         /* client used in net debugging */
82 static int ptraceSock = RPC_ANYSOCK;
83
84 enum clnt_stat net_clnt_call();
85 static void parse_args ();
86
87 static struct timeval rpcTimeout = { 10, 0 };
88
89 static char *skip_white_space ();
90 static char *find_white_space ();
91  
92 /* Tell the VxWorks target system to download a file.
93    The load addresses of the text, data, and bss segments are
94    stored in *pTextAddr, *pDataAddr, and *pBssAddr (respectively).
95    Returns 0 for success, -1 for failure.  */
96
97 static int
98 net_load (filename, pTextAddr, pDataAddr, pBssAddr)
99      char *filename;
100      CORE_ADDR *pTextAddr;
101      CORE_ADDR *pDataAddr;
102      CORE_ADDR *pBssAddr;
103 {
104   enum clnt_stat status;
105   struct ldfile ldstruct;
106   struct timeval load_timeout;
107
108   memset ((char *) &ldstruct, '\0', sizeof (ldstruct));
109
110   /* We invoke clnt_call () here directly, instead of through
111      net_clnt_call (), because we need to set a large timeout value.
112      The load on the target side can take quite a while, easily
113      more than 10 seconds.  The user can kill this call by typing
114      CTRL-C if there really is a problem with the load.  
115
116      Do not change the tv_sec value without checking -- select() imposes
117      a limit of 10**8 on it for no good reason that I can see...  */
118
119   load_timeout.tv_sec = 99999999;   /* A large number, effectively inf. */
120   load_timeout.tv_usec = 0;
121  
122   status = clnt_call (pClient, VX_LOAD, xdr_wrapstring, &filename, xdr_ldfile,
123                       &ldstruct, load_timeout);
124
125   if (status == RPC_SUCCESS)
126     {
127       if (*ldstruct.name == 0)  /* load failed on VxWorks side */
128         return -1;
129       *pTextAddr = ldstruct.txt_addr;
130       *pDataAddr = ldstruct.data_addr;
131       *pBssAddr = ldstruct.bss_addr;
132       return 0;
133     }
134   else
135     return -1;
136 }
137
138 /* returns 0 if successful, errno if RPC failed or VxWorks complains. */
139
140 static int
141 net_break (addr, procnum)
142      int addr;
143      u_long procnum;
144 {
145   enum clnt_stat status;
146   int break_status;
147   Rptrace ptrace_in;  /* XXX This is stupid.  It doesn't need to be a ptrace
148                          structure.  How about something smaller? */
149
150   memset ((char *) &ptrace_in, '\0', sizeof (ptrace_in));
151   break_status = 0;
152
153   ptrace_in.addr = addr;
154   ptrace_in.pid = inferior_pid;
155
156   status = net_clnt_call (procnum, xdr_rptrace, &ptrace_in, xdr_int,
157                           &break_status);
158
159   if (status != RPC_SUCCESS)
160       return errno;
161
162   if (break_status == -1)
163     return ENOMEM;
164   return break_status;  /* probably (FIXME) zero */
165 }
166
167 /* returns 0 if successful, errno otherwise */
168
169 static int
170 vx_insert_breakpoint (addr)
171      int addr;
172 {
173   return net_break (addr, VX_BREAK_ADD);
174 }
175
176 /* returns 0 if successful, errno otherwise */
177
178 static int
179 vx_remove_breakpoint (addr)
180      int addr;
181 {
182   return net_break (addr, VX_BREAK_DELETE);
183 }
184
185 /* Start an inferior process and sets inferior_pid to its pid.
186    EXEC_FILE is the file to run.
187    ALLARGS is a string containing the arguments to the program.
188    ENV is the environment vector to pass.
189    Returns process id.  Errors reported with error().
190    On VxWorks, we ignore exec_file.  */
191  
192 static void
193 vx_create_inferior (exec_file, args, env)
194      char *exec_file;
195      char *args;
196      char **env;
197 {
198   enum clnt_stat status;
199   arg_array passArgs;
200   TASK_START taskStart;
201
202   memset ((char *) &passArgs, '\0', sizeof (passArgs));
203   memset ((char *) &taskStart, '\0', sizeof (taskStart));
204
205   /* parse arguments, put them in passArgs */
206
207   parse_args (args, &passArgs);
208
209   if (passArgs.arg_array_len == 0)
210     error ("You must specify a function name to run, and arguments if any");
211
212   status = net_clnt_call (PROCESS_START, xdr_arg_array, &passArgs,
213                           xdr_TASK_START, &taskStart);
214
215   if ((status != RPC_SUCCESS) || (taskStart.status == -1))
216     error ("Can't create process on remote target machine");
217
218   /* Save the name of the running function */
219   vx_running = savestring (passArgs.arg_array_val[0],
220                            strlen (passArgs.arg_array_val[0]));
221
222   push_target (&vx_run_ops);
223   inferior_pid = taskStart.pid;
224
225   /* We will get a trace trap after one instruction.
226      Insert breakpoints and continue.  */
227
228   init_wait_for_inferior ();
229
230   /* Set up the "saved terminal modes" of the inferior
231      based on what modes we are starting it with.  */
232   target_terminal_init ();
233
234   /* Install inferior's terminal modes.  */
235   target_terminal_inferior ();
236
237   stop_soon_quietly = 1;
238   wait_for_inferior ();         /* Get the task spawn event */
239   stop_soon_quietly = 0;
240
241   /* insert_step_breakpoint ();  FIXME, do we need this?  */
242   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
243 }
244
245 /* Fill ARGSTRUCT in argc/argv form with the arguments from the
246    argument string ARGSTRING.  */
247
248 static void
249 parse_args (arg_string, arg_struct)
250      register char *arg_string;
251      arg_array *arg_struct;
252 {
253   register int arg_count = 0;   /* number of arguments */
254   register int arg_index = 0;
255   register char *p0;
256  
257   memset ((char *) arg_struct, '\0', sizeof (arg_array));
258  
259   /* first count how many arguments there are */
260
261   p0 = arg_string;
262   while (*p0 != '\0')
263     {
264       if (*(p0 = skip_white_space (p0)) == '\0')
265         break;
266       p0 = find_white_space (p0);
267       arg_count++;
268     }
269
270   arg_struct->arg_array_len = arg_count;
271   arg_struct->arg_array_val = (char **) xmalloc ((arg_count + 1)
272                                                  * sizeof (char *));
273
274   /* now copy argument strings into arg_struct.  */
275
276   while (*(arg_string = skip_white_space (arg_string)))
277     {
278       p0 = find_white_space (arg_string);
279       arg_struct->arg_array_val[arg_index++] = savestring (arg_string,
280                                                            p0 - arg_string);
281       arg_string = p0;
282     }
283
284   arg_struct->arg_array_val[arg_count] = NULL;
285 }
286
287 /* Advance a string pointer across whitespace and return a pointer
288    to the first non-white character.  */
289
290 static char *
291 skip_white_space (p)
292      register char *p;
293 {
294   while (*p == ' ' || *p == '\t')
295     p++;
296   return p;
297 }
298     
299 /* Search for the first unquoted whitespace character in a string.
300    Returns a pointer to the character, or to the null terminator
301    if no whitespace is found.  */
302
303 static char *
304 find_white_space (p)
305      register char *p;
306 {
307   register int c;
308
309   while ((c = *p) != ' ' && c != '\t' && c)
310     {
311       if (c == '\'' || c == '"')
312         {
313           while (*++p != c && *p)
314             {
315               if (*p == '\\')
316                 p++;
317             }
318           if (!*p)
319             break;
320         }
321       p++;
322     }
323   return p;
324 }
325     
326 /* Poll the VxWorks target system for an event related
327    to the debugged task.
328    Returns -1 if remote wait failed, task status otherwise.  */
329
330 static int
331 net_wait (pEvent)
332     RDB_EVENT *pEvent;
333 {
334     int pid;
335     enum clnt_stat status;
336
337     memset ((char *) pEvent, '\0', sizeof (RDB_EVENT));
338
339     pid = inferior_pid;
340     status = net_clnt_call (PROCESS_WAIT, xdr_int, &pid, xdr_RDB_EVENT,
341                             pEvent);
342
343     return (status == RPC_SUCCESS)? pEvent->status: -1;
344 }
345     
346 /* Suspend the remote task.
347    Returns -1 if suspend fails on target system, 0 otherwise.  */
348
349 static int
350 net_quit ()
351 {
352   int pid;
353   int quit_status;
354   enum clnt_stat status;
355
356   quit_status = 0;
357
358   /* don't let rdbTask suspend itself by passing a pid of 0 */
359
360   if ((pid = inferior_pid) == 0)
361     return -1;
362
363   status = net_clnt_call (VX_TASK_SUSPEND, xdr_int, &pid, xdr_int,
364                           &quit_status);
365
366   return (status == RPC_SUCCESS)? quit_status: -1;
367 }
368
369 /* Read a register or registers from the remote system.  */
370
371 static void
372 vx_read_register (regno)
373      int regno;
374 {
375   int status;
376   Rptrace ptrace_in;
377   Ptrace_return ptrace_out;
378   C_bytes in_data;
379   C_bytes out_data;
380   extern char registers[];
381
382   memset ((char *) &ptrace_in, '\0', sizeof (ptrace_in));
383   memset ((char *) &ptrace_out, '\0', sizeof (ptrace_out));
384
385   /* FIXME, eventually only get the ones we need.  */
386   registers_fetched ();
387   
388   ptrace_in.pid = inferior_pid;
389   ptrace_out.info.more_data = (caddr_t) &out_data;
390   out_data.len   = VX_NUM_REGS * REGISTER_RAW_SIZE (0);
391   out_data.bytes = (caddr_t) registers;
392   
393   status = net_ptrace_clnt_call (PTRACE_GETREGS, &ptrace_in, &ptrace_out);
394   if (status)
395     error (rpcerr);
396   if (ptrace_out.status == -1)
397     {
398       errno = ptrace_out.errno;
399       perror_with_name ("net_ptrace_clnt_call(PTRACE_GETREGS)");
400     }
401   
402 #ifdef VX_SIZE_FPREGS
403   /* If the target has floating point registers, fetch them.
404      Otherwise, zero the floating point register values in
405      registers[] for good measure, even though we might not
406      need to.  */
407
408   if (target_has_fp)
409     {
410       ptrace_in.pid = inferior_pid;
411       ptrace_out.info.more_data = (caddr_t) &out_data;
412       out_data.len   =  VX_SIZE_FPREGS;
413       out_data.bytes = (caddr_t) &registers[REGISTER_BYTE (FP0_REGNUM)];
414   
415       status = net_ptrace_clnt_call (PTRACE_GETFPREGS, &ptrace_in, &ptrace_out);
416       if (status)
417         error (rpcerr);
418       if (ptrace_out.status == -1)
419         {
420           errno = ptrace_out.errno;
421           perror_with_name ("net_ptrace_clnt_call(PTRACE_GETFPREGS)");
422         }
423     }
424   else
425     {
426       memset (&registers[REGISTER_BYTE (FP0_REGNUM)], '\0', VX_SIZE_FPREGS);
427     }
428 #endif /* VX_SIZE_FPREGS */
429 }
430
431 /* Prepare to store registers.  Since we will store all of them,
432    read out their current values now.  */
433
434 static void
435 vx_prepare_to_store ()
436 {
437   /* Fetch all registers, if any of them are not yet fetched.  */
438   read_register_bytes (0, NULL, REGISTER_BYTES);
439 }
440
441
442 /* Store our register values back into the inferior.
443    If REGNO is -1, do this for all registers.
444    Otherwise, REGNO specifies which register (so we can save time).  */
445 /* FIXME, look at REGNO to save time here */
446
447 static void
448 vx_write_register (regno)
449      int regno;
450 {
451   C_bytes in_data;
452   C_bytes out_data;
453   extern char registers[];
454   int status;
455   Rptrace ptrace_in;
456   Ptrace_return ptrace_out;
457
458   memset ((char *) &ptrace_in, '\0', sizeof (ptrace_in));
459   memset ((char *) &ptrace_out, '\0', sizeof (ptrace_out));
460
461   ptrace_in.pid = inferior_pid;
462   ptrace_in.info.ttype     = DATA;
463   ptrace_in.info.more_data = (caddr_t) &in_data;
464
465   in_data.bytes = registers;
466
467   in_data.len = VX_NUM_REGS * REGISTER_SIZE;
468
469   /* XXX change second param to be a proc number */
470   status = net_ptrace_clnt_call (PTRACE_SETREGS, &ptrace_in, &ptrace_out);
471   if (status)
472     error (rpcerr);
473   if (ptrace_out.status == -1)
474     {
475       errno = ptrace_out.errno;
476       perror_with_name ("net_ptrace_clnt_call(PTRACE_SETREGS)");
477     }
478
479 #ifdef VX_SIZE_FPREGS
480   /* Store floating point registers if the target has them.  */
481
482   if (target_has_fp)
483     {
484       ptrace_in.pid = inferior_pid;
485       ptrace_in.info.ttype     = DATA;
486       ptrace_in.info.more_data = (caddr_t) &in_data;
487
488
489       in_data.bytes = &registers[REGISTER_BYTE (FP0_REGNUM)];
490       in_data.len = VX_SIZE_FPREGS;
491
492       status = net_ptrace_clnt_call (PTRACE_SETFPREGS, &ptrace_in,
493                                      &ptrace_out);
494       if (status)
495           error (rpcerr);
496       if (ptrace_out.status == -1)
497         {
498           errno = ptrace_out.errno;
499           perror_with_name ("net_ptrace_clnt_call(PTRACE_SETFPREGS)");
500         }
501     }
502 #endif  /* VX_SIZE_FPREGS */
503 }
504
505 /* Copy LEN bytes to or from remote inferior's memory starting at MEMADDR
506    to debugger memory starting at MYADDR.  WRITE is true if writing to the
507    inferior.
508    Result is the number of bytes written or read (zero if error).  The
509    protocol allows us to return a negative count, indicating that we can't
510    handle the current address but can handle one N bytes further, but
511    vxworks doesn't give us that information.  */
512
513 static int
514 vx_xfer_memory (memaddr, myaddr, len, write, target)
515      CORE_ADDR memaddr;
516      char *myaddr;
517      int len;
518      int write;
519      struct target_ops *target;                 /* ignored */
520 {
521   int status;
522   Rptrace ptrace_in;
523   Ptrace_return ptrace_out;
524   C_bytes data;
525
526   memset ((char *) &ptrace_in, '\0', sizeof (ptrace_in));
527   memset ((char *) &ptrace_out, '\0', sizeof (ptrace_out));
528
529   ptrace_in.pid = inferior_pid;         /* XXX pid unnecessary for READDATA */
530   ptrace_in.addr = (int) memaddr;       /* Where from */
531   ptrace_in.data = len;                 /* How many bytes */
532
533   if (write)
534     {
535       ptrace_in.info.ttype     = DATA;
536       ptrace_in.info.more_data = (caddr_t) &data;
537
538       data.bytes = (caddr_t) myaddr;    /* Where from */
539       data.len   = len;                 /* How many bytes (again, for XDR) */
540
541       /* XXX change second param to be a proc number */
542       status = net_ptrace_clnt_call (PTRACE_WRITEDATA, &ptrace_in,
543                                      &ptrace_out);
544     }
545   else
546     {
547       ptrace_out.info.more_data = (caddr_t) &data;
548       data.bytes = myaddr;              /* Where to */
549       data.len   = len;                 /* How many (again, for XDR) */
550
551       /* XXX change second param to be a proc number */
552       status = net_ptrace_clnt_call (PTRACE_READDATA, &ptrace_in, &ptrace_out);
553     }
554
555   if (status)
556       error (rpcerr);
557   if (ptrace_out.status == -1)
558     {
559       return 0;         /* No bytes moved */
560     }
561   return len;           /* Moved *all* the bytes */
562 }
563
564 static void
565 vx_files_info ()
566 {
567   printf_unfiltered ("\tAttached to host `%s'", vx_host);
568   printf_unfiltered (", which has %sfloating point", target_has_fp? "": "no ");
569   printf_unfiltered (".\n");
570 }
571
572 static void
573 vx_run_files_info ()
574 {
575   printf_unfiltered ("\tRunning %s VxWorks process %s", 
576                      vx_running ? "child" : "attached",
577                      local_hex_string (inferior_pid));
578   if (vx_running)
579     printf_unfiltered (", function `%s'", vx_running);
580   printf_unfiltered(".\n");
581 }
582
583 static void
584 vx_resume (pid, step, siggnal)
585      int pid;
586      int step;
587      enum target_signal siggnal;
588 {
589   int status;
590   Rptrace ptrace_in;
591   Ptrace_return ptrace_out;
592
593   if (pid == -1)
594     pid = inferior_pid;
595
596   if (siggnal != 0 && siggnal != stop_signal)
597     error ("Cannot send signals to VxWorks processes");
598
599   memset ((char *) &ptrace_in, '\0', sizeof (ptrace_in));
600   memset ((char *) &ptrace_out, '\0', sizeof (ptrace_out));
601
602   ptrace_in.pid = pid;
603   ptrace_in.addr = 1;   /* Target side insists on this, or it panics.  */
604
605   /* XXX change second param to be a proc number */
606   status = net_ptrace_clnt_call (step? PTRACE_SINGLESTEP: PTRACE_CONT,
607                                  &ptrace_in, &ptrace_out);
608   if (status)
609     error (rpcerr);
610   if (ptrace_out.status == -1)
611     {
612       errno = ptrace_out.errno;
613       perror_with_name ("Resuming remote process");
614     }
615 }
616
617 static void
618 vx_mourn_inferior ()
619 {
620   pop_target ();                /* Pop back to no-child state */
621   generic_mourn_inferior ();
622 }
623
624 \f
625 static void vx_add_symbols PARAMS ((char *, int, CORE_ADDR, CORE_ADDR,
626                                     CORE_ADDR));
627
628 struct find_sect_args {
629   CORE_ADDR text_start;
630   CORE_ADDR data_start;
631   CORE_ADDR bss_start;
632 };
633
634 static void find_sect PARAMS ((bfd *, asection *, void *));
635
636 static void
637 find_sect (abfd, sect, obj)
638      bfd *abfd;
639      asection *sect;
640      PTR obj;
641 {
642   struct find_sect_args *args = (struct find_sect_args *)obj;
643
644   if (bfd_get_section_flags (abfd, sect) & (SEC_CODE & SEC_READONLY))
645     args->text_start = bfd_get_section_vma (abfd, sect);
646   else if (bfd_get_section_flags (abfd, sect) & SEC_ALLOC)
647     {
648       if (bfd_get_section_flags (abfd, sect) & SEC_LOAD)
649         {
650           /* Exclude .ctor and .dtor sections which have SEC_CODE set but not
651              SEC_DATA.  */
652           if (bfd_get_section_flags (abfd, sect) & SEC_DATA)
653             args->data_start = bfd_get_section_vma (abfd, sect);
654         }
655       else
656         args->bss_start = bfd_get_section_vma (abfd, sect);
657     }
658 }
659
660 static void
661 vx_add_symbols (name, from_tty, text_addr, data_addr, bss_addr)
662      char *name;
663      int from_tty;
664      CORE_ADDR text_addr;
665      CORE_ADDR data_addr;
666      CORE_ADDR bss_addr;
667 {
668   struct section_offsets *offs;
669   struct objfile *objfile;
670   struct find_sect_args ss;
671
672   objfile = symbol_file_add (name, from_tty, 0, 0, 0, 0);
673   offs = (struct section_offsets *)
674     alloca (sizeof (struct section_offsets)
675             + objfile->num_sections * sizeof (offs->offsets));
676   memcpy (offs, objfile->section_offsets,
677           sizeof (struct section_offsets)
678           + objfile->num_sections * sizeof (offs->offsets));
679
680   ss.text_start = 0;
681   ss.data_start = 0;
682   ss.bss_start = 0;
683   bfd_map_over_sections (objfile->obfd, find_sect, &ss);
684
685   /* Both COFF and b.out frontends use these SECT_OFF_* values.  */
686   ANOFFSET (offs, SECT_OFF_TEXT) = text_addr - ss.text_start;
687   ANOFFSET (offs, SECT_OFF_DATA) = data_addr - ss.data_start;
688   ANOFFSET (offs, SECT_OFF_BSS) = bss_addr - ss.bss_start;
689   objfile_relocate (objfile, offs);
690 }
691
692 /* This function allows the addition of incrementally linked object files.  */
693
694 static void
695 vx_load_command (arg_string, from_tty)
696      char *arg_string;
697      int from_tty;
698 {
699   CORE_ADDR text_addr;
700   CORE_ADDR data_addr;
701   CORE_ADDR bss_addr;
702
703   if (arg_string == 0)
704     error ("The load command takes a file name");
705
706   arg_string = tilde_expand (arg_string);
707   make_cleanup (free, arg_string);
708
709   dont_repeat ();
710
711   QUIT;
712   immediate_quit++;
713   if (net_load (arg_string, &text_addr, &data_addr, &bss_addr) == -1)
714     error ("Load failed on target machine");
715   immediate_quit--;
716
717   vx_add_symbols (arg_string, from_tty, text_addr, data_addr, bss_addr);
718
719   /* Getting new symbols may change our opinion about what is
720      frameless.  */
721   reinit_frame_cache ();
722 }
723
724 #ifdef FIXME  /* Not ready for prime time */
725 /* Single step the target program at the source or machine level.
726    Takes an error exit if rpc fails.
727    Returns -1 if remote single-step operation fails, else 0.  */
728
729 static int
730 net_step ()
731 {
732   enum clnt_stat status;
733   int step_status;
734   SOURCE_STEP source_step;
735
736   source_step.taskId = inferior_pid;
737
738   if (step_range_end)
739     {
740       source_step.startAddr = step_range_start;
741       source_step.endAddr = step_range_end;
742     }
743   else
744     {
745       source_step.startAddr = 0;
746       source_step.endAddr = 0;
747     }
748
749   status = net_clnt_call (VX_SOURCE_STEP, xdr_SOURCE_STEP, &source_step,
750                           xdr_int, &step_status);
751
752   if (status == RPC_SUCCESS)
753     return step_status;
754   else 
755     error (rpcerr);
756 }
757 #endif
758
759 /* Emulate ptrace using RPC calls to the VxWorks target system.
760    Returns nonzero (-1) if RPC status to VxWorks is bad, 0 otherwise.  */
761
762 static int
763 net_ptrace_clnt_call (request, pPtraceIn, pPtraceOut)
764     enum ptracereq request;
765     Rptrace *pPtraceIn;
766     Ptrace_return *pPtraceOut;
767 {
768   enum clnt_stat status;
769
770   status = net_clnt_call (request, xdr_rptrace, pPtraceIn, xdr_ptrace_return,
771                           pPtraceOut);
772
773   if (status != RPC_SUCCESS)
774       return -1;
775
776   return 0;
777 }
778
779 /* Query the target for the name of the file from which VxWorks was
780    booted.  pBootFile is the address of a pointer to the buffer to
781    receive the file name; if the pointer pointed to by pBootFile is 
782    NULL, memory for the buffer will be allocated by XDR.
783    Returns -1 if rpc failed, 0 otherwise.  */
784
785 static int
786 net_get_boot_file (pBootFile)
787      char **pBootFile;
788 {
789   enum clnt_stat status;
790
791   status = net_clnt_call (VX_BOOT_FILE_INQ, xdr_void, (char *) 0,
792                           xdr_wrapstring, pBootFile);
793   return (status == RPC_SUCCESS) ? 0 : -1;
794 }
795
796 /* Fetch a list of loaded object modules from the VxWorks target.
797    Returns -1 if rpc failed, 0 otherwise
798    There's no way to check if the returned loadTable is correct.
799    VxWorks doesn't check it.  */
800
801 static int
802 net_get_symbols (pLoadTable)
803      ldtabl *pLoadTable;                /* return pointer to ldtabl here */
804 {
805   enum clnt_stat status;
806
807   memset ((char *) pLoadTable, '\0', sizeof (struct ldtabl));
808
809   status = net_clnt_call (VX_STATE_INQ, xdr_void, 0, xdr_ldtabl, pLoadTable);
810   return (status == RPC_SUCCESS) ? 0 : -1;
811 }
812
813 /* Look up a symbol in the VxWorks target's symbol table.
814    Returns status of symbol read on target side (0=success, -1=fail)
815    Returns -1 and complain()s if rpc fails.  */
816
817 struct complaint cant_contact_target =
818   {"Lost contact with VxWorks target", 0, 0};
819
820 static int
821 vx_lookup_symbol (name, pAddr)
822      char *name;                /* symbol name */
823      CORE_ADDR *pAddr;
824 {
825   enum clnt_stat status;
826   SYMBOL_ADDR symbolAddr;
827
828   *pAddr = 0;
829   memset ((char *) &symbolAddr, '\0', sizeof (symbolAddr));
830
831   status = net_clnt_call (VX_SYMBOL_INQ, xdr_wrapstring, &name,
832                           xdr_SYMBOL_ADDR, &symbolAddr);
833   if (status != RPC_SUCCESS)
834     {
835       complain (&cant_contact_target);
836       return -1;
837     }
838
839   *pAddr = symbolAddr.addr;
840   return symbolAddr.status;
841 }
842
843 /* Check to see if the VxWorks target has a floating point coprocessor.
844    Returns 1 if target has floating point processor, 0 otherwise.
845    Calls error() if rpc fails.  */
846
847 static int
848 net_check_for_fp ()
849 {
850   enum clnt_stat status;
851   bool_t fp = 0;        /* true if fp processor is present on target board */
852
853   status = net_clnt_call (VX_FP_INQUIRE, xdr_void, 0, xdr_bool, &fp);
854   if (status != RPC_SUCCESS)
855     error (rpcerr);
856
857    return (int) fp;
858 }
859
860 /* Establish an RPC connection with the VxWorks target system.
861    Calls error () if unable to establish connection.  */
862
863 static void
864 net_connect (host)
865      char *host;
866 {
867   struct sockaddr_in destAddr;
868   struct hostent *destHost;
869   unsigned long addr;
870
871   /* Get the internet address for the given host.  Allow a numeric
872      IP address or a hostname.  */
873
874   addr = inet_addr (host);
875   if (addr == -1)
876     {
877       destHost = (struct hostent *) gethostbyname (host);
878       if (destHost == NULL)
879         /* FIXME: Probably should include hostname here in quotes.
880            For example if the user types "target vxworks vx960 " it should
881            say "Invalid host `vx960 '." not just "Invalid hostname".  */
882         error ("Invalid hostname.  Couldn't find remote host address.");
883       addr = * (unsigned long *) destHost->h_addr;
884     }
885
886   memset (&destAddr, '\0', sizeof (destAddr));
887
888   destAddr.sin_addr.s_addr = addr;
889   destAddr.sin_family      = AF_INET;
890   destAddr.sin_port        = 0; /* set to actual port that remote
891                                    ptrace is listening on.  */
892
893   /* Create a tcp client transport on which to issue
894      calls to the remote ptrace server.  */
895
896   ptraceSock = RPC_ANYSOCK;
897   pClient = clnttcp_create (&destAddr, RDBPROG, RDBVERS, &ptraceSock, 0, 0);
898   /* FIXME, here is where we deal with different version numbers of the
899      proto */
900
901   if (pClient == NULL)
902     {
903       clnt_pcreateerror ("\tnet_connect");
904       error ("Couldn't connect to remote target.");
905     }
906 }
907 \f
908 /* Sleep for the specified number of milliseconds 
909  * (assumed to be less than 1000).
910  * If select () is interrupted, returns immediately;
911  * takes an error exit if select () fails for some other reason.
912  */
913
914 static void
915 sleep_ms (ms)
916      long ms;
917 {
918   struct timeval select_timeout;
919   int status;
920
921   select_timeout.tv_sec = 0;
922   select_timeout.tv_usec = ms * 1000;
923
924   status = select (0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0,
925                    &select_timeout);
926
927   if (status < 0 && errno != EINTR)
928     perror_with_name ("select");
929 }
930
931 static int
932 vx_wait (pid_to_wait_for, status)
933      int pid_to_wait_for;
934      struct target_waitstatus *status;
935 {
936   register int pid;
937   RDB_EVENT rdbEvent;
938   int quit_failed;
939
940   do
941     {
942       /* If CTRL-C is hit during this loop,
943          suspend the inferior process.  */
944
945       quit_failed = 0;
946       if (quit_flag)
947         {
948           quit_failed = (net_quit () == -1);
949           quit_flag = 0;
950         }
951
952       /* If a net_quit () or net_wait () call has failed,
953          allow the user to break the connection with the target.
954          We can't simply error () out of this loop, since the 
955          data structures representing the state of the inferior
956          are in an inconsistent state.  */
957
958       if (quit_failed || net_wait (&rdbEvent) == -1)
959         {
960           terminal_ours ();
961           if (query ("Can't %s.  Disconnect from target system? ",
962                      (quit_failed) ? "suspend remote task"
963                                    : "get status of remote task"))
964             {
965               target_mourn_inferior();
966               error ("Use the \"target\" command to reconnect.");
967             }
968           else
969             {
970               terminal_inferior ();
971               continue;
972             }
973         }
974       
975       pid = rdbEvent.taskId;
976       if (pid == 0)
977         {
978           sleep_ms (200);       /* FIXME Don't kill the network too badly */
979         }
980       else if (pid != inferior_pid)
981         fatal ("Bad pid for debugged task: %s\n",
982                local_hex_string((unsigned long) pid));
983     } while (pid == 0);
984
985   /* The mostly likely kind.  */
986   status->kind = TARGET_WAITKIND_STOPPED;
987
988   switch (rdbEvent.eventType)
989     {
990     case EVENT_EXIT:
991       status->kind = TARGET_WAITKIND_EXITED;
992       /* FIXME is it possible to distinguish between a
993          normal vs abnormal exit in VxWorks? */
994       status->value.integer = 0;
995       break;
996
997     case EVENT_START:
998       /* Task was just started. */
999       status->value.sig = TARGET_SIGNAL_TRAP;
1000       break;
1001
1002     case EVENT_STOP:
1003       status->value.sig = TARGET_SIGNAL_TRAP;
1004       /* XXX was it stopped by a signal?  act accordingly */
1005       break;
1006
1007     case EVENT_BREAK:           /* Breakpoint was hit. */
1008       status->value.sig = TARGET_SIGNAL_TRAP;
1009       break;
1010
1011     case EVENT_SUSPEND:         /* Task was suspended, probably by ^C. */
1012       status->value.sig = TARGET_SIGNAL_INT;
1013       break;
1014
1015     case EVENT_BUS_ERR:         /* Task made evil nasty reference. */
1016       status->value.sig = TARGET_SIGNAL_BUS;
1017       break;
1018
1019     case EVENT_ZERO_DIV:        /* Division by zero */
1020       status->value.sig = TARGET_SIGNAL_FPE;
1021       break;
1022
1023     case EVENT_SIGNAL:
1024 #ifdef I80960
1025       status->value.sig = i960_fault_to_signal (rdbEvent.sigType);
1026 #else
1027       /* Back in the old days, before enum target_signal, this code used
1028          to add NSIG to the signal number and claim that PRINT_RANDOM_SIGNAL
1029          would take care of it.  But PRINT_RANDOM_SIGNAL has never been
1030          defined except on the i960, so I don't really know what we are
1031          supposed to do on other architectures.  */
1032       status->value.sig = TARGET_SIGNAL_UNKNOWN;
1033 #endif
1034       break;
1035     } /* switch */
1036   return pid;
1037 }
1038 \f
1039 static int
1040 symbol_stub (arg)
1041      char *arg;
1042 {
1043   symbol_file_command (arg, 0);
1044   return 1;
1045 }
1046
1047 static int
1048 add_symbol_stub (arg)
1049      char *arg;
1050 {
1051   struct ldfile *pLoadFile = (struct ldfile *)arg;
1052
1053   printf_unfiltered("\t%s: ", pLoadFile->name);
1054   vx_add_symbols (pLoadFile->name, 0, pLoadFile->txt_addr,
1055                   pLoadFile->data_addr, pLoadFile->bss_addr);
1056   printf_unfiltered ("ok\n");
1057   return 1;
1058 }
1059 /* Target command for VxWorks target systems.
1060
1061    Used in vxgdb.  Takes the name of a remote target machine
1062    running vxWorks and connects to it to initialize remote network
1063    debugging.  */
1064
1065 static void
1066 vx_open (args, from_tty)
1067      char *args;
1068      int from_tty;
1069 {
1070   extern int close ();
1071   char *bootFile;
1072   extern char *source_path;
1073   struct ldtabl loadTable;
1074   struct ldfile *pLoadFile;
1075   int i;
1076   extern CLIENT *pClient;
1077   int symbols_added = 0;
1078
1079   if (!args)
1080     error_no_arg ("target machine name");
1081
1082   target_preopen (from_tty);
1083   
1084   unpush_target (&vx_ops);
1085   printf_unfiltered ("Attaching remote machine across net...\n");
1086   gdb_flush (gdb_stdout);
1087
1088   /* Allow the user to kill the connect attempt by typing ^C.
1089      Wait until the call to target_has_fp () completes before
1090      disallowing an immediate quit, since even if net_connect ()
1091      is successful, the remote debug server might be hung.  */
1092
1093   immediate_quit++;
1094
1095   net_connect (args);
1096   target_has_fp = net_check_for_fp ();
1097   printf_filtered ("Connected to %s.\n", args);
1098
1099   immediate_quit--;
1100
1101   push_target (&vx_ops);
1102
1103   /* Save a copy of the target host's name.  */
1104   vx_host = savestring (args, strlen (args));
1105
1106   /* Find out the name of the file from which the target was booted
1107      and load its symbol table.  */
1108
1109   printf_filtered ("Looking in Unix path for all loaded modules:\n");
1110   bootFile = NULL;
1111   if (!net_get_boot_file (&bootFile))
1112     {
1113       if (*bootFile)
1114         {
1115           printf_filtered ("\t%s: ", bootFile);
1116           /* This assumes that the kernel is never relocated.  Hope that is an
1117              accurate assumption.  */
1118           if (catch_errors
1119               (symbol_stub,
1120                bootFile,
1121                "Error while reading symbols from boot file:\n",
1122                RETURN_MASK_ALL))
1123             puts_filtered ("ok\n");
1124         }
1125       else if (from_tty)
1126         printf_unfiltered ("VxWorks kernel symbols not loaded.\n");
1127     }
1128   else
1129     error ("Can't retrieve boot file name from target machine.");
1130
1131   clnt_freeres (pClient, xdr_wrapstring, &bootFile);
1132
1133   if (net_get_symbols (&loadTable) != 0)
1134     error ("Can't read loaded modules from target machine");
1135
1136   i = 0-1;
1137   while (++i < loadTable.tbl_size)
1138     {
1139       QUIT;     /* FIXME, avoids clnt_freeres below:  mem leak */
1140       pLoadFile = &loadTable.tbl_ent [i];
1141 #ifdef WRS_ORIG
1142   {
1143     register int desc;
1144     struct cleanup *old_chain;
1145     char *fullname = NULL;
1146
1147     desc = openp (source_path, 0, pLoadFile->name, O_RDONLY, 0, &fullname);
1148     if (desc < 0)
1149         perror_with_name (pLoadFile->name);
1150     old_chain = make_cleanup (close, desc);
1151     add_file_at_addr (fullname, desc, pLoadFile->txt_addr, pLoadFile->data_addr,
1152                       pLoadFile->bss_addr);
1153     do_cleanups (old_chain);
1154   }
1155 #else
1156       /* FIXME: Is there something better to search than the PATH? (probably
1157          not the source path, since source might be in different directories
1158          than objects.  */
1159
1160       if (catch_errors (add_symbol_stub, (char *)pLoadFile, (char *)0,
1161                         RETURN_MASK_ALL))
1162         symbols_added = 1;
1163 #endif
1164     }
1165   printf_filtered ("Done.\n");
1166
1167   clnt_freeres (pClient, xdr_ldtabl, &loadTable);
1168
1169   /* Getting new symbols may change our opinion about what is
1170      frameless.  */
1171   if (symbols_added)
1172     reinit_frame_cache ();
1173 }
1174 \f
1175 /* Takes a task started up outside of gdb and ``attaches'' to it.
1176    This stops it cold in its tracks and allows us to start tracing it.  */
1177
1178 static void
1179 vx_attach (args, from_tty)
1180      char *args;
1181      int from_tty;
1182 {
1183   unsigned long pid;
1184   char *cptr = 0;
1185   Rptrace ptrace_in;
1186   Ptrace_return ptrace_out;
1187   int status;
1188
1189   if (!args)
1190     error_no_arg ("process-id to attach");
1191
1192   pid = strtoul (args, &cptr, 0);
1193   if ((cptr == args) || (*cptr != '\0'))
1194     error ("Invalid process-id -- give a single number in decimal or 0xhex");
1195
1196   if (from_tty)
1197     printf_unfiltered ("Attaching pid %s.\n",
1198                        local_hex_string((unsigned long) pid));
1199
1200   memset ((char *)&ptrace_in,  '\0', sizeof (ptrace_in));
1201   memset ((char *)&ptrace_out, '\0', sizeof (ptrace_out));
1202   ptrace_in.pid = pid;
1203
1204   status = net_ptrace_clnt_call (PTRACE_ATTACH, &ptrace_in, &ptrace_out);
1205   if (status == -1)
1206     error (rpcerr);
1207   if (ptrace_out.status == -1)
1208     {
1209       errno = ptrace_out.errno;
1210       perror_with_name ("Attaching remote process");
1211     }
1212
1213   /* It worked... */
1214   push_target (&vx_run_ops);
1215   /* The unsigned long pid will get turned into a signed int here,
1216      but it doesn't seem to matter.  inferior_pid must be signed
1217      in order for other parts of GDB to work correctly.  */
1218   inferior_pid = pid;
1219   vx_running = 0;
1220 }
1221
1222
1223 /* detach_command --
1224    takes a program previously attached to and detaches it.
1225    The program resumes execution and will no longer stop
1226    on signals, etc.  We better not have left any breakpoints
1227    in the program or it'll die when it hits one.  For this
1228    to work, it may be necessary for the process to have been
1229    previously attached.  It *might* work if the program was
1230    started via the normal ptrace (PTRACE_TRACEME).  */
1231
1232 static void
1233 vx_detach (args, from_tty)
1234      char *args;
1235      int from_tty;
1236 {
1237   Rptrace ptrace_in;
1238   Ptrace_return ptrace_out;
1239   int signal = 0;
1240   int status;
1241
1242   if (args)
1243     error ("Argument given to VxWorks \"detach\".");
1244
1245   if (from_tty)
1246       printf_unfiltered ("Detaching pid %s.\n",
1247               local_hex_string((unsigned long) inferior_pid));
1248
1249   if (args)             /* FIXME, should be possible to leave suspended */
1250     signal = atoi (args);
1251   
1252   memset ((char *)&ptrace_in,  '\0', sizeof (ptrace_in));
1253   memset ((char *)&ptrace_out, '\0', sizeof (ptrace_out));
1254   ptrace_in.pid = inferior_pid;
1255
1256   status = net_ptrace_clnt_call (PTRACE_DETACH, &ptrace_in, &ptrace_out);
1257   if (status == -1)
1258     error (rpcerr);
1259   if (ptrace_out.status == -1)
1260     {
1261       errno = ptrace_out.errno;
1262       perror_with_name ("Detaching VxWorks process");
1263     }
1264
1265   inferior_pid = 0;
1266   pop_target ();        /* go back to non-executing VxWorks connection */
1267 }
1268
1269 /* vx_kill -- takes a running task and wipes it out.  */
1270
1271 static void
1272 vx_kill ()
1273 {
1274   Rptrace ptrace_in;
1275   Ptrace_return ptrace_out;
1276   int status;
1277
1278   printf_unfiltered ("Killing pid %s.\n", local_hex_string((unsigned long) inferior_pid));
1279
1280   memset ((char *)&ptrace_in,  '\0', sizeof (ptrace_in));
1281   memset ((char *)&ptrace_out, '\0', sizeof (ptrace_out));
1282   ptrace_in.pid = inferior_pid;
1283
1284   status = net_ptrace_clnt_call (PTRACE_KILL, &ptrace_in, &ptrace_out);
1285   if (status == -1)
1286     warning (rpcerr);
1287   else if (ptrace_out.status == -1)
1288     {
1289       errno = ptrace_out.errno;
1290       perror_with_name ("Killing VxWorks process");
1291     }
1292
1293   /* If it gives good status, the process is *gone*, no events remain.
1294      If the kill failed, assume the process is gone anyhow.  */
1295   inferior_pid = 0;
1296   pop_target ();        /* go back to non-executing VxWorks connection */
1297 }
1298
1299 /* Clean up from the VxWorks process target as it goes away.  */
1300
1301 static void
1302 vx_proc_close (quitting)
1303      int quitting;
1304 {
1305   inferior_pid = 0;             /* No longer have a process.  */
1306   if (vx_running)
1307     free (vx_running);
1308   vx_running = 0;
1309 }
1310 \f
1311 /* Make an RPC call to the VxWorks target.
1312    Returns RPC status.  */
1313
1314 static enum clnt_stat
1315 net_clnt_call (procNum, inProc, in, outProc, out)
1316     enum ptracereq procNum;
1317     xdrproc_t inProc;
1318     char *in;
1319     xdrproc_t outProc;
1320     char *out;
1321 {
1322   enum clnt_stat status;
1323   
1324   status = clnt_call (pClient, procNum, inProc, in, outProc, out, rpcTimeout);
1325
1326   if (status != RPC_SUCCESS)
1327       clnt_perrno (status);
1328
1329   return status;
1330 }
1331
1332 /* Clean up before losing control.  */
1333
1334 static void
1335 vx_close (quitting)
1336      int quitting;
1337 {
1338   if (pClient)
1339     clnt_destroy (pClient);     /* The net connection */
1340   pClient = 0;
1341
1342   if (vx_host)
1343     free (vx_host);             /* The hostname */
1344   vx_host = 0;
1345 }
1346
1347 /* A vxprocess target should be started via "run" not "target".  */
1348 /*ARGSUSED*/
1349 static void
1350 vx_proc_open (name, from_tty)
1351      char *name;
1352      int from_tty;
1353 {
1354   error ("Use the \"run\" command to start a VxWorks process.");
1355 }
1356
1357 /* Target ops structure for accessing memory and such over the net */
1358
1359 struct target_ops vx_ops = {
1360   "vxworks", "VxWorks target memory via RPC over TCP/IP",
1361   "Use VxWorks target memory.  \n\
1362 Specify the name of the machine to connect to.",
1363   vx_open, vx_close, vx_attach, 0, /* vx_detach, */
1364   0, 0, /* resume, wait */
1365   0, 0, /* read_reg, write_reg */
1366   0, /* prep_to_store, */
1367   vx_xfer_memory, vx_files_info,
1368   0, 0, /* insert_breakpoint, remove_breakpoint */
1369   0, 0, 0, 0, 0,        /* terminal stuff */
1370   0, /* vx_kill, */
1371   vx_load_command,
1372   vx_lookup_symbol,
1373   vx_create_inferior, 0,  /* mourn_inferior */
1374   0, /* can_run */
1375   0, /* notice_signals */
1376   core_stratum, 0, /* next */
1377   1, 1, 0, 0, 0,        /* all mem, mem, stack, regs, exec */
1378   0, 0,                 /* Section pointers */
1379   OPS_MAGIC,            /* Always the last thing */
1380 };
1381
1382 /* Target ops structure for accessing VxWorks child processes over the net */
1383
1384 struct target_ops vx_run_ops = {
1385   "vxprocess", "VxWorks process",
1386   "VxWorks process, started by the \"run\" command.",
1387   vx_proc_open, vx_proc_close, 0, vx_detach, /* vx_attach */
1388   vx_resume, vx_wait,
1389   vx_read_register, vx_write_register,
1390   vx_prepare_to_store,
1391   vx_xfer_memory, vx_run_files_info,
1392   vx_insert_breakpoint, vx_remove_breakpoint,
1393   0, 0, 0, 0, 0,        /* terminal stuff */
1394   vx_kill,
1395   vx_load_command,
1396   vx_lookup_symbol,
1397   0, vx_mourn_inferior,
1398   0, /* can_run */
1399   0, /* notice_signals */
1400   process_stratum, 0, /* next */
1401   0, /* all_mem--off to avoid spurious msg in "i files" */
1402   1, 1, 1, 1,   /* mem, stack, regs, exec */
1403   0, 0,                 /* Section pointers */
1404   OPS_MAGIC,            /* Always the last thing */
1405 };
1406 /* ==> Remember when reading at end of file, there are two "ops" structs here. */
1407 \f
1408 void
1409 _initialize_vx ()
1410 {
1411   add_show_from_set
1412     (add_set_cmd ("vxworks-timeout", class_support, var_uinteger,
1413                   (char *) &rpcTimeout.tv_sec,
1414                   "Set seconds to wait for rpc calls to return.\n\
1415 Set the number of seconds to wait for rpc calls to return.", &setlist),
1416      &showlist);
1417
1418   add_target (&vx_ops);
1419   add_target (&vx_run_ops);
1420 }