* target.c (target_detach): Call generic_mourn_inferior.
[platform/upstream/binutils.git] / gdb / target.c
1 /* Select target systems and architectures at runtime for GDB.
2    Copyright 1990, 1992, 1993 Free Software Foundation, Inc.
3    Contributed by 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 <errno.h>
23 #include <ctype.h>
24 #include "target.h"
25 #include "gdbcmd.h"
26 #include "symtab.h"
27 #include "inferior.h"
28 #include "bfd.h"
29 #include "symfile.h"
30 #include "objfiles.h"
31
32 extern int errno;
33
34 static void
35 target_info PARAMS ((char *, int));
36
37 static void
38 cleanup_target PARAMS ((struct target_ops *));
39
40 static void
41 maybe_kill_then_create_inferior PARAMS ((char *, char *, char **));
42
43 static void
44 maybe_kill_then_attach PARAMS ((char *, int));
45
46 static void
47 kill_or_be_killed PARAMS ((int));
48
49 static void
50 default_terminal_info PARAMS ((char *, int));
51
52 static int
53 nosymbol PARAMS ((char *, CORE_ADDR *));
54
55 static void
56 tcomplain PARAMS ((void));
57
58 static int
59 nomemory PARAMS ((CORE_ADDR, char *, int, int));
60
61 static int
62 return_zero PARAMS ((void));
63
64 static void
65 ignore PARAMS ((void));
66
67 static void
68 target_command PARAMS ((char *, int));
69
70 static struct target_ops *
71 find_default_run_target PARAMS ((char *));
72
73 /* Pointer to array of target architecture structures; the size of the
74    array; the current index into the array; the allocated size of the 
75    array.  */
76 struct target_ops **target_structs;
77 unsigned target_struct_size;
78 unsigned target_struct_index;
79 unsigned target_struct_allocsize;
80 #define DEFAULT_ALLOCSIZE       10
81
82 /* The initial current target, so that there is always a semi-valid
83    current target.  */
84
85 struct target_ops dummy_target = {"None", "None", "",
86     0, 0,               /* open, close */
87     find_default_attach, 0,  /* attach, detach */
88     0, 0,               /* resume, wait */
89     0, 0, 0,            /* registers */
90     0, 0,               /* memory */
91     0, 0,               /* bkpts */
92     0, 0, 0, 0, 0,      /* terminal */
93     0, 0,               /* kill, load */
94     0,                  /* lookup_symbol */
95     find_default_create_inferior, /* create_inferior */
96     0,                  /* mourn_inferior */
97     0,                  /* can_run */
98     0,                  /* notice_signals */
99     dummy_stratum, 0,   /* stratum, next */
100     0, 0, 0, 0, 0,      /* all mem, mem, stack, regs, exec */
101     0, 0,               /* section pointers */
102     OPS_MAGIC,
103 };
104
105 /* The target structure we are currently using to talk to a process
106    or file or whatever "inferior" we have.  */
107
108 struct target_ops *current_target;
109
110 /* The stack of target structures that have been pushed.  */
111
112 struct target_ops **current_target_stack;
113
114 /* Command list for target.  */
115
116 static struct cmd_list_element *targetlist = NULL;
117
118 /* The user just typed 'target' without the name of a target.  */
119
120 /* ARGSUSED */
121 static void
122 target_command (arg, from_tty)
123      char *arg;
124      int from_tty;
125 {
126   fputs_filtered ("Argument required (target name).  Try `help target'\n",
127                   stdout);
128 }
129
130 /* Add a possible target architecture to the list.  */
131
132 void
133 add_target (t)
134      struct target_ops *t;
135 {
136   if (t->to_magic != OPS_MAGIC)
137     {
138       fprintf(stderr, "Magic number of %s target struct wrong\n", 
139         t->to_shortname);
140       abort();
141     }
142
143   if (!target_structs)
144     {
145       target_struct_allocsize = DEFAULT_ALLOCSIZE;
146       target_structs = (struct target_ops **) xmalloc
147         (target_struct_allocsize * sizeof (*target_structs));
148     }
149   if (target_struct_size >= target_struct_allocsize)
150     {
151       target_struct_allocsize *= 2;
152       target_structs = (struct target_ops **)
153           xrealloc ((char *) target_structs, 
154                     target_struct_allocsize * sizeof (*target_structs));
155     }
156   target_structs[target_struct_size++] = t;
157   cleanup_target (t);
158
159   if (targetlist == NULL)
160     add_prefix_cmd ("target", class_run, target_command,
161                     "Connect to a target machine or process.\n\
162 The first argument is the type or protocol of the target machine.\n\
163 Remaining arguments are interpreted by the target protocol.  For more\n\
164 information on the arguments for a particular protocol, type\n\
165 `help target ' followed by the protocol name.",
166                     &targetlist, "target ", 0, &cmdlist);
167   add_cmd (t->to_shortname, no_class, t->to_open, t->to_doc, &targetlist);
168 }
169
170 /* Stub functions */
171
172 static void
173 ignore ()
174 {
175 }
176
177 /* ARGSUSED */
178 static int
179 nomemory (memaddr, myaddr, len, write)
180      CORE_ADDR memaddr;
181      char *myaddr;
182      int len;
183      int write;
184 {
185   errno = EIO;          /* Can't read/write this location */
186   return 0;             /* No bytes handled */
187 }
188
189 static void
190 tcomplain ()
191 {
192   error ("You can't do that when your target is `%s'",
193          current_target->to_shortname);
194 }
195
196 void
197 noprocess ()
198 {
199   error ("You can't do that without a process to debug");
200 }
201
202 /* ARGSUSED */
203 static int
204 nosymbol (name, addrp)
205      char *name;
206      CORE_ADDR *addrp;
207 {
208   return 1;             /* Symbol does not exist in target env */
209 }
210
211 /* ARGSUSED */
212 static void
213 default_terminal_info (args, from_tty)
214      char *args;
215      int from_tty;
216 {
217   printf("No saved terminal information.\n");
218 }
219
220 #if 0
221 /* With strata, this function is no longer needed.  FIXME.  */
222 /* This is the default target_create_inferior function.  It looks up
223    the stack for some target that cares to create inferiors, then
224    calls it -- or complains if not found.  */
225
226 static void
227 upstack_create_inferior (exec, args, env)
228      char *exec;
229      char *args;
230      char **env;
231 {
232   struct target_ops *t;
233
234   for (t = current_target;
235        t;
236        t = t->to_next)
237     {
238       if (t->to_create_inferior != upstack_create_inferior)
239         {
240           t->to_create_inferior (exec, args, env);
241           return;
242         }
243
244     }
245   tcomplain();
246 }
247 #endif
248
249 /* This is the default target_create_inferior and target_attach function.
250    If the current target is executing, it asks whether to kill it off.
251    If this function returns without calling error(), it has killed off
252    the target, and the operation should be attempted.  */
253
254 static void
255 kill_or_be_killed (from_tty)
256      int from_tty;
257 {
258   if (target_has_execution)
259     {
260       printf ("You are already running a program:\n");
261       target_files_info ();
262       if (query ("Kill it? ")) {
263         target_kill ();
264         if (target_has_execution)
265           error ("Killing the program did not help.");
266         return;
267       } else {
268         error ("Program not killed.");
269       }
270     }
271   tcomplain();
272 }
273
274 static void
275 maybe_kill_then_attach (args, from_tty)
276      char *args;
277      int from_tty;
278 {
279   kill_or_be_killed (from_tty);
280   target_attach (args, from_tty);
281 }
282
283 static void
284 maybe_kill_then_create_inferior (exec, args, env)
285      char *exec;
286      char *args;
287      char **env;
288 {
289   kill_or_be_killed (0);
290   target_create_inferior (exec, args, env);
291 }
292
293 /* Clean up a target struct so it no longer has any zero pointers in it.
294    We default entries, at least to stubs that print error messages.  */
295
296 static void
297 cleanup_target (t)
298      struct target_ops *t;
299 {
300
301   /* Check magic number.  If wrong, it probably means someone changed
302      the struct definition, but not all the places that initialize one.  */
303   if (t->to_magic != OPS_MAGIC)
304     {
305       fprintf(stderr, "Magic number of %s target struct wrong\n", 
306         t->to_shortname);
307       abort();
308     }
309
310 #define de_fault(field, value) \
311   if (!t->field)        t->field = value
312
313   /*        FIELD                       DEFAULT VALUE        */
314
315   de_fault (to_open,                    (void (*)())tcomplain);
316   de_fault (to_close,                   (void (*)())ignore);
317   de_fault (to_attach,                  maybe_kill_then_attach);
318   de_fault (to_detach,                  (void (*)())ignore);
319   de_fault (to_resume,                  (void (*)())noprocess);
320   de_fault (to_wait,                    (int (*)())noprocess);
321   de_fault (to_fetch_registers,         (void (*)())ignore);
322   de_fault (to_store_registers,         (void (*)())noprocess);
323   de_fault (to_prepare_to_store,        (void (*)())noprocess);
324   de_fault (to_xfer_memory,             (int (*)())nomemory);
325   de_fault (to_files_info,              (void (*)())ignore);
326   de_fault (to_insert_breakpoint,       memory_insert_breakpoint);
327   de_fault (to_remove_breakpoint,       memory_remove_breakpoint);
328   de_fault (to_terminal_init,           ignore);
329   de_fault (to_terminal_inferior,       ignore);
330   de_fault (to_terminal_ours_for_output,ignore);
331   de_fault (to_terminal_ours,           ignore);
332   de_fault (to_terminal_info,           default_terminal_info);
333   de_fault (to_kill,                    (void (*)())noprocess);
334   de_fault (to_load,                    (void (*)())tcomplain);
335   de_fault (to_lookup_symbol,           nosymbol);
336   de_fault (to_create_inferior,         maybe_kill_then_create_inferior);
337   de_fault (to_mourn_inferior,          (void (*)())noprocess);
338   de_fault (to_can_run,                 return_zero);
339   de_fault (to_notice_signals,          (void (*)())ignore);
340   de_fault (to_next,                    0);
341   de_fault (to_has_all_memory,          0);
342   de_fault (to_has_memory,              0);
343   de_fault (to_has_stack,               0);
344   de_fault (to_has_registers,           0);
345   de_fault (to_has_execution,           0);
346
347 #undef de_fault
348 }
349
350 /* Push a new target type into the stack of the existing target accessors,
351    possibly superseding some of the existing accessors.
352
353    Result is zero if the pushed target ended up on top of the stack,
354    nonzero if at least one target is on top of it.
355
356    Rather than allow an empty stack, we always have the dummy target at
357    the bottom stratum, so we can call the function vectors without
358    checking them.  */
359
360 int
361 push_target (t)
362      struct target_ops *t;
363 {
364   struct target_ops *st, *prev;
365
366   for (prev = 0, st = current_target;
367        st;
368        prev = st, st = st->to_next) {
369     if ((int)(t->to_stratum) >= (int)(st->to_stratum))
370       break;
371   }
372
373   while (t->to_stratum == st->to_stratum) {
374     /* There's already something on this stratum.  Close it off.  */
375     (st->to_close) (0);
376     if (prev)
377       prev->to_next = st->to_next;      /* Unchain old target_ops */
378     else
379       current_target = st->to_next;     /* Unchain first on list */
380     st = st->to_next;
381   }
382
383   /* We have removed all targets in our stratum, now add ourself.  */
384   t->to_next = st;
385   if (prev)
386     prev->to_next = t;
387   else
388     current_target = t;
389
390   cleanup_target (current_target);
391   return prev != 0;
392 }
393
394 /* Remove a target_ops vector from the stack, wherever it may be. 
395    Return how many times it was removed (0 or 1 unless bug).  */
396
397 int
398 unpush_target (t)
399      struct target_ops *t;
400 {
401   struct target_ops *u, *v;
402   int result = 0;
403
404   for (u = current_target, v = 0;
405        u;
406        v = u, u = u->to_next)
407     if (u == t)
408       {
409         if (v == 0)
410           pop_target();                 /* unchain top copy */
411         else {
412           (t->to_close)(0);             /* Let it clean up */
413           v->to_next = t->to_next;      /* unchain middle copy */
414         }
415         result++;
416       }
417   return result;
418 }
419
420 void
421 pop_target ()
422 {
423   (current_target->to_close)(0);        /* Let it clean up */
424   current_target = current_target->to_next;
425 #if 0
426   /* This will dump core if ever called--push_target expects current_target
427      to be non-NULL.  But I don't think it's needed; I don't see how the
428      dummy_target could ever be removed from the stack.  */
429   if (!current_target)          /* At bottom, push dummy.  */
430     push_target (&dummy_target);
431 #endif
432 }
433
434 #undef  MIN
435 #define MIN(A, B) (((A) <= (B)) ? (A) : (B))
436
437 /* target_read_string -- read a null terminated string from MEMADDR in target.
438    The read may also be terminated early by getting an error from target_xfer_
439    memory.
440    LEN is the size of the buffer pointed to by MYADDR.  Note that a terminating
441    null will only be written if there is sufficient room.  The return value is
442    is the number of bytes (including the null) actually transferred.
443 */
444
445 int
446 target_read_string (memaddr, myaddr, len)
447      CORE_ADDR memaddr;
448      char *myaddr;
449      int len;
450 {
451   int tlen, origlen, offset, i;
452   char buf[4];
453
454   origlen = len;
455
456   while (len > 0)
457     {
458       tlen = MIN (len, 4 - (memaddr & 3));
459       offset = memaddr & 3;
460
461       if (target_xfer_memory (memaddr & ~3, buf, 4, 0))
462         return origlen - len;
463
464       for (i = 0; i < tlen; i++)
465         {
466           *myaddr++ = buf[i + offset];
467           if (buf[i + offset] == '\000')
468             return (origlen - len) + i + 1;
469         }
470
471       memaddr += tlen;
472       len -= tlen;
473     }
474   return origlen;
475 }
476
477 /* Read LEN bytes of target memory at address MEMADDR, placing the results in
478    GDB's memory at MYADDR.  Returns either 0 for success or an errno value
479    if any error occurs.
480
481    If an error occurs, no guarantee is made about the contents of the data at
482    MYADDR.  In particular, the caller should not depend upon partial reads
483    filling the buffer with good data.  There is no way for the caller to know
484    how much good data might have been transfered anyway.  Callers that can
485    deal with partial reads should call target_read_memory_partial. */
486
487 int
488 target_read_memory (memaddr, myaddr, len)
489      CORE_ADDR memaddr;
490      char *myaddr;
491      int len;
492 {
493   return target_xfer_memory (memaddr, myaddr, len, 0);
494 }
495
496 /* Read LEN bytes of target memory at address MEMADDR, placing the results
497    in GDB's memory at MYADDR.  Returns a count of the bytes actually read,
498    and optionally an errno value in the location pointed to by ERRNOPTR
499    if ERRNOPTR is non-null. */
500
501 int
502 target_read_memory_partial (memaddr, myaddr, len, errnoptr)
503      CORE_ADDR memaddr;
504      char *myaddr;
505      int len;
506      int *errnoptr;
507 {
508   int nread;    /* Number of bytes actually read. */
509   int errcode;  /* Error from last read. */
510
511   /* First try a complete read. */
512   errcode = target_xfer_memory (memaddr, myaddr, len, 0);
513   if (errcode == 0)
514     {
515       /* Got it all. */
516       nread = len;
517     }
518   else
519     {
520       /* Loop, reading one byte at a time until we get as much as we can. */
521       for (errcode = 0, nread = 0; len > 0 && errcode == 0; nread++, len--)
522         {
523           errcode = target_xfer_memory (memaddr++, myaddr++, 1, 0);
524         }
525       /* If an error, the last read was unsuccessful, so adjust count. */
526       if (errcode != 0)
527         {
528           nread--;
529         }
530     }
531   if (errnoptr != NULL)
532     {
533       *errnoptr = errcode;
534     }
535   return (nread);
536 }
537
538 int
539 target_write_memory (memaddr, myaddr, len)
540      CORE_ADDR memaddr;
541      char *myaddr;
542      int len;
543 {
544   return target_xfer_memory (memaddr, myaddr, len, 1);
545 }
546  
547 /* Move memory to or from the targets.  Iterate until all of it has
548    been moved, if necessary.  The top target gets priority; anything
549    it doesn't want, is offered to the next one down, etc.  Note the
550    business with curlen:  if an early target says "no, but I have a
551    boundary overlapping this xfer" then we shorten what we offer to
552    the subsequent targets so the early guy will get a chance at the
553    tail before the subsequent ones do. 
554
555    Result is 0 or errno value.  */
556
557 int
558 target_xfer_memory (memaddr, myaddr, len, write)
559      CORE_ADDR memaddr;
560      char *myaddr;
561      int len;
562      int write;
563 {
564   int curlen;
565   int res;
566   struct target_ops *t;
567
568   /* to_xfer_memory is not guaranteed to set errno, even when it returns
569      0.  */
570   errno = 0;
571
572   /* The quick case is that the top target does it all.  */
573   res = current_target->to_xfer_memory
574                         (memaddr, myaddr, len, write, current_target);
575   if (res == len)
576     return 0;
577
578   if (res > 0)
579     goto bump;
580   /* If res <= 0 then we call it again in the loop.  Ah well.  */
581
582   for (; len > 0;)
583     {
584       curlen = len;             /* Want to do it all */
585       for (t = current_target;
586            t;
587            t = t->to_has_all_memory? 0: t->to_next)
588         {
589           res = t->to_xfer_memory(memaddr, myaddr, curlen, write, t);
590           if (res > 0) break;   /* Handled all or part of xfer */
591           if (res == 0) continue;       /* Handled none */
592           curlen = -res;        /* Could handle once we get past res bytes */
593         }
594       if (res <= 0)
595         {
596           /* If this address is for nonexistent memory,
597              read zeros if reading, or do nothing if writing.  Return error. */
598           if (!write)
599             memset (myaddr, 0, len);
600           if (errno == 0)
601             return EIO;
602           else
603             return errno;
604         }
605 bump:
606       memaddr += res;
607       myaddr  += res;
608       len     -= res;
609     }
610   return 0;                     /* We managed to cover it all somehow. */
611 }
612
613
614 /* ARGSUSED */
615 static void
616 target_info (args, from_tty)
617      char *args;
618      int from_tty;
619 {
620   struct target_ops *t;
621   int has_all_mem = 0;
622   
623   if (symfile_objfile != NULL)
624     printf ("Symbols from \"%s\".\n", symfile_objfile->name);
625
626 #ifdef FILES_INFO_HOOK
627   if (FILES_INFO_HOOK ())
628     return;
629 #endif
630
631   for (t = current_target;
632        t;
633        t = t->to_next)
634     {
635       if ((int)(t->to_stratum) <= (int)dummy_stratum)
636         continue;
637       if (has_all_mem)
638         printf("\tWhile running this, gdb does not access memory from...\n");
639       printf("%s:\n", t->to_longname);
640       (t->to_files_info)(t);
641       has_all_mem = t->to_has_all_memory;
642     }
643 }
644
645 /* This is to be called by the open routine before it does
646    anything.  */
647
648 void
649 target_preopen (from_tty)
650      int from_tty;
651 {
652   dont_repeat();
653
654   if (target_has_execution)
655     {   
656       if (query ("A program is being debugged already.  Kill it? "))
657         target_kill ();
658       else
659         error ("Program not killed.");
660     }
661 }
662
663 /* Detach a target after doing deferred register stores.  */
664
665 void
666 target_detach (args, from_tty)
667      char *args;
668      int from_tty;
669 {
670   /* Handle any optimized stores to the inferior.  */
671 #ifdef DO_DEFERRED_STORES
672   DO_DEFERRED_STORES;
673 #endif
674   (current_target->to_detach) (args, from_tty);
675
676   /* It is correct to do this because the top process can never be as high
677      as process_stratum now.  This is needed at least in the case where
678      we detach a corefile, and thus need to flush the frame cache.  */
679   generic_mourn_inferior ();
680 }
681
682 /* Look through the list of possible targets for a target that can
683    execute a run or attach command without any other data.  This is
684    used to locate the default process stratum.
685
686    Result is always valid (error() is called for errors).  */
687
688 static struct target_ops *
689 find_default_run_target (do_mesg)
690      char *do_mesg;
691 {
692   struct target_ops **t;
693   struct target_ops *runable = NULL;
694   int count;
695
696   count = 0;
697
698   for (t = target_structs; t < target_structs + target_struct_size;
699        ++t)
700     {
701       if (target_can_run(*t))
702         {
703           runable = *t;
704           ++count;
705         }
706     }
707
708   if (count != 1)
709     error ("Don't know how to %s.  Try \"help target\".", do_mesg);
710
711   return runable;
712 }
713
714 void
715 find_default_attach (args, from_tty)
716      char *args;
717      int from_tty;
718 {
719   struct target_ops *t;
720
721   t = find_default_run_target("attach");
722   (t->to_attach) (args, from_tty);
723   return;
724 }
725
726 void
727 find_default_create_inferior (exec_file, allargs, env)
728      char *exec_file;
729      char *allargs;
730      char **env;
731 {
732   struct target_ops *t;
733
734   t = find_default_run_target("run");
735   (t->to_create_inferior) (exec_file, allargs, env);
736   return;
737 }
738
739 static int
740 return_zero ()
741 {
742   return 0;
743 }
744
745 struct target_ops *
746 find_core_target ()
747 {
748   struct target_ops **t;
749   struct target_ops *runable = NULL;
750   int count;
751   
752   count = 0;
753   
754   for (t = target_structs; t < target_structs + target_struct_size;
755        ++t)
756     {
757       if ((*t)->to_stratum == core_stratum)
758         {
759           runable = *t;
760           ++count;
761         }
762     }
763   
764   return(count == 1 ? runable : NULL);
765 }
766   
767 /* Convert a normal process ID to a string.  Returns the string in a static
768    buffer.  */
769
770 char *
771 normal_pid_to_str (pid)
772      int pid;
773 {
774   static char buf[30];
775
776   sprintf (buf, "process %d", pid);
777
778   return buf;
779 }
780
781 static char targ_desc[] = 
782     "Names of targets and files being debugged.\n\
783 Shows the entire stack of targets currently in use (including the exec-file,\n\
784 core-file, and process, if any), as well as the symbol file name.";
785
786 void
787 _initialize_targets ()
788 {
789   current_target = &dummy_target;
790   cleanup_target (current_target);
791
792   add_info ("target", target_info, targ_desc);
793   add_info ("files", target_info, targ_desc);
794 }