9760cab47564bbee72019291161462127b637555
[external/binutils.git] / gdb / utils.c
1 /* General utility routines for GDB, the GNU debugger.
2    Copyright 1986, 89, 90, 91, 92, 95, 96, 1998 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include "defs.h"
22 #include <ctype.h>
23 #include "gdb_string.h"
24 #include "event-top.h"
25
26 #ifdef HAVE_CURSES_H
27 #include <curses.h>
28 #endif
29 #ifdef HAVE_TERM_H
30 #include <term.h>
31 #endif
32
33 /* SunOS's curses.h has a '#define reg register' in it.  Thank you Sun. */
34 #ifdef reg
35 #undef reg
36 #endif
37
38 #include "signals.h"
39 #include "gdbcmd.h"
40 #include "serial.h"
41 #include "bfd.h"
42 #include "target.h"
43 #include "demangle.h"
44 #include "expression.h"
45 #include "language.h"
46 #include "annotate.h"
47
48 #include <readline/readline.h>
49
50 #undef XMALLOC
51 #define XMALLOC(TYPE) ((TYPE*) xmalloc (sizeof (TYPE)))
52
53 /* readline defines this.  */
54 #undef savestring
55
56 void (*error_begin_hook) PARAMS ((void));
57
58 /* Holds the last error message issued by gdb */
59
60 static GDB_FILE *gdb_lasterr;
61
62 /* Prototypes for local functions */
63
64 static void vfprintf_maybe_filtered PARAMS ((GDB_FILE *, const char *,
65                                              va_list, int));
66
67 static void fputs_maybe_filtered PARAMS ((const char *, GDB_FILE *, int));
68
69 #if defined (USE_MMALLOC) && !defined (NO_MMCHECK)
70 static void malloc_botch PARAMS ((void));
71 #endif
72
73 static void
74 prompt_for_continue PARAMS ((void));
75
76 static void
77 set_width_command PARAMS ((char *, int, struct cmd_list_element *));
78
79 static void
80 set_width PARAMS ((void));
81
82 #ifndef GDB_FILE_ISATTY
83 #define GDB_FILE_ISATTY(GDB_FILE_PTR)   (gdb_file_isatty(GDB_FILE_PTR))
84 #endif
85
86 /* Chain of cleanup actions established with make_cleanup,
87    to be executed if an error happens.  */
88
89 static struct cleanup *cleanup_chain;   /* cleaned up after a failed command */
90 static struct cleanup *final_cleanup_chain;     /* cleaned up when gdb exits */
91 static struct cleanup *run_cleanup_chain;       /* cleaned up on each 'run' */
92 static struct cleanup *exec_cleanup_chain;      /* cleaned up on each execution command */
93 /* cleaned up on each error from within an execution command */
94 static struct cleanup *exec_error_cleanup_chain; 
95
96 /* Pointer to what is left to do for an execution command after the
97    target stops. Used only in asynchronous mode, by targets that
98    support async execution.  The finish and until commands use it. So
99    does the target extended-remote command. */
100 struct continuation *cmd_continuation;
101
102 /* Nonzero if we have job control. */
103
104 int job_control;
105
106 /* Nonzero means a quit has been requested.  */
107
108 int quit_flag;
109
110 /* Nonzero means quit immediately if Control-C is typed now, rather
111    than waiting until QUIT is executed.  Be careful in setting this;
112    code which executes with immediate_quit set has to be very careful
113    about being able to deal with being interrupted at any time.  It is
114    almost always better to use QUIT; the only exception I can think of
115    is being able to quit out of a system call (using EINTR loses if
116    the SIGINT happens between the previous QUIT and the system call).
117    To immediately quit in the case in which a SIGINT happens between
118    the previous QUIT and setting immediate_quit (desirable anytime we
119    expect to block), call QUIT after setting immediate_quit.  */
120
121 int immediate_quit;
122
123 /* Nonzero means that encoded C++ names should be printed out in their
124    C++ form rather than raw.  */
125
126 int demangle = 1;
127
128 /* Nonzero means that encoded C++ names should be printed out in their
129    C++ form even in assembler language displays.  If this is set, but
130    DEMANGLE is zero, names are printed raw, i.e. DEMANGLE controls.  */
131
132 int asm_demangle = 0;
133
134 /* Nonzero means that strings with character values >0x7F should be printed
135    as octal escapes.  Zero means just print the value (e.g. it's an
136    international character, and the terminal or window can cope.)  */
137
138 int sevenbit_strings = 0;
139
140 /* String to be printed before error messages, if any.  */
141
142 char *error_pre_print;
143
144 /* String to be printed before quit messages, if any.  */
145
146 char *quit_pre_print;
147
148 /* String to be printed before warning messages, if any.  */
149
150 char *warning_pre_print = "\nwarning: ";
151
152 int pagination_enabled = 1;
153 \f
154
155 /* Add a new cleanup to the cleanup_chain,
156    and return the previous chain pointer
157    to be passed later to do_cleanups or discard_cleanups.
158    Args are FUNCTION to clean up with, and ARG to pass to it.  */
159
160 struct cleanup *
161 make_cleanup (function, arg)
162      void (*function) PARAMS ((PTR));
163      PTR arg;
164 {
165   return make_my_cleanup (&cleanup_chain, function, arg);
166 }
167
168 struct cleanup *
169 make_final_cleanup (function, arg)
170      void (*function) PARAMS ((PTR));
171      PTR arg;
172 {
173   return make_my_cleanup (&final_cleanup_chain, function, arg);
174 }
175
176 struct cleanup *
177 make_run_cleanup (function, arg)
178      void (*function) PARAMS ((PTR));
179      PTR arg;
180 {
181   return make_my_cleanup (&run_cleanup_chain, function, arg);
182 }
183
184 struct cleanup *
185 make_exec_cleanup (function, arg)
186      void (*function) PARAMS ((PTR));
187      PTR arg;
188 {
189   return make_my_cleanup (&exec_cleanup_chain, function, arg);
190 }
191
192 struct cleanup *
193 make_exec_error_cleanup (function, arg)
194      void (*function) PARAMS ((PTR));
195      PTR arg;
196 {
197   return make_my_cleanup (&exec_error_cleanup_chain, function, arg);
198 }
199
200 static void
201 do_freeargv (arg)
202      void *arg;
203 {
204   freeargv ((char **) arg);
205 }
206
207 struct cleanup *
208 make_cleanup_freeargv (arg)
209      char **arg;
210 {
211   return make_my_cleanup (&cleanup_chain, do_freeargv, arg);
212 }
213
214 static void
215 do_gdb_file_delete (void *arg)
216 {
217   gdb_file_delete (arg);
218 }
219
220 struct cleanup *
221 make_cleanup_gdb_file_delete (struct gdb_file *arg)
222 {
223   return make_my_cleanup (&cleanup_chain, do_gdb_file_delete, arg);
224 }
225
226 struct cleanup *
227 make_my_cleanup (pmy_chain, function, arg)
228      struct cleanup **pmy_chain;
229      void (*function) PARAMS ((PTR));
230      PTR arg;
231 {
232   register struct cleanup *new
233   = (struct cleanup *) xmalloc (sizeof (struct cleanup));
234   register struct cleanup *old_chain = *pmy_chain;
235
236   new->next = *pmy_chain;
237   new->function = function;
238   new->arg = arg;
239   *pmy_chain = new;
240
241   return old_chain;
242 }
243
244 /* Discard cleanups and do the actions they describe
245    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
246
247 void
248 do_cleanups (old_chain)
249      register struct cleanup *old_chain;
250 {
251   do_my_cleanups (&cleanup_chain, old_chain);
252 }
253
254 void
255 do_final_cleanups (old_chain)
256      register struct cleanup *old_chain;
257 {
258   do_my_cleanups (&final_cleanup_chain, old_chain);
259 }
260
261 void
262 do_run_cleanups (old_chain)
263      register struct cleanup *old_chain;
264 {
265   do_my_cleanups (&run_cleanup_chain, old_chain);
266 }
267
268 void
269 do_exec_cleanups (old_chain)
270      register struct cleanup *old_chain;
271 {
272   do_my_cleanups (&exec_cleanup_chain, old_chain);
273 }
274
275 void
276 do_exec_error_cleanups (old_chain)
277      register struct cleanup *old_chain;
278 {
279   do_my_cleanups (&exec_error_cleanup_chain, old_chain);
280 }
281
282 void
283 do_my_cleanups (pmy_chain, old_chain)
284      register struct cleanup **pmy_chain;
285      register struct cleanup *old_chain;
286 {
287   register struct cleanup *ptr;
288   while ((ptr = *pmy_chain) != old_chain)
289     {
290       *pmy_chain = ptr->next;   /* Do this first incase recursion */
291       (*ptr->function) (ptr->arg);
292       free (ptr);
293     }
294 }
295
296 /* Discard cleanups, not doing the actions they describe,
297    until we get back to the point OLD_CHAIN in the cleanup_chain.  */
298
299 void
300 discard_cleanups (old_chain)
301      register struct cleanup *old_chain;
302 {
303   discard_my_cleanups (&cleanup_chain, old_chain);
304 }
305
306 void
307 discard_final_cleanups (old_chain)
308      register struct cleanup *old_chain;
309 {
310   discard_my_cleanups (&final_cleanup_chain, old_chain);
311 }
312
313 void
314 discard_exec_error_cleanups (old_chain)
315      register struct cleanup *old_chain;
316 {
317   discard_my_cleanups (&exec_error_cleanup_chain, old_chain);
318 }
319
320 void
321 discard_my_cleanups (pmy_chain, old_chain)
322      register struct cleanup **pmy_chain;
323      register struct cleanup *old_chain;
324 {
325   register struct cleanup *ptr;
326   while ((ptr = *pmy_chain) != old_chain)
327     {
328       *pmy_chain = ptr->next;
329       free ((PTR) ptr);
330     }
331 }
332
333 /* Set the cleanup_chain to 0, and return the old cleanup chain.  */
334 struct cleanup *
335 save_cleanups ()
336 {
337   return save_my_cleanups (&cleanup_chain);
338 }
339
340 struct cleanup *
341 save_final_cleanups ()
342 {
343   return save_my_cleanups (&final_cleanup_chain);
344 }
345
346 struct cleanup *
347 save_my_cleanups (pmy_chain)
348      struct cleanup **pmy_chain;
349 {
350   struct cleanup *old_chain = *pmy_chain;
351
352   *pmy_chain = 0;
353   return old_chain;
354 }
355
356 /* Restore the cleanup chain from a previously saved chain.  */
357 void
358 restore_cleanups (chain)
359      struct cleanup *chain;
360 {
361   restore_my_cleanups (&cleanup_chain, chain);
362 }
363
364 void
365 restore_final_cleanups (chain)
366      struct cleanup *chain;
367 {
368   restore_my_cleanups (&final_cleanup_chain, chain);
369 }
370
371 void
372 restore_my_cleanups (pmy_chain, chain)
373      struct cleanup **pmy_chain;
374      struct cleanup *chain;
375 {
376   *pmy_chain = chain;
377 }
378
379 /* This function is useful for cleanups.
380    Do
381
382    foo = xmalloc (...);
383    old_chain = make_cleanup (free_current_contents, &foo);
384
385    to arrange to free the object thus allocated.  */
386
387 void
388 free_current_contents (location)
389      char **location;
390 {
391   free (*location);
392 }
393
394 /* Provide a known function that does nothing, to use as a base for
395    for a possibly long chain of cleanups.  This is useful where we
396    use the cleanup chain for handling normal cleanups as well as dealing
397    with cleanups that need to be done as a result of a call to error().
398    In such cases, we may not be certain where the first cleanup is, unless
399    we have a do-nothing one to always use as the base. */
400
401 /* ARGSUSED */
402 void
403 null_cleanup (arg)
404      PTR arg;
405 {
406 }
407
408 /* Add a continuation to the continuation list, the gloabl list
409    cmd_continuation. */
410 void
411 add_continuation (continuation_hook, arg_list)
412      void (*continuation_hook) PARAMS ((struct continuation_arg *));
413      struct continuation_arg *arg_list;
414 {
415   struct continuation *continuation_ptr;
416
417   continuation_ptr = (struct continuation *) xmalloc (sizeof (struct continuation));
418   continuation_ptr->continuation_hook = continuation_hook;
419   continuation_ptr->arg_list = arg_list;
420   continuation_ptr->next = cmd_continuation;
421   cmd_continuation = continuation_ptr;
422 }
423
424 /* Walk down the cmd_continuation list, and execute all the
425    continuations. */
426 void
427 do_all_continuations ()
428 {
429   struct continuation *continuation_ptr;
430
431   while (cmd_continuation)
432     {
433       (cmd_continuation->continuation_hook) (cmd_continuation->arg_list);
434       continuation_ptr = cmd_continuation;
435       cmd_continuation = continuation_ptr->next;
436       free (continuation_ptr);
437     }
438 }
439
440 /* Walk down the cmd_continuation list, and get rid of all the
441    continuations. */
442 void
443 discard_all_continuations ()
444 {
445   struct continuation *continuation_ptr;
446
447   while (cmd_continuation)
448     {
449       continuation_ptr = cmd_continuation;
450       cmd_continuation = continuation_ptr->next;
451       free (continuation_ptr);
452     }
453 }
454
455 \f
456
457 /* Print a warning message.  Way to use this is to call warning_begin,
458    output the warning message (use unfiltered output to gdb_stderr),
459    ending in a newline.  There is not currently a warning_end that you
460    call afterwards, but such a thing might be added if it is useful
461    for a GUI to separate warning messages from other output.
462
463    FIXME: Why do warnings use unfiltered output and errors filtered?
464    Is this anything other than a historical accident?  */
465
466 void
467 warning_begin ()
468 {
469   target_terminal_ours ();
470   wrap_here ("");               /* Force out any buffered output */
471   gdb_flush (gdb_stdout);
472   if (warning_pre_print)
473     fprintf_unfiltered (gdb_stderr, warning_pre_print);
474 }
475
476 /* Print a warning message.
477    The first argument STRING is the warning message, used as a fprintf string,
478    and the remaining args are passed as arguments to it.
479    The primary difference between warnings and errors is that a warning
480    does not force the return to command level.  */
481
482 void
483 warning (const char *string,...)
484 {
485   va_list args;
486   va_start (args, string);
487   if (warning_hook)
488     (*warning_hook) (string, args);
489   else
490     {
491       warning_begin ();
492       vfprintf_unfiltered (gdb_stderr, string, args);
493       fprintf_unfiltered (gdb_stderr, "\n");
494       va_end (args);
495     }
496 }
497
498 /* Start the printing of an error message.  Way to use this is to call
499    this, output the error message (use filtered output to gdb_stderr
500    (FIXME: Some callers, like memory_error, use gdb_stdout)), ending
501    in a newline, and then call return_to_top_level (RETURN_ERROR).
502    error() provides a convenient way to do this for the special case
503    that the error message can be formatted with a single printf call,
504    but this is more general.  */
505 void
506 error_begin ()
507 {
508   if (error_begin_hook)
509     error_begin_hook ();
510
511   target_terminal_ours ();
512   wrap_here ("");               /* Force out any buffered output */
513   gdb_flush (gdb_stdout);
514
515   annotate_error_begin ();
516
517   if (error_pre_print)
518     fprintf_filtered (gdb_stderr, error_pre_print);
519 }
520
521 /* Print an error message and return to command level.
522    The first argument STRING is the error message, used as a fprintf string,
523    and the remaining args are passed as arguments to it.  */
524
525 NORETURN void
526 verror (const char *string, va_list args)
527 {
528   /* FIXME: cagney/1999-11-10: All error calls should come here.
529      Unfortunatly some code uses the sequence: error_begin(); print
530      error message; return_to_top_level.  That code should be
531      flushed. */
532   error_begin ();
533   vfprintf_filtered (gdb_stderr, string, args);
534   fprintf_filtered (gdb_stderr, "\n");
535   /* Save it as the last error as well (no newline) */
536   gdb_file_rewind (gdb_lasterr);
537   vfprintf_filtered (gdb_lasterr, string, args);
538   va_end (args);
539   return_to_top_level (RETURN_ERROR);
540 }
541
542 NORETURN void
543 error (const char *string,...)
544 {
545   va_list args;
546   va_start (args, string);
547   verror (string, args);
548   va_end (args);
549 }
550
551 NORETURN void
552 error_stream (GDB_FILE *stream)
553 {
554   long size;
555   char *msg = gdb_file_xstrdup (stream, &size);
556   make_cleanup (free, msg);
557   error ("%s", msg);
558 }
559
560 /* Get the last error message issued by gdb */
561
562 char *
563 error_last_message (void)
564 {
565   long len;
566   return gdb_file_xstrdup (gdb_lasterr, &len);
567 }
568   
569 /* This is to be called by main() at the very beginning */
570
571 void
572 error_init (void)
573 {
574   gdb_lasterr = mem_fileopen ();
575 }
576
577 /* Print a message reporting an internal error. Ask the user if they
578    want to continue, dump core, or just exit. */
579
580 NORETURN void
581 internal_verror (const char *fmt, va_list ap)
582 {
583   static char msg[] = "Internal GDB error: recursive internal error.\n";
584   static int dejavu = 0;
585   int continue_p;
586   int dump_core_p;
587
588   /* don't allow infinite error recursion. */
589   switch (dejavu)
590     {
591     case 0:
592       dejavu = 1;
593       break;
594     case 1:
595       dejavu = 2;
596       fputs_unfiltered (msg, gdb_stderr);
597       abort ();
598     default:
599       dejavu = 3;
600       write (STDERR_FILENO, msg, sizeof (msg));
601       exit (1);
602     }
603
604   /* Try to get the message out */
605   fputs_unfiltered ("gdb-internal-error: ", gdb_stderr);
606   vfprintf_unfiltered (gdb_stderr, fmt, ap);
607   fputs_unfiltered ("\n", gdb_stderr);
608
609   /* Default (no case) is to quit GDB.  When in batch mode this
610      lessens the likelhood of GDB going into an infinate loop. */
611   continue_p = query ("\
612 An internal GDB error was detected.  This may make make further\n\
613 debugging unreliable.  Continue this debugging session? ");
614
615   /* Default (no case) is to not dump core.  Lessen the chance of GDB
616      leaving random core files around. */
617   dump_core_p = query ("\
618 Create a core file containing the current state of GDB? ");
619
620   if (continue_p)
621     {
622       if (dump_core_p)
623         {
624           if (fork () == 0)
625             abort ();
626         }
627     }
628   else
629     {
630       if (dump_core_p)
631         abort ();
632       else
633         exit (1);
634     }
635
636   dejavu = 0;
637   return_to_top_level (RETURN_ERROR);
638 }
639
640 NORETURN void
641 internal_error (char *string, ...)
642 {
643   va_list ap;
644   va_start (ap, string);
645   internal_verror (string, ap);
646   va_end (ap);
647 }
648
649 /* The strerror() function can return NULL for errno values that are
650    out of range.  Provide a "safe" version that always returns a
651    printable string. */
652
653 char *
654 safe_strerror (errnum)
655      int errnum;
656 {
657   char *msg;
658   static char buf[32];
659
660   if ((msg = strerror (errnum)) == NULL)
661     {
662       sprintf (buf, "(undocumented errno %d)", errnum);
663       msg = buf;
664     }
665   return (msg);
666 }
667
668 /* The strsignal() function can return NULL for signal values that are
669    out of range.  Provide a "safe" version that always returns a
670    printable string. */
671
672 char *
673 safe_strsignal (signo)
674      int signo;
675 {
676   char *msg;
677   static char buf[32];
678
679   if ((msg = strsignal (signo)) == NULL)
680     {
681       sprintf (buf, "(undocumented signal %d)", signo);
682       msg = buf;
683     }
684   return (msg);
685 }
686
687
688 /* Print the system error message for errno, and also mention STRING
689    as the file name for which the error was encountered.
690    Then return to command level.  */
691
692 NORETURN void
693 perror_with_name (string)
694      char *string;
695 {
696   char *err;
697   char *combined;
698
699   err = safe_strerror (errno);
700   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
701   strcpy (combined, string);
702   strcat (combined, ": ");
703   strcat (combined, err);
704
705   /* I understand setting these is a matter of taste.  Still, some people
706      may clear errno but not know about bfd_error.  Doing this here is not
707      unreasonable. */
708   bfd_set_error (bfd_error_no_error);
709   errno = 0;
710
711   error ("%s.", combined);
712 }
713
714 /* Print the system error message for ERRCODE, and also mention STRING
715    as the file name for which the error was encountered.  */
716
717 void
718 print_sys_errmsg (string, errcode)
719      char *string;
720      int errcode;
721 {
722   char *err;
723   char *combined;
724
725   err = safe_strerror (errcode);
726   combined = (char *) alloca (strlen (err) + strlen (string) + 3);
727   strcpy (combined, string);
728   strcat (combined, ": ");
729   strcat (combined, err);
730
731   /* We want anything which was printed on stdout to come out first, before
732      this message.  */
733   gdb_flush (gdb_stdout);
734   fprintf_unfiltered (gdb_stderr, "%s.\n", combined);
735 }
736
737 /* Control C eventually causes this to be called, at a convenient time.  */
738
739 void
740 quit ()
741 {
742   serial_t gdb_stdout_serial = serial_fdopen (1);
743
744   target_terminal_ours ();
745
746   /* We want all output to appear now, before we print "Quit".  We
747      have 3 levels of buffering we have to flush (it's possible that
748      some of these should be changed to flush the lower-level ones
749      too):  */
750
751   /* 1.  The _filtered buffer.  */
752   wrap_here ((char *) 0);
753
754   /* 2.  The stdio buffer.  */
755   gdb_flush (gdb_stdout);
756   gdb_flush (gdb_stderr);
757
758   /* 3.  The system-level buffer.  */
759   SERIAL_DRAIN_OUTPUT (gdb_stdout_serial);
760   SERIAL_UN_FDOPEN (gdb_stdout_serial);
761
762   annotate_error_begin ();
763
764   /* Don't use *_filtered; we don't want to prompt the user to continue.  */
765   if (quit_pre_print)
766     fprintf_unfiltered (gdb_stderr, quit_pre_print);
767
768 #ifdef __MSDOS__
769   /* No steenking SIGINT will ever be coming our way when the
770      program is resumed.  Don't lie.  */
771   fprintf_unfiltered (gdb_stderr, "Quit\n");
772 #else
773   if (job_control
774   /* If there is no terminal switching for this target, then we can't
775      possibly get screwed by the lack of job control.  */
776       || current_target.to_terminal_ours == NULL)
777     fprintf_unfiltered (gdb_stderr, "Quit\n");
778   else
779     fprintf_unfiltered (gdb_stderr,
780                "Quit (expect signal SIGINT when the program is resumed)\n");
781 #endif
782   return_to_top_level (RETURN_QUIT);
783 }
784
785
786 #if defined(_MSC_VER)           /* should test for wingdb instead? */
787
788 /*
789  * Windows translates all keyboard and mouse events 
790  * into a message which is appended to the message 
791  * queue for the process.
792  */
793
794 void
795 notice_quit ()
796 {
797   int k = win32pollquit ();
798   if (k == 1)
799     quit_flag = 1;
800   else if (k == 2)
801     immediate_quit = 1;
802 }
803
804 #else /* !defined(_MSC_VER) */
805
806 void
807 notice_quit ()
808 {
809   /* Done by signals */
810 }
811
812 #endif /* !defined(_MSC_VER) */
813
814 /* Control C comes here */
815 void
816 request_quit (signo)
817      int signo;
818 {
819   quit_flag = 1;
820   /* Restore the signal handler.  Harmless with BSD-style signals, needed
821      for System V-style signals.  So just always do it, rather than worrying
822      about USG defines and stuff like that.  */
823   signal (signo, request_quit);
824
825 #ifdef REQUEST_QUIT
826   REQUEST_QUIT;
827 #else
828   if (immediate_quit)
829     quit ();
830 #endif
831 }
832 \f
833 /* Memory management stuff (malloc friends).  */
834
835 /* Make a substitute size_t for non-ANSI compilers. */
836
837 #ifndef HAVE_STDDEF_H
838 #ifndef size_t
839 #define size_t unsigned int
840 #endif
841 #endif
842
843 #if !defined (USE_MMALLOC)
844
845 PTR
846 mmalloc (md, size)
847      PTR md;
848      size_t size;
849 {
850   return malloc (size);
851 }
852
853 PTR
854 mrealloc (md, ptr, size)
855      PTR md;
856      PTR ptr;
857      size_t size;
858 {
859   if (ptr == 0)                 /* Guard against old realloc's */
860     return malloc (size);
861   else
862     return realloc (ptr, size);
863 }
864
865 void
866 mfree (md, ptr)
867      PTR md;
868      PTR ptr;
869 {
870   free (ptr);
871 }
872
873 #endif /* USE_MMALLOC */
874
875 #if !defined (USE_MMALLOC) || defined (NO_MMCHECK)
876
877 void
878 init_malloc (md)
879      PTR md;
880 {
881 }
882
883 #else /* Have mmalloc and want corruption checking */
884
885 static void
886 malloc_botch ()
887 {
888   fprintf_unfiltered (gdb_stderr, "Memory corruption\n");
889   abort ();
890 }
891
892 /* Attempt to install hooks in mmalloc/mrealloc/mfree for the heap specified
893    by MD, to detect memory corruption.  Note that MD may be NULL to specify
894    the default heap that grows via sbrk.
895
896    Note that for freshly created regions, we must call mmcheckf prior to any
897    mallocs in the region.  Otherwise, any region which was allocated prior to
898    installing the checking hooks, which is later reallocated or freed, will
899    fail the checks!  The mmcheck function only allows initial hooks to be
900    installed before the first mmalloc.  However, anytime after we have called
901    mmcheck the first time to install the checking hooks, we can call it again
902    to update the function pointer to the memory corruption handler.
903
904    Returns zero on failure, non-zero on success. */
905
906 #ifndef MMCHECK_FORCE
907 #define MMCHECK_FORCE 0
908 #endif
909
910 void
911 init_malloc (md)
912      PTR md;
913 {
914   if (!mmcheckf (md, malloc_botch, MMCHECK_FORCE))
915     {
916       /* Don't use warning(), which relies on current_target being set
917          to something other than dummy_target, until after
918          initialize_all_files(). */
919
920       fprintf_unfiltered
921         (gdb_stderr, "warning: failed to install memory consistency checks; ");
922       fprintf_unfiltered
923         (gdb_stderr, "configuration should define NO_MMCHECK or MMCHECK_FORCE\n");
924     }
925
926   mmtrace ();
927 }
928
929 #endif /* Have mmalloc and want corruption checking  */
930
931 /* Called when a memory allocation fails, with the number of bytes of
932    memory requested in SIZE. */
933
934 NORETURN void
935 nomem (size)
936      long size;
937 {
938   if (size > 0)
939     {
940       internal_error ("virtual memory exhausted: can't allocate %ld bytes.", size);
941     }
942   else
943     {
944       internal_error ("virtual memory exhausted.");
945     }
946 }
947
948 /* Like mmalloc but get error if no storage available, and protect against
949    the caller wanting to allocate zero bytes.  Whether to return NULL for
950    a zero byte request, or translate the request into a request for one
951    byte of zero'd storage, is a religious issue. */
952
953 PTR
954 xmmalloc (md, size)
955      PTR md;
956      long size;
957 {
958   register PTR val;
959
960   if (size == 0)
961     {
962       val = NULL;
963     }
964   else if ((val = mmalloc (md, size)) == NULL)
965     {
966       nomem (size);
967     }
968   return (val);
969 }
970
971 /* Like mrealloc but get error if no storage available.  */
972
973 PTR
974 xmrealloc (md, ptr, size)
975      PTR md;
976      PTR ptr;
977      long size;
978 {
979   register PTR val;
980
981   if (ptr != NULL)
982     {
983       val = mrealloc (md, ptr, size);
984     }
985   else
986     {
987       val = mmalloc (md, size);
988     }
989   if (val == NULL)
990     {
991       nomem (size);
992     }
993   return (val);
994 }
995
996 /* Like malloc but get error if no storage available, and protect against
997    the caller wanting to allocate zero bytes.  */
998
999 PTR
1000 xmalloc (size)
1001      size_t size;
1002 {
1003   return (xmmalloc ((PTR) NULL, size));
1004 }
1005
1006 /* Like mrealloc but get error if no storage available.  */
1007
1008 PTR
1009 xrealloc (ptr, size)
1010      PTR ptr;
1011      size_t size;
1012 {
1013   return (xmrealloc ((PTR) NULL, ptr, size));
1014 }
1015 \f
1016
1017 /* My replacement for the read system call.
1018    Used like `read' but keeps going if `read' returns too soon.  */
1019
1020 int
1021 myread (desc, addr, len)
1022      int desc;
1023      char *addr;
1024      int len;
1025 {
1026   register int val;
1027   int orglen = len;
1028
1029   while (len > 0)
1030     {
1031       val = read (desc, addr, len);
1032       if (val < 0)
1033         return val;
1034       if (val == 0)
1035         return orglen - len;
1036       len -= val;
1037       addr += val;
1038     }
1039   return orglen;
1040 }
1041 \f
1042 /* Make a copy of the string at PTR with SIZE characters
1043    (and add a null character at the end in the copy).
1044    Uses malloc to get the space.  Returns the address of the copy.  */
1045
1046 char *
1047 savestring (ptr, size)
1048      const char *ptr;
1049      int size;
1050 {
1051   register char *p = (char *) xmalloc (size + 1);
1052   memcpy (p, ptr, size);
1053   p[size] = 0;
1054   return p;
1055 }
1056
1057 char *
1058 msavestring (md, ptr, size)
1059      PTR md;
1060      const char *ptr;
1061      int size;
1062 {
1063   register char *p = (char *) xmmalloc (md, size + 1);
1064   memcpy (p, ptr, size);
1065   p[size] = 0;
1066   return p;
1067 }
1068
1069 /* The "const" is so it compiles under DGUX (which prototypes strsave
1070    in <string.h>.  FIXME: This should be named "xstrsave", shouldn't it?
1071    Doesn't real strsave return NULL if out of memory?  */
1072 char *
1073 strsave (ptr)
1074      const char *ptr;
1075 {
1076   return savestring (ptr, strlen (ptr));
1077 }
1078
1079 char *
1080 mstrsave (md, ptr)
1081      PTR md;
1082      const char *ptr;
1083 {
1084   return (msavestring (md, ptr, strlen (ptr)));
1085 }
1086
1087 void
1088 print_spaces (n, file)
1089      register int n;
1090      register GDB_FILE *file;
1091 {
1092   fputs_unfiltered (n_spaces (n), file);
1093 }
1094
1095 /* Print a host address.  */
1096
1097 void
1098 gdb_print_host_address (void *addr, struct gdb_file *stream)
1099 {
1100
1101   /* We could use the %p conversion specifier to fprintf if we had any
1102      way of knowing whether this host supports it.  But the following
1103      should work on the Alpha and on 32 bit machines.  */
1104
1105   fprintf_filtered (stream, "0x%lx", (unsigned long) addr);
1106 }
1107
1108 /* Ask user a y-or-n question and return 1 iff answer is yes.
1109    Takes three args which are given to printf to print the question.
1110    The first, a control string, should end in "? ".
1111    It should not say how to answer, because we do that.  */
1112
1113 /* VARARGS */
1114 int
1115 query (char *ctlstr,...)
1116 {
1117   va_list args;
1118   register int answer;
1119   register int ans2;
1120   int retval;
1121
1122   va_start (args, ctlstr);
1123
1124   if (query_hook)
1125     {
1126       return query_hook (ctlstr, args);
1127     }
1128
1129   /* Automatically answer "yes" if input is not from a terminal.  */
1130   if (!input_from_terminal_p ())
1131     return 1;
1132 #ifdef MPW
1133   /* FIXME Automatically answer "yes" if called from MacGDB.  */
1134   if (mac_app)
1135     return 1;
1136 #endif /* MPW */
1137
1138   while (1)
1139     {
1140       wrap_here ("");           /* Flush any buffered output */
1141       gdb_flush (gdb_stdout);
1142
1143       if (annotation_level > 1)
1144         printf_filtered ("\n\032\032pre-query\n");
1145
1146       vfprintf_filtered (gdb_stdout, ctlstr, args);
1147       printf_filtered ("(y or n) ");
1148
1149       if (annotation_level > 1)
1150         printf_filtered ("\n\032\032query\n");
1151
1152 #ifdef MPW
1153       /* If not in MacGDB, move to a new line so the entered line doesn't
1154          have a prompt on the front of it. */
1155       if (!mac_app)
1156         fputs_unfiltered ("\n", gdb_stdout);
1157 #endif /* MPW */
1158
1159       wrap_here ("");
1160       gdb_flush (gdb_stdout);
1161
1162 #if defined(TUI)
1163       if (!tui_version || cmdWin == tuiWinWithFocus ())
1164 #endif
1165         answer = fgetc (stdin);
1166 #if defined(TUI)
1167       else
1168         answer = (unsigned char) tuiBufferGetc ();
1169
1170 #endif
1171       clearerr (stdin);         /* in case of C-d */
1172       if (answer == EOF)        /* C-d */
1173         {
1174           retval = 1;
1175           break;
1176         }
1177       /* Eat rest of input line, to EOF or newline */
1178       if ((answer != '\n') || (tui_version && answer != '\r'))
1179         do
1180           {
1181 #if defined(TUI)
1182             if (!tui_version || cmdWin == tuiWinWithFocus ())
1183 #endif
1184               ans2 = fgetc (stdin);
1185 #if defined(TUI)
1186             else
1187               ans2 = (unsigned char) tuiBufferGetc ();
1188 #endif
1189             clearerr (stdin);
1190           }
1191         while (ans2 != EOF && ans2 != '\n' && ans2 != '\r');
1192       TUIDO (((TuiOpaqueFuncPtr) tui_vStartNewLines, 1));
1193
1194       if (answer >= 'a')
1195         answer -= 040;
1196       if (answer == 'Y')
1197         {
1198           retval = 1;
1199           break;
1200         }
1201       if (answer == 'N')
1202         {
1203           retval = 0;
1204           break;
1205         }
1206       printf_filtered ("Please answer y or n.\n");
1207     }
1208
1209   if (annotation_level > 1)
1210     printf_filtered ("\n\032\032post-query\n");
1211   return retval;
1212 }
1213 \f
1214
1215 /* Parse a C escape sequence.  STRING_PTR points to a variable
1216    containing a pointer to the string to parse.  That pointer
1217    should point to the character after the \.  That pointer
1218    is updated past the characters we use.  The value of the
1219    escape sequence is returned.
1220
1221    A negative value means the sequence \ newline was seen,
1222    which is supposed to be equivalent to nothing at all.
1223
1224    If \ is followed by a null character, we return a negative
1225    value and leave the string pointer pointing at the null character.
1226
1227    If \ is followed by 000, we return 0 and leave the string pointer
1228    after the zeros.  A value of 0 does not mean end of string.  */
1229
1230 int
1231 parse_escape (string_ptr)
1232      char **string_ptr;
1233 {
1234   register int c = *(*string_ptr)++;
1235   switch (c)
1236     {
1237     case 'a':
1238       return 007;               /* Bell (alert) char */
1239     case 'b':
1240       return '\b';
1241     case 'e':                   /* Escape character */
1242       return 033;
1243     case 'f':
1244       return '\f';
1245     case 'n':
1246       return '\n';
1247     case 'r':
1248       return '\r';
1249     case 't':
1250       return '\t';
1251     case 'v':
1252       return '\v';
1253     case '\n':
1254       return -2;
1255     case 0:
1256       (*string_ptr)--;
1257       return 0;
1258     case '^':
1259       c = *(*string_ptr)++;
1260       if (c == '\\')
1261         c = parse_escape (string_ptr);
1262       if (c == '?')
1263         return 0177;
1264       return (c & 0200) | (c & 037);
1265
1266     case '0':
1267     case '1':
1268     case '2':
1269     case '3':
1270     case '4':
1271     case '5':
1272     case '6':
1273     case '7':
1274       {
1275         register int i = c - '0';
1276         register int count = 0;
1277         while (++count < 3)
1278           {
1279             if ((c = *(*string_ptr)++) >= '0' && c <= '7')
1280               {
1281                 i *= 8;
1282                 i += c - '0';
1283               }
1284             else
1285               {
1286                 (*string_ptr)--;
1287                 break;
1288               }
1289           }
1290         return i;
1291       }
1292     default:
1293       return c;
1294     }
1295 }
1296 \f
1297 /* Print the character C on STREAM as part of the contents of a literal
1298    string whose delimiter is QUOTER.  Note that this routine should only
1299    be call for printing things which are independent of the language
1300    of the program being debugged. */
1301
1302 static void printchar PARAMS ((int c, void (*do_fputs) (const char *, GDB_FILE*), void (*do_fprintf) (GDB_FILE*, const char *, ...), GDB_FILE *stream, int quoter));
1303
1304 static void
1305 printchar (c, do_fputs, do_fprintf, stream, quoter)
1306      int c;
1307      void (*do_fputs) PARAMS ((const char *, GDB_FILE*));
1308      void (*do_fprintf) PARAMS ((GDB_FILE*, const char *, ...));
1309      GDB_FILE *stream;
1310      int quoter;
1311 {
1312
1313   c &= 0xFF;                    /* Avoid sign bit follies */
1314
1315   if (c < 0x20 ||               /* Low control chars */
1316       (c >= 0x7F && c < 0xA0) ||        /* DEL, High controls */
1317       (sevenbit_strings && c >= 0x80))
1318     {                           /* high order bit set */
1319       switch (c)
1320         {
1321         case '\n':
1322           do_fputs ("\\n", stream);
1323           break;
1324         case '\b':
1325           do_fputs ("\\b", stream);
1326           break;
1327         case '\t':
1328           do_fputs ("\\t", stream);
1329           break;
1330         case '\f':
1331           do_fputs ("\\f", stream);
1332           break;
1333         case '\r':
1334           do_fputs ("\\r", stream);
1335           break;
1336         case '\033':
1337           do_fputs ("\\e", stream);
1338           break;
1339         case '\007':
1340           do_fputs ("\\a", stream);
1341           break;
1342         default:
1343           do_fprintf (stream, "\\%.3o", (unsigned int) c);
1344           break;
1345         }
1346     }
1347   else
1348     {
1349       if (c == '\\' || c == quoter)
1350         do_fputs ("\\", stream);
1351       do_fprintf (stream, "%c", c);
1352     }
1353 }
1354
1355 /* Print the character C on STREAM as part of the contents of a
1356    literal string whose delimiter is QUOTER.  Note that these routines
1357    should only be call for printing things which are independent of
1358    the language of the program being debugged. */
1359
1360 void
1361 fputstr_filtered (str, quoter, stream)
1362      const char *str;
1363      int quoter;
1364      GDB_FILE *stream;
1365 {
1366   while (*str)
1367     printchar (*str++, fputs_filtered, fprintf_filtered, stream, quoter);
1368 }
1369
1370 void
1371 fputstr_unfiltered (str, quoter, stream)
1372      const char *str;
1373      int quoter;
1374      GDB_FILE *stream;
1375 {
1376   while (*str)
1377     printchar (*str++, fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1378 }
1379
1380 void
1381 fputstrn_unfiltered (str, n, quoter, stream)
1382      const char *str;
1383      int n;
1384      int quoter;
1385      GDB_FILE *stream;
1386 {
1387   int i;
1388   for (i = 0; i < n; i++)
1389     printchar (str[i], fputs_unfiltered, fprintf_unfiltered, stream, quoter);
1390 }
1391
1392 \f
1393
1394 /* Number of lines per page or UINT_MAX if paging is disabled.  */
1395 static unsigned int lines_per_page;
1396 /* Number of chars per line or UNIT_MAX if line folding is disabled.  */
1397 static unsigned int chars_per_line;
1398 /* Current count of lines printed on this page, chars on this line.  */
1399 static unsigned int lines_printed, chars_printed;
1400
1401 /* Buffer and start column of buffered text, for doing smarter word-
1402    wrapping.  When someone calls wrap_here(), we start buffering output
1403    that comes through fputs_filtered().  If we see a newline, we just
1404    spit it out and forget about the wrap_here().  If we see another
1405    wrap_here(), we spit it out and remember the newer one.  If we see
1406    the end of the line, we spit out a newline, the indent, and then
1407    the buffered output.  */
1408
1409 /* Malloc'd buffer with chars_per_line+2 bytes.  Contains characters which
1410    are waiting to be output (they have already been counted in chars_printed).
1411    When wrap_buffer[0] is null, the buffer is empty.  */
1412 static char *wrap_buffer;
1413
1414 /* Pointer in wrap_buffer to the next character to fill.  */
1415 static char *wrap_pointer;
1416
1417 /* String to indent by if the wrap occurs.  Must not be NULL if wrap_column
1418    is non-zero.  */
1419 static char *wrap_indent;
1420
1421 /* Column number on the screen where wrap_buffer begins, or 0 if wrapping
1422    is not in effect.  */
1423 static int wrap_column;
1424 \f
1425
1426 /* Inialize the lines and chars per page */
1427 void
1428 init_page_info ()
1429 {
1430 #if defined(TUI)
1431   if (tui_version && m_winPtrNotNull (cmdWin))
1432     {
1433       lines_per_page = cmdWin->generic.height;
1434       chars_per_line = cmdWin->generic.width;
1435     }
1436   else
1437 #endif
1438     {
1439       /* These defaults will be used if we are unable to get the correct
1440          values from termcap.  */
1441 #if defined(__GO32__)
1442       lines_per_page = ScreenRows ();
1443       chars_per_line = ScreenCols ();
1444 #else
1445       lines_per_page = 24;
1446       chars_per_line = 80;
1447
1448 #if !defined (MPW) && !defined (_WIN32)
1449       /* No termcap under MPW, although might be cool to do something
1450          by looking at worksheet or console window sizes. */
1451       /* Initialize the screen height and width from termcap.  */
1452       {
1453         char *termtype = getenv ("TERM");
1454
1455         /* Positive means success, nonpositive means failure.  */
1456         int status;
1457
1458         /* 2048 is large enough for all known terminals, according to the
1459            GNU termcap manual.  */
1460         char term_buffer[2048];
1461
1462         if (termtype)
1463           {
1464             status = tgetent (term_buffer, termtype);
1465             if (status > 0)
1466               {
1467                 int val;
1468                 int running_in_emacs = getenv ("EMACS") != NULL;
1469
1470                 val = tgetnum ("li");
1471                 if (val >= 0 && !running_in_emacs)
1472                   lines_per_page = val;
1473                 else
1474                   /* The number of lines per page is not mentioned
1475                      in the terminal description.  This probably means
1476                      that paging is not useful (e.g. emacs shell window),
1477                      so disable paging.  */
1478                   lines_per_page = UINT_MAX;
1479
1480                 val = tgetnum ("co");
1481                 if (val >= 0)
1482                   chars_per_line = val;
1483               }
1484           }
1485       }
1486 #endif /* MPW */
1487
1488 #if defined(SIGWINCH) && defined(SIGWINCH_HANDLER)
1489
1490       /* If there is a better way to determine the window size, use it. */
1491       SIGWINCH_HANDLER (SIGWINCH);
1492 #endif
1493 #endif
1494       /* If the output is not a terminal, don't paginate it.  */
1495       if (!GDB_FILE_ISATTY (gdb_stdout))
1496         lines_per_page = UINT_MAX;
1497     }                           /* the command_line_version */
1498   set_width ();
1499 }
1500
1501 static void
1502 set_width ()
1503 {
1504   if (chars_per_line == 0)
1505     init_page_info ();
1506
1507   if (!wrap_buffer)
1508     {
1509       wrap_buffer = (char *) xmalloc (chars_per_line + 2);
1510       wrap_buffer[0] = '\0';
1511     }
1512   else
1513     wrap_buffer = (char *) xrealloc (wrap_buffer, chars_per_line + 2);
1514   wrap_pointer = wrap_buffer;   /* Start it at the beginning */
1515 }
1516
1517 /* ARGSUSED */
1518 static void
1519 set_width_command (args, from_tty, c)
1520      char *args;
1521      int from_tty;
1522      struct cmd_list_element *c;
1523 {
1524   set_width ();
1525 }
1526
1527 /* Wait, so the user can read what's on the screen.  Prompt the user
1528    to continue by pressing RETURN.  */
1529
1530 static void
1531 prompt_for_continue ()
1532 {
1533   char *ignore;
1534   char cont_prompt[120];
1535
1536   if (annotation_level > 1)
1537     printf_unfiltered ("\n\032\032pre-prompt-for-continue\n");
1538
1539   strcpy (cont_prompt,
1540           "---Type <return> to continue, or q <return> to quit---");
1541   if (annotation_level > 1)
1542     strcat (cont_prompt, "\n\032\032prompt-for-continue\n");
1543
1544   /* We must do this *before* we call gdb_readline, else it will eventually
1545      call us -- thinking that we're trying to print beyond the end of the 
1546      screen.  */
1547   reinitialize_more_filter ();
1548
1549   immediate_quit++;
1550   /* On a real operating system, the user can quit with SIGINT.
1551      But not on GO32.
1552
1553      'q' is provided on all systems so users don't have to change habits
1554      from system to system, and because telling them what to do in
1555      the prompt is more user-friendly than expecting them to think of
1556      SIGINT.  */
1557   /* Call readline, not gdb_readline, because GO32 readline handles control-C
1558      whereas control-C to gdb_readline will cause the user to get dumped
1559      out to DOS.  */
1560   ignore = readline (cont_prompt);
1561
1562   if (annotation_level > 1)
1563     printf_unfiltered ("\n\032\032post-prompt-for-continue\n");
1564
1565   if (ignore)
1566     {
1567       char *p = ignore;
1568       while (*p == ' ' || *p == '\t')
1569         ++p;
1570       if (p[0] == 'q')
1571         {
1572           if (!event_loop_p)
1573             request_quit (SIGINT);
1574           else
1575             async_request_quit (0);
1576         }
1577       free (ignore);
1578     }
1579   immediate_quit--;
1580
1581   /* Now we have to do this again, so that GDB will know that it doesn't
1582      need to save the ---Type <return>--- line at the top of the screen.  */
1583   reinitialize_more_filter ();
1584
1585   dont_repeat ();               /* Forget prev cmd -- CR won't repeat it. */
1586 }
1587
1588 /* Reinitialize filter; ie. tell it to reset to original values.  */
1589
1590 void
1591 reinitialize_more_filter ()
1592 {
1593   lines_printed = 0;
1594   chars_printed = 0;
1595 }
1596
1597 /* Indicate that if the next sequence of characters overflows the line,
1598    a newline should be inserted here rather than when it hits the end. 
1599    If INDENT is non-null, it is a string to be printed to indent the
1600    wrapped part on the next line.  INDENT must remain accessible until
1601    the next call to wrap_here() or until a newline is printed through
1602    fputs_filtered().
1603
1604    If the line is already overfull, we immediately print a newline and
1605    the indentation, and disable further wrapping.
1606
1607    If we don't know the width of lines, but we know the page height,
1608    we must not wrap words, but should still keep track of newlines
1609    that were explicitly printed.
1610
1611    INDENT should not contain tabs, as that will mess up the char count
1612    on the next line.  FIXME.
1613
1614    This routine is guaranteed to force out any output which has been
1615    squirreled away in the wrap_buffer, so wrap_here ((char *)0) can be
1616    used to force out output from the wrap_buffer.  */
1617
1618 void
1619 wrap_here (indent)
1620      char *indent;
1621 {
1622   /* This should have been allocated, but be paranoid anyway. */
1623   if (!wrap_buffer)
1624     abort ();
1625
1626   if (wrap_buffer[0])
1627     {
1628       *wrap_pointer = '\0';
1629       fputs_unfiltered (wrap_buffer, gdb_stdout);
1630     }
1631   wrap_pointer = wrap_buffer;
1632   wrap_buffer[0] = '\0';
1633   if (chars_per_line == UINT_MAX)       /* No line overflow checking */
1634     {
1635       wrap_column = 0;
1636     }
1637   else if (chars_printed >= chars_per_line)
1638     {
1639       puts_filtered ("\n");
1640       if (indent != NULL)
1641         puts_filtered (indent);
1642       wrap_column = 0;
1643     }
1644   else
1645     {
1646       wrap_column = chars_printed;
1647       if (indent == NULL)
1648         wrap_indent = "";
1649       else
1650         wrap_indent = indent;
1651     }
1652 }
1653
1654 /* Ensure that whatever gets printed next, using the filtered output
1655    commands, starts at the beginning of the line.  I.E. if there is
1656    any pending output for the current line, flush it and start a new
1657    line.  Otherwise do nothing. */
1658
1659 void
1660 begin_line ()
1661 {
1662   if (chars_printed > 0)
1663     {
1664       puts_filtered ("\n");
1665     }
1666 }
1667
1668
1669 /* ``struct gdb_file'' implementation that maps directly onto
1670    <stdio.h>'s FILE. */
1671
1672 static gdb_file_write_ftype stdio_file_write;
1673 static gdb_file_fputs_ftype stdio_file_fputs;
1674 static gdb_file_isatty_ftype stdio_file_isatty;
1675 static gdb_file_delete_ftype stdio_file_delete;
1676 static struct gdb_file *stdio_file_new PARAMS ((FILE * file, int close_p));
1677 static gdb_file_flush_ftype stdio_file_flush;
1678
1679 static int stdio_file_magic;
1680
1681 struct stdio_file
1682   {
1683     int *magic;
1684     FILE *file;
1685     int close_p;
1686   };
1687
1688 static struct gdb_file *
1689 stdio_file_new (file, close_p)
1690      FILE *file;
1691      int close_p;
1692 {
1693   struct gdb_file *gdb_file = gdb_file_new ();
1694   struct stdio_file *stdio = xmalloc (sizeof (struct stdio_file));
1695   stdio->magic = &stdio_file_magic;
1696   stdio->file = file;
1697   stdio->close_p = close_p;
1698   set_gdb_file_data (gdb_file, stdio, stdio_file_delete);
1699   set_gdb_file_flush (gdb_file, stdio_file_flush);
1700   set_gdb_file_write (gdb_file, stdio_file_write);
1701   set_gdb_file_fputs (gdb_file, stdio_file_fputs);
1702   set_gdb_file_isatty (gdb_file, stdio_file_isatty);
1703   return gdb_file;
1704 }
1705
1706 static void
1707 stdio_file_delete (file)
1708      struct gdb_file *file;
1709 {
1710   struct stdio_file *stdio = gdb_file_data (file);
1711   if (stdio->magic != &stdio_file_magic)
1712     internal_error ("stdio_file_delete: bad magic number");
1713   if (stdio->close_p)
1714     {
1715       fclose (stdio->file);
1716     }
1717   free (stdio);
1718 }
1719
1720 static void
1721 stdio_file_flush (file)
1722      struct gdb_file *file;
1723 {
1724   struct stdio_file *stdio = gdb_file_data (file);
1725   if (stdio->magic != &stdio_file_magic)
1726     internal_error ("stdio_file_flush: bad magic number");
1727   fflush (stdio->file);
1728 }
1729
1730 static void
1731 stdio_file_write (struct gdb_file *file, const char *buf, long length_buf)
1732 {
1733   struct stdio_file *stdio = gdb_file_data (file);
1734   if (stdio->magic != &stdio_file_magic)
1735     internal_error ("stdio_file_write: bad magic number");
1736   fwrite (buf, length_buf, 1, stdio->file);
1737 }
1738
1739 static void
1740 stdio_file_fputs (linebuffer, file)
1741      const char *linebuffer;
1742      struct gdb_file *file;
1743 {
1744   struct stdio_file *stdio = gdb_file_data (file);
1745   if (stdio->magic != &stdio_file_magic)
1746     internal_error ("stdio_file_fputs: bad magic number");
1747   fputs (linebuffer, stdio->file);
1748 }
1749
1750 static int
1751 stdio_file_isatty (file)
1752      struct gdb_file *file;
1753 {
1754   struct stdio_file *stdio = gdb_file_data (file);
1755   if (stdio->magic != &stdio_file_magic)
1756     internal_error ("stdio_file_isatty: bad magic number");
1757   return (isatty (fileno (stdio->file)));
1758 }
1759
1760 /* Like fdopen().  Create a gdb_file from a previously opened FILE. */
1761
1762 struct gdb_file *
1763 stdio_fileopen (file)
1764      FILE *file;
1765 {
1766   return stdio_file_new (file, 0);
1767 }
1768
1769
1770 /* A pure memory based ``struct gdb_file'' that can be used an output
1771    buffer. The buffers accumulated contents are available via
1772    gdb_file_put(). */
1773
1774 struct mem_file
1775   {
1776     int *magic;
1777     char *buffer;
1778     int sizeof_buffer;
1779     int length_buffer;
1780   };
1781
1782 static gdb_file_rewind_ftype mem_file_rewind;
1783 static gdb_file_put_ftype mem_file_put;
1784 static gdb_file_write_ftype mem_file_write;
1785 static gdb_file_delete_ftype mem_file_delete;
1786 static struct gdb_file *mem_file_new PARAMS ((void));
1787 static int mem_file_magic;
1788
1789 static struct gdb_file *
1790 mem_file_new (void)
1791 {
1792   struct mem_file *stream = XMALLOC (struct mem_file);
1793   struct gdb_file *file = gdb_file_new ();
1794   set_gdb_file_data (file, stream, mem_file_delete);
1795   set_gdb_file_rewind (file, mem_file_rewind);
1796   set_gdb_file_put (file, mem_file_put);
1797   set_gdb_file_write (file, mem_file_write);
1798   stream->magic = &mem_file_magic;
1799   stream->buffer = NULL;
1800   stream->sizeof_buffer = 0;
1801   stream->length_buffer = 0;
1802   return file;
1803 }
1804
1805 static void
1806 mem_file_delete (struct gdb_file *file)
1807 {
1808   struct mem_file *stream = gdb_file_data (file);
1809   if (stream->magic != &mem_file_magic)
1810     internal_error ("mem_file_delete: bad magic number");
1811   if (stream->buffer != NULL)
1812     free (stream->buffer);
1813   free (stream);
1814 }
1815
1816 struct gdb_file *
1817 mem_fileopen (void)
1818 {
1819   return mem_file_new ();
1820 }
1821
1822 static void
1823 mem_file_rewind (struct gdb_file *file)
1824 {
1825   struct mem_file *stream = gdb_file_data (file);
1826   if (stream->magic != &mem_file_magic)
1827     internal_error ("mem_file_rewind: bad magic number");
1828   stream->length_buffer = 0;
1829 }
1830
1831 static void
1832 mem_file_put (struct gdb_file *file,
1833               gdb_file_put_method_ftype *write,
1834               void *dest)
1835 {
1836   struct mem_file *stream = gdb_file_data (file);
1837   if (stream->magic != &mem_file_magic)
1838     internal_error ("mem_file_put: bad magic number");
1839   if (stream->length_buffer > 0)
1840     write (dest, stream->buffer, stream->length_buffer);
1841 }
1842
1843 void
1844 mem_file_write (struct gdb_file *file,
1845                 const char *buffer,
1846                 long length_buffer)
1847 {
1848   struct mem_file *stream = gdb_file_data (file);
1849   if (stream->magic != &mem_file_magic)
1850     internal_error ("mem_file_write: bad magic number");
1851   if (stream->buffer == NULL)
1852     {
1853       stream->length_buffer = length_buffer;
1854       stream->sizeof_buffer = length_buffer;
1855       stream->buffer = xmalloc (stream->sizeof_buffer);
1856       memcpy (stream->buffer, buffer, length_buffer);
1857     }
1858   else
1859     {
1860       int new_length = stream->length_buffer + length_buffer;
1861       if (new_length >= stream->sizeof_buffer)
1862         {
1863           stream->sizeof_buffer = new_length;
1864           stream->buffer = xrealloc (stream->buffer, stream->sizeof_buffer);
1865         }
1866       memcpy (stream->buffer + stream->length_buffer, buffer, length_buffer);
1867       stream->length_buffer = new_length;
1868     }
1869 }
1870
1871 /* A ``struct gdb_file'' that is compatible with all the legacy
1872    code. */
1873
1874 /* new */
1875 enum streamtype
1876 {
1877   afile,
1878   astring
1879 };
1880
1881 /* new */
1882 struct tui_stream
1883 {
1884   int *ts_magic;
1885   enum streamtype ts_streamtype;
1886   FILE *ts_filestream;
1887   char *ts_strbuf;
1888   int ts_buflen;
1889 };
1890
1891 static gdb_file_flush_ftype tui_file_flush;
1892 extern gdb_file_fputs_ftype tui_file_fputs;
1893 static gdb_file_isatty_ftype tui_file_isatty;
1894 static gdb_file_rewind_ftype tui_file_rewind;
1895 static gdb_file_put_ftype tui_file_put;
1896 static gdb_file_delete_ftype tui_file_delete;
1897 static struct gdb_file *tui_file_new PARAMS ((void));
1898 static int tui_file_magic;
1899
1900 static struct gdb_file *
1901 tui_file_new ()
1902 {
1903   struct tui_stream *tui = xmalloc (sizeof (struct tui_stream));
1904   struct gdb_file *file = gdb_file_new ();
1905   set_gdb_file_data (file, tui, tui_file_delete);
1906   set_gdb_file_flush (file, tui_file_flush);
1907   set_gdb_file_fputs (file, tui_file_fputs);
1908   set_gdb_file_isatty (file, tui_file_isatty);
1909   set_gdb_file_rewind (file, tui_file_rewind);
1910   set_gdb_file_put (file, tui_file_put);
1911   tui->ts_magic = &tui_file_magic;
1912   return file;
1913 }
1914
1915 static void
1916 tui_file_delete (file)
1917      struct gdb_file *file;
1918 {
1919   struct tui_stream *tmpstream = gdb_file_data (file);
1920   if (tmpstream->ts_magic != &tui_file_magic)
1921     internal_error ("tui_file_delete: bad magic number");
1922   if ((tmpstream->ts_streamtype == astring) &&
1923       (tmpstream->ts_strbuf != NULL))
1924     {
1925       free (tmpstream->ts_strbuf);
1926     }
1927   free (tmpstream);
1928 }
1929
1930 struct gdb_file *
1931 tui_fileopen (stream)
1932      FILE *stream;
1933 {
1934   struct gdb_file *file = tui_file_new ();
1935   struct tui_stream *tmpstream = gdb_file_data (file);
1936   tmpstream->ts_streamtype = afile;
1937   tmpstream->ts_filestream = stream;
1938   tmpstream->ts_strbuf = NULL;
1939   tmpstream->ts_buflen = 0;
1940   return file;
1941 }
1942
1943 struct gdb_file *
1944 tui_sfileopen (n)
1945      int n;
1946 {
1947   struct gdb_file *file = tui_file_new ();
1948   struct tui_stream *tmpstream = gdb_file_data (file);
1949   tmpstream->ts_streamtype = astring;
1950   tmpstream->ts_filestream = NULL;
1951   if (n > 0)
1952     {
1953       tmpstream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
1954       tmpstream->ts_strbuf[0] = '\0';
1955     }
1956   else
1957     /* Do not allocate the buffer now.  The first time something is printed
1958        one will be allocated by tui_file_adjust_strbuf()  */
1959     tmpstream->ts_strbuf = NULL;
1960   tmpstream->ts_buflen = n;
1961   return file;
1962 }
1963
1964 static int
1965 tui_file_isatty (file)
1966      struct gdb_file *file;
1967 {
1968   struct tui_stream *stream = gdb_file_data (file);
1969   if (stream->ts_magic != &tui_file_magic)
1970     internal_error ("tui_file_isatty: bad magic number");
1971   if (stream->ts_streamtype == afile)
1972     return (isatty (fileno (stream->ts_filestream)));
1973   else
1974     return 0;
1975 }
1976
1977 static void
1978 tui_file_rewind (file)
1979      struct gdb_file *file;
1980 {
1981   struct tui_stream *stream = gdb_file_data (file);
1982   if (stream->ts_magic != &tui_file_magic)
1983     internal_error ("tui_file_rewind: bad magic number");
1984   stream->ts_strbuf[0] = '\0';
1985 }
1986
1987 static void
1988 tui_file_put (struct gdb_file *file,
1989               gdb_file_put_method_ftype *write,
1990               void *dest)
1991 {
1992   struct tui_stream *stream = gdb_file_data (file);
1993   if (stream->ts_magic != &tui_file_magic)
1994     internal_error ("tui_file_put: bad magic number");
1995   if (stream->ts_streamtype == astring)
1996     write (dest, stream->ts_strbuf, strlen (stream->ts_strbuf));
1997 }
1998
1999 /* All TUI I/O sent to the *_filtered and *_unfiltered functions
2000    eventually ends up here.  The fputs_unfiltered_hook is primarily
2001    used by GUIs to collect all output and send it to the GUI, instead
2002    of the controlling terminal.  Only output to gdb_stdout and
2003    gdb_stderr are sent to the hook.  Everything else is sent on to
2004    fputs to allow file I/O to be handled appropriately.  */
2005
2006 /* FIXME: Should be broken up and moved to a TUI specific file. */
2007
2008 void
2009 tui_file_fputs (linebuffer, file)
2010      const char *linebuffer;
2011      GDB_FILE *file;
2012 {
2013   struct tui_stream *stream = gdb_file_data (file);
2014 #if defined(TUI)
2015   extern int tui_owns_terminal;
2016 #endif
2017   /* NOTE: cagney/1999-10-13: The use of fputs_unfiltered_hook is
2018      seriously discouraged.  Those wanting to hook output should
2019      instead implement their own gdb_file object and install that. See
2020      also tui_file_flush(). */
2021   if (fputs_unfiltered_hook
2022       && (file == gdb_stdout
2023           || file == gdb_stderr))
2024     fputs_unfiltered_hook (linebuffer, file);
2025   else
2026     {
2027 #if defined(TUI)
2028       if (tui_version && tui_owns_terminal)
2029         {
2030           /* If we get here somehow while updating the TUI (from
2031            * within a tuiDo(), then we need to temporarily 
2032            * set up the terminal for GDB output. This probably just
2033            * happens on error output.
2034            */
2035
2036           if (stream->ts_streamtype == astring)
2037             {
2038               tui_file_adjust_strbuf (strlen (linebuffer), stream);
2039               strcat (stream->ts_strbuf, linebuffer);
2040             }
2041           else
2042             {
2043               tuiTermUnsetup (0, (tui_version) ? cmdWin->detail.commandInfo.curch : 0);
2044               fputs (linebuffer, stream->ts_filestream);
2045               tuiTermSetup (0);
2046               if (linebuffer[strlen (linebuffer) - 1] == '\n')
2047                 tuiClearCommandCharCount ();
2048               else
2049                 tuiIncrCommandCharCountBy (strlen (linebuffer));
2050             }
2051         }
2052       else
2053         {
2054           /* The normal case - just do a fputs() */
2055           if (stream->ts_streamtype == astring)
2056             {
2057               tui_file_adjust_strbuf (strlen (linebuffer), stream);
2058               strcat (stream->ts_strbuf, linebuffer);
2059             }
2060           else
2061             fputs (linebuffer, stream->ts_filestream);
2062         }
2063
2064
2065 #else
2066       if (stream->ts_streamtype == astring)
2067         {
2068           tui_file_adjust_strbuf (strlen (linebuffer), file);
2069           strcat (stream->ts_strbuf, linebuffer);
2070         }
2071       else
2072         fputs (linebuffer, stream->ts_filestream);
2073 #endif
2074     }
2075 }
2076
2077 char *
2078 tui_file_get_strbuf (struct gdb_file *file)
2079 {
2080   struct tui_stream *stream = gdb_file_data (file);
2081   if (stream->ts_magic != &tui_file_magic)
2082     internal_error ("tui_file_get_strbuf: bad magic number");
2083   return (stream->ts_strbuf);
2084 }
2085
2086 /* adjust the length of the buffer by the amount necessary
2087    to accomodate appending a string of length N to the buffer contents */
2088 void
2089 tui_file_adjust_strbuf (int n, struct gdb_file *file)
2090 {
2091   struct tui_stream *stream = gdb_file_data (file);
2092   int non_null_chars;
2093   if (stream->ts_magic != &tui_file_magic)
2094     internal_error ("tui_file_adjust_strbuf: bad magic number");
2095
2096   if (stream->ts_streamtype != astring)
2097     return;
2098
2099   if (stream->ts_strbuf)
2100     {
2101       /* There is already a buffer allocated */
2102       non_null_chars = strlen (stream->ts_strbuf);
2103
2104       if (n > (stream->ts_buflen - non_null_chars - 1))
2105         {
2106           stream->ts_buflen = n + non_null_chars + 1;
2107           stream->ts_strbuf = xrealloc (stream->ts_strbuf, stream->ts_buflen);
2108         }
2109     }
2110   else
2111     /* No buffer yet, so allocate one of the desired size */
2112     stream->ts_strbuf = xmalloc ((n + 1) * sizeof (char));
2113 }
2114
2115 GDB_FILE *
2116 gdb_fopen (name, mode)
2117      char *name;
2118      char *mode;
2119 {
2120   FILE *f = fopen (name, mode);
2121   if (f == NULL)
2122     return NULL;
2123   return stdio_file_new (f, 1);
2124 }
2125
2126 static void
2127 tui_file_flush (file)
2128      GDB_FILE *file;
2129 {
2130   struct tui_stream *stream = gdb_file_data (file);
2131   if (stream->ts_magic != &tui_file_magic)
2132     internal_error ("tui_file_flush: bad magic number");
2133
2134   /* NOTE: cagney/1999-10-12: If we've been linked with code that uses
2135      fputs_unfiltered_hook then we assume that it doesn't need to know
2136      about flushes.  Code that does need to know about flushes can
2137      implement a proper gdb_file object. */
2138   if (fputs_unfiltered_hook)
2139     return;
2140
2141   switch (stream->ts_streamtype)
2142     {
2143     case astring:
2144       break;
2145     case afile:
2146       fflush (stream->ts_filestream);
2147       break;
2148     }
2149 }
2150
2151 /* Implement the ``struct gdb_file'' object. */
2152
2153 static gdb_file_isatty_ftype null_file_isatty;
2154 static gdb_file_write_ftype null_file_write;
2155 static gdb_file_fputs_ftype null_file_fputs;
2156 static gdb_file_flush_ftype null_file_flush;
2157 static gdb_file_delete_ftype null_file_delete;
2158 static gdb_file_rewind_ftype null_file_rewind;
2159 static gdb_file_put_ftype null_file_put;
2160
2161 struct gdb_file
2162   {
2163     int *magic;
2164     gdb_file_flush_ftype *to_flush;
2165     gdb_file_write_ftype *to_write;
2166     gdb_file_fputs_ftype *to_fputs;
2167     gdb_file_delete_ftype *to_delete;
2168     gdb_file_isatty_ftype *to_isatty;
2169     gdb_file_rewind_ftype *to_rewind;
2170     gdb_file_put_ftype *to_put;
2171     void *to_data;
2172   };
2173 int gdb_file_magic;
2174
2175 struct gdb_file *
2176 gdb_file_new ()
2177 {
2178   struct gdb_file *file = xmalloc (sizeof (struct gdb_file));
2179   file->magic = &gdb_file_magic;
2180   set_gdb_file_data (file, NULL, null_file_delete);
2181   set_gdb_file_flush (file, null_file_flush);
2182   set_gdb_file_write (file, null_file_write);
2183   set_gdb_file_fputs (file, null_file_fputs);
2184   set_gdb_file_isatty (file, null_file_isatty);
2185   set_gdb_file_rewind (file, null_file_rewind);
2186   set_gdb_file_put (file, null_file_put);
2187   return file;
2188 }
2189
2190 void
2191 gdb_file_delete (file)
2192      struct gdb_file *file;
2193 {
2194   file->to_delete (file);
2195   free (file);
2196 }
2197
2198 static int
2199 null_file_isatty (file)
2200      struct gdb_file *file;
2201 {
2202   return 0;
2203 }
2204
2205 static void
2206 null_file_rewind (file)
2207      struct gdb_file *file;
2208 {
2209   return;
2210 }
2211
2212 static void
2213 null_file_put (struct gdb_file *file,
2214                gdb_file_put_method_ftype *write,
2215                void *dest)
2216 {
2217   return;
2218 }
2219
2220 static void
2221 null_file_flush (file)
2222      struct gdb_file *file;
2223 {
2224   return;
2225 }
2226
2227 static void
2228 null_file_write (struct gdb_file *file,
2229                  const char *buf,
2230                  long sizeof_buf)
2231 {
2232   if (file->to_fputs == null_file_fputs)
2233     /* Both the write and fputs methods are null. Discard the
2234        request. */
2235     return;
2236   else
2237     {
2238       /* The fputs method isn't null, slowly pass the write request
2239          onto that.  FYI, this isn't as bad as it may look - the
2240          current (as of 1999-11-07) printf_* function calls fputc and
2241          fputc does exactly the below.  By having a write function it
2242          is possible to clean up that code.  */
2243       int i;
2244       char b[2];
2245       b[1] = '\0';
2246       for (i = 0; i < sizeof_buf; i++)
2247         {
2248           b[0] = buf[i];
2249           file->to_fputs (b, file);
2250         }
2251       return;
2252     }
2253 }
2254
2255 static void
2256 null_file_fputs (buf, file)
2257      const char *buf;
2258      struct gdb_file *file;
2259 {
2260   if (file->to_write == null_file_write)
2261     /* Both the write and fputs methods are null. Discard the
2262        request. */
2263     return;
2264   else
2265     {
2266       /* The write method was implemented, use that. */
2267       file->to_write (file, buf, strlen (buf));
2268     }
2269 }
2270
2271 static void
2272 null_file_delete (file)
2273      struct gdb_file *file;
2274 {
2275   return;
2276 }
2277
2278 void *
2279 gdb_file_data (file)
2280      struct gdb_file *file;
2281 {
2282   if (file->magic != &gdb_file_magic)
2283     internal_error ("gdb_file_data: bad magic number");
2284   return file->to_data;
2285 }
2286
2287 void
2288 gdb_flush (file)
2289      struct gdb_file *file;
2290 {
2291   file->to_flush (file);
2292 }
2293
2294 int
2295 gdb_file_isatty (file)
2296      struct gdb_file *file;
2297 {
2298   return file->to_isatty (file);
2299 }
2300
2301 void
2302 gdb_file_rewind (file)
2303      struct gdb_file *file;
2304 {
2305   file->to_rewind (file);
2306 }
2307
2308 void
2309 gdb_file_put (struct gdb_file *file,
2310               gdb_file_put_method_ftype *write,
2311               void *dest)
2312 {
2313   file->to_put (file, write, dest);
2314 }
2315
2316 void
2317 gdb_file_write (struct gdb_file *file,
2318                 const char *buf,
2319                 long length_buf)
2320 {
2321   file->to_write (file, buf, length_buf);
2322 }
2323
2324 void
2325 fputs_unfiltered (buf, file)
2326      const char *buf;
2327      struct gdb_file *file;
2328 {
2329   file->to_fputs (buf, file);
2330 }
2331
2332 void
2333 set_gdb_file_flush (file, flush)
2334      struct gdb_file *file;
2335      gdb_file_flush_ftype *flush;
2336 {
2337   file->to_flush = flush;
2338 }
2339
2340 void
2341 set_gdb_file_isatty (file, isatty)
2342      struct gdb_file *file;
2343      gdb_file_isatty_ftype *isatty;
2344 {
2345   file->to_isatty = isatty;
2346 }
2347
2348 void
2349 set_gdb_file_rewind (file, rewind)
2350      struct gdb_file *file;
2351      gdb_file_rewind_ftype *rewind;
2352 {
2353   file->to_rewind = rewind;
2354 }
2355
2356 void
2357 set_gdb_file_put (file, put)
2358      struct gdb_file *file;
2359      gdb_file_put_ftype *put;
2360 {
2361   file->to_put = put;
2362 }
2363
2364 void
2365 set_gdb_file_write (struct gdb_file *file,
2366                     gdb_file_write_ftype *write)
2367 {
2368   file->to_write = write;
2369 }
2370
2371 void
2372 set_gdb_file_fputs (file, fputs)
2373      struct gdb_file *file;
2374      gdb_file_fputs_ftype *fputs;
2375 {
2376   file->to_fputs = fputs;
2377 }
2378
2379 void
2380 set_gdb_file_data (file, data, delete)
2381      struct gdb_file *file;
2382      void *data;
2383      gdb_file_delete_ftype *delete;
2384 {
2385   file->to_data = data;
2386   file->to_delete = delete;
2387 }
2388
2389 /* gdb_file utility function for converting a ``struct gdb_file'' into
2390    a memory buffer''. */
2391
2392 struct accumulated_gdb_file
2393 {
2394   char *buffer;
2395   long length;
2396 };
2397
2398 static void
2399 do_gdb_file_xstrdup (void *context, const char *buffer, long length)
2400 {
2401   struct accumulated_gdb_file *acc = context;
2402   if (acc->buffer == NULL)
2403     acc->buffer = xmalloc (length + 1);
2404   else
2405     acc->buffer = xrealloc (acc->buffer, acc->length + length + 1);
2406   memcpy (acc->buffer + acc->length, buffer, length);
2407   acc->length += length;
2408   acc->buffer[acc->length] = '\0';
2409 }
2410
2411 char *
2412 gdb_file_xstrdup (struct gdb_file *file,
2413                   long *length)
2414 {
2415   struct accumulated_gdb_file acc;
2416   acc.buffer = NULL;
2417   acc.length = 0;
2418   gdb_file_put (file, do_gdb_file_xstrdup, &acc);
2419   if (acc.buffer == NULL)
2420     acc.buffer = xstrdup ("");
2421   *length = acc.length;
2422   return acc.buffer;
2423 }
2424
2425
2426 /* Like fputs but if FILTER is true, pause after every screenful.
2427
2428    Regardless of FILTER can wrap at points other than the final
2429    character of a line.
2430
2431    Unlike fputs, fputs_maybe_filtered does not return a value.
2432    It is OK for LINEBUFFER to be NULL, in which case just don't print
2433    anything.
2434
2435    Note that a longjmp to top level may occur in this routine (only if
2436    FILTER is true) (since prompt_for_continue may do so) so this
2437    routine should not be called when cleanups are not in place.  */
2438
2439 static void
2440 fputs_maybe_filtered (linebuffer, stream, filter)
2441      const char *linebuffer;
2442      GDB_FILE *stream;
2443      int filter;
2444 {
2445   const char *lineptr;
2446
2447   if (linebuffer == 0)
2448     return;
2449
2450   /* Don't do any filtering if it is disabled.  */
2451   if ((stream != gdb_stdout) || !pagination_enabled
2452       || (lines_per_page == UINT_MAX && chars_per_line == UINT_MAX))
2453     {
2454       fputs_unfiltered (linebuffer, stream);
2455       return;
2456     }
2457
2458   /* Go through and output each character.  Show line extension
2459      when this is necessary; prompt user for new page when this is
2460      necessary.  */
2461
2462   lineptr = linebuffer;
2463   while (*lineptr)
2464     {
2465       /* Possible new page.  */
2466       if (filter &&
2467           (lines_printed >= lines_per_page - 1))
2468         prompt_for_continue ();
2469
2470       while (*lineptr && *lineptr != '\n')
2471         {
2472           /* Print a single line.  */
2473           if (*lineptr == '\t')
2474             {
2475               if (wrap_column)
2476                 *wrap_pointer++ = '\t';
2477               else
2478                 fputc_unfiltered ('\t', stream);
2479               /* Shifting right by 3 produces the number of tab stops
2480                  we have already passed, and then adding one and
2481                  shifting left 3 advances to the next tab stop.  */
2482               chars_printed = ((chars_printed >> 3) + 1) << 3;
2483               lineptr++;
2484             }
2485           else
2486             {
2487               if (wrap_column)
2488                 *wrap_pointer++ = *lineptr;
2489               else
2490                 fputc_unfiltered (*lineptr, stream);
2491               chars_printed++;
2492               lineptr++;
2493             }
2494
2495           if (chars_printed >= chars_per_line)
2496             {
2497               unsigned int save_chars = chars_printed;
2498
2499               chars_printed = 0;
2500               lines_printed++;
2501               /* If we aren't actually wrapping, don't output newline --
2502                  if chars_per_line is right, we probably just overflowed
2503                  anyway; if it's wrong, let us keep going.  */
2504               if (wrap_column)
2505                 fputc_unfiltered ('\n', stream);
2506
2507               /* Possible new page.  */
2508               if (lines_printed >= lines_per_page - 1)
2509                 prompt_for_continue ();
2510
2511               /* Now output indentation and wrapped string */
2512               if (wrap_column)
2513                 {
2514                   fputs_unfiltered (wrap_indent, stream);
2515                   *wrap_pointer = '\0';         /* Null-terminate saved stuff */
2516                   fputs_unfiltered (wrap_buffer, stream);       /* and eject it */
2517                   /* FIXME, this strlen is what prevents wrap_indent from
2518                      containing tabs.  However, if we recurse to print it
2519                      and count its chars, we risk trouble if wrap_indent is
2520                      longer than (the user settable) chars_per_line. 
2521                      Note also that this can set chars_printed > chars_per_line
2522                      if we are printing a long string.  */
2523                   chars_printed = strlen (wrap_indent)
2524                     + (save_chars - wrap_column);
2525                   wrap_pointer = wrap_buffer;   /* Reset buffer */
2526                   wrap_buffer[0] = '\0';
2527                   wrap_column = 0;      /* And disable fancy wrap */
2528                 }
2529             }
2530         }
2531
2532       if (*lineptr == '\n')
2533         {
2534           chars_printed = 0;
2535           wrap_here ((char *) 0);       /* Spit out chars, cancel further wraps */
2536           lines_printed++;
2537           fputc_unfiltered ('\n', stream);
2538           lineptr++;
2539         }
2540     }
2541 }
2542
2543 void
2544 fputs_filtered (linebuffer, stream)
2545      const char *linebuffer;
2546      GDB_FILE *stream;
2547 {
2548   fputs_maybe_filtered (linebuffer, stream, 1);
2549 }
2550
2551 int
2552 putchar_unfiltered (c)
2553      int c;
2554 {
2555   char buf = c;
2556   gdb_file_write (gdb_stdout, &buf, 1);
2557   return c;
2558 }
2559
2560 int
2561 fputc_unfiltered (c, stream)
2562      int c;
2563      GDB_FILE *stream;
2564 {
2565   char buf = c;
2566   gdb_file_write (stream, &buf, 1);
2567   return c;
2568 }
2569
2570 int
2571 fputc_filtered (c, stream)
2572      int c;
2573      GDB_FILE *stream;
2574 {
2575   char buf[2];
2576
2577   buf[0] = c;
2578   buf[1] = 0;
2579   fputs_filtered (buf, stream);
2580   return c;
2581 }
2582
2583 /* puts_debug is like fputs_unfiltered, except it prints special
2584    characters in printable fashion.  */
2585
2586 void
2587 puts_debug (prefix, string, suffix)
2588      char *prefix;
2589      char *string;
2590      char *suffix;
2591 {
2592   int ch;
2593
2594   /* Print prefix and suffix after each line.  */
2595   static int new_line = 1;
2596   static int return_p = 0;
2597   static char *prev_prefix = "";
2598   static char *prev_suffix = "";
2599
2600   if (*string == '\n')
2601     return_p = 0;
2602
2603   /* If the prefix is changing, print the previous suffix, a new line,
2604      and the new prefix.  */
2605   if ((return_p || (strcmp (prev_prefix, prefix) != 0)) && !new_line)
2606     {
2607       fputs_unfiltered (prev_suffix, gdb_stdlog);
2608       fputs_unfiltered ("\n", gdb_stdlog);
2609       fputs_unfiltered (prefix, gdb_stdlog);
2610     }
2611
2612   /* Print prefix if we printed a newline during the previous call.  */
2613   if (new_line)
2614     {
2615       new_line = 0;
2616       fputs_unfiltered (prefix, gdb_stdlog);
2617     }
2618
2619   prev_prefix = prefix;
2620   prev_suffix = suffix;
2621
2622   /* Output characters in a printable format.  */
2623   while ((ch = *string++) != '\0')
2624     {
2625       switch (ch)
2626         {
2627         default:
2628           if (isprint (ch))
2629             fputc_unfiltered (ch, gdb_stdlog);
2630
2631           else
2632             fprintf_unfiltered (gdb_stdlog, "\\x%02x", ch & 0xff);
2633           break;
2634
2635         case '\\':
2636           fputs_unfiltered ("\\\\", gdb_stdlog);
2637           break;
2638         case '\b':
2639           fputs_unfiltered ("\\b", gdb_stdlog);
2640           break;
2641         case '\f':
2642           fputs_unfiltered ("\\f", gdb_stdlog);
2643           break;
2644         case '\n':
2645           new_line = 1;
2646           fputs_unfiltered ("\\n", gdb_stdlog);
2647           break;
2648         case '\r':
2649           fputs_unfiltered ("\\r", gdb_stdlog);
2650           break;
2651         case '\t':
2652           fputs_unfiltered ("\\t", gdb_stdlog);
2653           break;
2654         case '\v':
2655           fputs_unfiltered ("\\v", gdb_stdlog);
2656           break;
2657         }
2658
2659       return_p = ch == '\r';
2660     }
2661
2662   /* Print suffix if we printed a newline.  */
2663   if (new_line)
2664     {
2665       fputs_unfiltered (suffix, gdb_stdlog);
2666       fputs_unfiltered ("\n", gdb_stdlog);
2667     }
2668 }
2669
2670
2671 /* Print a variable number of ARGS using format FORMAT.  If this
2672    information is going to put the amount written (since the last call
2673    to REINITIALIZE_MORE_FILTER or the last page break) over the page size,
2674    call prompt_for_continue to get the users permision to continue.
2675
2676    Unlike fprintf, this function does not return a value.
2677
2678    We implement three variants, vfprintf (takes a vararg list and stream),
2679    fprintf (takes a stream to write on), and printf (the usual).
2680
2681    Note also that a longjmp to top level may occur in this routine
2682    (since prompt_for_continue may do so) so this routine should not be
2683    called when cleanups are not in place.  */
2684
2685 static void
2686 vfprintf_maybe_filtered (stream, format, args, filter)
2687      GDB_FILE *stream;
2688      const char *format;
2689      va_list args;
2690      int filter;
2691 {
2692   char *linebuffer;
2693   struct cleanup *old_cleanups;
2694
2695   vasprintf (&linebuffer, format, args);
2696   if (linebuffer == NULL)
2697     {
2698       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2699       exit (1);
2700     }
2701   old_cleanups = make_cleanup (free, linebuffer);
2702   fputs_maybe_filtered (linebuffer, stream, filter);
2703   do_cleanups (old_cleanups);
2704 }
2705
2706
2707 void
2708 vfprintf_filtered (stream, format, args)
2709      GDB_FILE *stream;
2710      const char *format;
2711      va_list args;
2712 {
2713   vfprintf_maybe_filtered (stream, format, args, 1);
2714 }
2715
2716 void
2717 vfprintf_unfiltered (stream, format, args)
2718      GDB_FILE *stream;
2719      const char *format;
2720      va_list args;
2721 {
2722   char *linebuffer;
2723   struct cleanup *old_cleanups;
2724
2725   vasprintf (&linebuffer, format, args);
2726   if (linebuffer == NULL)
2727     {
2728       fputs_unfiltered ("\ngdb: virtual memory exhausted.\n", gdb_stderr);
2729       exit (1);
2730     }
2731   old_cleanups = make_cleanup (free, linebuffer);
2732   fputs_unfiltered (linebuffer, stream);
2733   do_cleanups (old_cleanups);
2734 }
2735
2736 void
2737 vprintf_filtered (format, args)
2738      const char *format;
2739      va_list args;
2740 {
2741   vfprintf_maybe_filtered (gdb_stdout, format, args, 1);
2742 }
2743
2744 void
2745 vprintf_unfiltered (format, args)
2746      const char *format;
2747      va_list args;
2748 {
2749   vfprintf_unfiltered (gdb_stdout, format, args);
2750 }
2751
2752 void
2753 fprintf_filtered (GDB_FILE * stream, const char *format,...)
2754 {
2755   va_list args;
2756   va_start (args, format);
2757   vfprintf_filtered (stream, format, args);
2758   va_end (args);
2759 }
2760
2761 void
2762 fprintf_unfiltered (GDB_FILE * stream, const char *format,...)
2763 {
2764   va_list args;
2765   va_start (args, format);
2766   vfprintf_unfiltered (stream, format, args);
2767   va_end (args);
2768 }
2769
2770 /* Like fprintf_filtered, but prints its result indented.
2771    Called as fprintfi_filtered (spaces, stream, format, ...);  */
2772
2773 void
2774 fprintfi_filtered (int spaces, GDB_FILE * stream, const char *format,...)
2775 {
2776   va_list args;
2777   va_start (args, format);
2778   print_spaces_filtered (spaces, stream);
2779
2780   vfprintf_filtered (stream, format, args);
2781   va_end (args);
2782 }
2783
2784
2785 void
2786 printf_filtered (const char *format,...)
2787 {
2788   va_list args;
2789   va_start (args, format);
2790   vfprintf_filtered (gdb_stdout, format, args);
2791   va_end (args);
2792 }
2793
2794
2795 void
2796 printf_unfiltered (const char *format,...)
2797 {
2798   va_list args;
2799   va_start (args, format);
2800   vfprintf_unfiltered (gdb_stdout, format, args);
2801   va_end (args);
2802 }
2803
2804 /* Like printf_filtered, but prints it's result indented.
2805    Called as printfi_filtered (spaces, format, ...);  */
2806
2807 void
2808 printfi_filtered (int spaces, const char *format,...)
2809 {
2810   va_list args;
2811   va_start (args, format);
2812   print_spaces_filtered (spaces, gdb_stdout);
2813   vfprintf_filtered (gdb_stdout, format, args);
2814   va_end (args);
2815 }
2816
2817 /* Easy -- but watch out!
2818
2819    This routine is *not* a replacement for puts()!  puts() appends a newline.
2820    This one doesn't, and had better not!  */
2821
2822 void
2823 puts_filtered (string)
2824      const char *string;
2825 {
2826   fputs_filtered (string, gdb_stdout);
2827 }
2828
2829 void
2830 puts_unfiltered (string)
2831      const char *string;
2832 {
2833   fputs_unfiltered (string, gdb_stdout);
2834 }
2835
2836 /* Return a pointer to N spaces and a null.  The pointer is good
2837    until the next call to here.  */
2838 char *
2839 n_spaces (n)
2840      int n;
2841 {
2842   char *t;
2843   static char *spaces = 0;
2844   static int max_spaces = -1;
2845
2846   if (n > max_spaces)
2847     {
2848       if (spaces)
2849         free (spaces);
2850       spaces = (char *) xmalloc (n + 1);
2851       for (t = spaces + n; t != spaces;)
2852         *--t = ' ';
2853       spaces[n] = '\0';
2854       max_spaces = n;
2855     }
2856
2857   return spaces + max_spaces - n;
2858 }
2859
2860 /* Print N spaces.  */
2861 void
2862 print_spaces_filtered (n, stream)
2863      int n;
2864      GDB_FILE *stream;
2865 {
2866   fputs_filtered (n_spaces (n), stream);
2867 }
2868 \f
2869 /* C++ demangler stuff.  */
2870
2871 /* fprintf_symbol_filtered attempts to demangle NAME, a symbol in language
2872    LANG, using demangling args ARG_MODE, and print it filtered to STREAM.
2873    If the name is not mangled, or the language for the name is unknown, or
2874    demangling is off, the name is printed in its "raw" form. */
2875
2876 void
2877 fprintf_symbol_filtered (stream, name, lang, arg_mode)
2878      GDB_FILE *stream;
2879      char *name;
2880      enum language lang;
2881      int arg_mode;
2882 {
2883   char *demangled;
2884
2885   if (name != NULL)
2886     {
2887       /* If user wants to see raw output, no problem.  */
2888       if (!demangle)
2889         {
2890           fputs_filtered (name, stream);
2891         }
2892       else
2893         {
2894           switch (lang)
2895             {
2896             case language_cplus:
2897               demangled = cplus_demangle (name, arg_mode);
2898               break;
2899             case language_java:
2900               demangled = cplus_demangle (name, arg_mode | DMGL_JAVA);
2901               break;
2902             case language_chill:
2903               demangled = chill_demangle (name);
2904               break;
2905             default:
2906               demangled = NULL;
2907               break;
2908             }
2909           fputs_filtered (demangled ? demangled : name, stream);
2910           if (demangled != NULL)
2911             {
2912               free (demangled);
2913             }
2914         }
2915     }
2916 }
2917
2918 /* Do a strcmp() type operation on STRING1 and STRING2, ignoring any
2919    differences in whitespace.  Returns 0 if they match, non-zero if they
2920    don't (slightly different than strcmp()'s range of return values).
2921
2922    As an extra hack, string1=="FOO(ARGS)" matches string2=="FOO".
2923    This "feature" is useful when searching for matching C++ function names
2924    (such as if the user types 'break FOO', where FOO is a mangled C++
2925    function). */
2926
2927 int
2928 strcmp_iw (string1, string2)
2929      const char *string1;
2930      const char *string2;
2931 {
2932   while ((*string1 != '\0') && (*string2 != '\0'))
2933     {
2934       while (isspace (*string1))
2935         {
2936           string1++;
2937         }
2938       while (isspace (*string2))
2939         {
2940           string2++;
2941         }
2942       if (*string1 != *string2)
2943         {
2944           break;
2945         }
2946       if (*string1 != '\0')
2947         {
2948           string1++;
2949           string2++;
2950         }
2951     }
2952   return (*string1 != '\0' && *string1 != '(') || (*string2 != '\0');
2953 }
2954 \f
2955
2956 /*
2957    ** subset_compare()
2958    **    Answer whether string_to_compare is a full or partial match to
2959    **    template_string.  The partial match must be in sequence starting
2960    **    at index 0.
2961  */
2962 int
2963 subset_compare (string_to_compare, template_string)
2964      char *string_to_compare;
2965      char *template_string;
2966 {
2967   int match;
2968   if (template_string != (char *) NULL && string_to_compare != (char *) NULL &&
2969       strlen (string_to_compare) <= strlen (template_string))
2970     match = (strncmp (template_string,
2971                       string_to_compare,
2972                       strlen (string_to_compare)) == 0);
2973   else
2974     match = 0;
2975   return match;
2976 }
2977
2978
2979 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2980 static void
2981 pagination_on_command (arg, from_tty)
2982      char *arg;
2983      int from_tty;
2984 {
2985   pagination_enabled = 1;
2986 }
2987
2988 static void pagination_on_command PARAMS ((char *arg, int from_tty));
2989 static void
2990 pagination_off_command (arg, from_tty)
2991      char *arg;
2992      int from_tty;
2993 {
2994   pagination_enabled = 0;
2995 }
2996 \f
2997
2998 void
2999 initialize_utils ()
3000 {
3001   struct cmd_list_element *c;
3002
3003   c = add_set_cmd ("width", class_support, var_uinteger,
3004                    (char *) &chars_per_line,
3005                    "Set number of characters gdb thinks are in a line.",
3006                    &setlist);
3007   add_show_from_set (c, &showlist);
3008   c->function.sfunc = set_width_command;
3009
3010   add_show_from_set
3011     (add_set_cmd ("height", class_support,
3012                   var_uinteger, (char *) &lines_per_page,
3013                   "Set number of lines gdb thinks are in a page.", &setlist),
3014      &showlist);
3015
3016   init_page_info ();
3017
3018   /* If the output is not a terminal, don't paginate it.  */
3019   if (!GDB_FILE_ISATTY (gdb_stdout))
3020     lines_per_page = UINT_MAX;
3021
3022   set_width_command ((char *) NULL, 0, c);
3023
3024   add_show_from_set
3025     (add_set_cmd ("demangle", class_support, var_boolean,
3026                   (char *) &demangle,
3027              "Set demangling of encoded C++ names when displaying symbols.",
3028                   &setprintlist),
3029      &showprintlist);
3030
3031   add_show_from_set
3032     (add_set_cmd ("pagination", class_support,
3033                   var_boolean, (char *) &pagination_enabled,
3034                   "Set state of pagination.", &setlist),
3035      &showlist);
3036   if (xdb_commands)
3037     {
3038       add_com ("am", class_support, pagination_on_command,
3039                "Enable pagination");
3040       add_com ("sm", class_support, pagination_off_command,
3041                "Disable pagination");
3042     }
3043
3044   add_show_from_set
3045     (add_set_cmd ("sevenbit-strings", class_support, var_boolean,
3046                   (char *) &sevenbit_strings,
3047                   "Set printing of 8-bit characters in strings as \\nnn.",
3048                   &setprintlist),
3049      &showprintlist);
3050
3051   add_show_from_set
3052     (add_set_cmd ("asm-demangle", class_support, var_boolean,
3053                   (char *) &asm_demangle,
3054                   "Set demangling of C++ names in disassembly listings.",
3055                   &setprintlist),
3056      &showprintlist);
3057 }
3058
3059 /* Machine specific function to handle SIGWINCH signal. */
3060
3061 #ifdef  SIGWINCH_HANDLER_BODY
3062 SIGWINCH_HANDLER_BODY
3063 #endif
3064 \f
3065 /* Support for converting target fp numbers into host DOUBLEST format.  */
3066
3067 /* XXX - This code should really be in libiberty/floatformat.c, however
3068    configuration issues with libiberty made this very difficult to do in the
3069    available time.  */
3070
3071 #include "floatformat.h"
3072 #include <math.h>               /* ldexp */
3073
3074 /* The odds that CHAR_BIT will be anything but 8 are low enough that I'm not
3075    going to bother with trying to muck around with whether it is defined in
3076    a system header, what we do if not, etc.  */
3077 #define FLOATFORMAT_CHAR_BIT 8
3078
3079 static unsigned long get_field PARAMS ((unsigned char *,
3080                                         enum floatformat_byteorders,
3081                                         unsigned int,
3082                                         unsigned int,
3083                                         unsigned int));
3084
3085 /* Extract a field which starts at START and is LEN bytes long.  DATA and
3086    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
3087 static unsigned long
3088 get_field (data, order, total_len, start, len)
3089      unsigned char *data;
3090      enum floatformat_byteorders order;
3091      unsigned int total_len;
3092      unsigned int start;
3093      unsigned int len;
3094 {
3095   unsigned long result;
3096   unsigned int cur_byte;
3097   int cur_bitshift;
3098
3099   /* Start at the least significant part of the field.  */
3100   cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
3101   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3102     cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
3103   cur_bitshift =
3104     ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
3105   result = *(data + cur_byte) >> (-cur_bitshift);
3106   cur_bitshift += FLOATFORMAT_CHAR_BIT;
3107   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3108     ++cur_byte;
3109   else
3110     --cur_byte;
3111
3112   /* Move towards the most significant part of the field.  */
3113   while (cur_bitshift < len)
3114     {
3115       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
3116         /* This is the last byte; zero out the bits which are not part of
3117            this field.  */
3118         result |=
3119           (*(data + cur_byte) & ((1 << (len - cur_bitshift)) - 1))
3120           << cur_bitshift;
3121       else
3122         result |= *(data + cur_byte) << cur_bitshift;
3123       cur_bitshift += FLOATFORMAT_CHAR_BIT;
3124       if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3125         ++cur_byte;
3126       else
3127         --cur_byte;
3128     }
3129   return result;
3130 }
3131
3132 /* Convert from FMT to a DOUBLEST.
3133    FROM is the address of the extended float.
3134    Store the DOUBLEST in *TO.  */
3135
3136 void
3137 floatformat_to_doublest (fmt, from, to)
3138      const struct floatformat *fmt;
3139      char *from;
3140      DOUBLEST *to;
3141 {
3142   unsigned char *ufrom = (unsigned char *) from;
3143   DOUBLEST dto;
3144   long exponent;
3145   unsigned long mant;
3146   unsigned int mant_bits, mant_off;
3147   int mant_bits_left;
3148   int special_exponent;         /* It's a NaN, denorm or zero */
3149
3150   /* If the mantissa bits are not contiguous from one end of the
3151      mantissa to the other, we need to make a private copy of the
3152      source bytes that is in the right order since the unpacking
3153      algorithm assumes that the bits are contiguous.
3154
3155      Swap the bytes individually rather than accessing them through
3156      "long *" since we have no guarantee that they start on a long
3157      alignment, and also sizeof(long) for the host could be different
3158      than sizeof(long) for the target.  FIXME: Assumes sizeof(long)
3159      for the target is 4. */
3160
3161   if (fmt->byteorder == floatformat_littlebyte_bigword)
3162     {
3163       static unsigned char *newfrom;
3164       unsigned char *swapin, *swapout;
3165       int longswaps;
3166
3167       longswaps = fmt->totalsize / FLOATFORMAT_CHAR_BIT;
3168       longswaps >>= 3;
3169
3170       if (newfrom == NULL)
3171         {
3172           newfrom = (unsigned char *) xmalloc (fmt->totalsize);
3173         }
3174       swapout = newfrom;
3175       swapin = ufrom;
3176       ufrom = newfrom;
3177       while (longswaps-- > 0)
3178         {
3179           /* This is ugly, but efficient */
3180           *swapout++ = swapin[4];
3181           *swapout++ = swapin[5];
3182           *swapout++ = swapin[6];
3183           *swapout++ = swapin[7];
3184           *swapout++ = swapin[0];
3185           *swapout++ = swapin[1];
3186           *swapout++ = swapin[2];
3187           *swapout++ = swapin[3];
3188           swapin += 8;
3189         }
3190     }
3191
3192   exponent = get_field (ufrom, fmt->byteorder, fmt->totalsize,
3193                         fmt->exp_start, fmt->exp_len);
3194   /* Note that if exponent indicates a NaN, we can't really do anything useful
3195      (not knowing if the host has NaN's, or how to build one).  So it will
3196      end up as an infinity or something close; that is OK.  */
3197
3198   mant_bits_left = fmt->man_len;
3199   mant_off = fmt->man_start;
3200   dto = 0.0;
3201
3202   special_exponent = exponent == 0 || exponent == fmt->exp_nan;
3203
3204 /* Don't bias NaNs. Use minimum exponent for denorms. For simplicity,
3205    we don't check for zero as the exponent doesn't matter. */
3206   if (!special_exponent)
3207     exponent -= fmt->exp_bias;
3208   else if (exponent == 0)
3209     exponent = 1 - fmt->exp_bias;
3210
3211   /* Build the result algebraically.  Might go infinite, underflow, etc;
3212      who cares. */
3213
3214 /* If this format uses a hidden bit, explicitly add it in now.  Otherwise,
3215    increment the exponent by one to account for the integer bit.  */
3216
3217   if (!special_exponent)
3218     {
3219       if (fmt->intbit == floatformat_intbit_no)
3220         dto = ldexp (1.0, exponent);
3221       else
3222         exponent++;
3223     }
3224
3225   while (mant_bits_left > 0)
3226     {
3227       mant_bits = min (mant_bits_left, 32);
3228
3229       mant = get_field (ufrom, fmt->byteorder, fmt->totalsize,
3230                         mant_off, mant_bits);
3231
3232       dto += ldexp ((double) mant, exponent - mant_bits);
3233       exponent -= mant_bits;
3234       mant_off += mant_bits;
3235       mant_bits_left -= mant_bits;
3236     }
3237
3238   /* Negate it if negative.  */
3239   if (get_field (ufrom, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1))
3240     dto = -dto;
3241   *to = dto;
3242 }
3243 \f
3244 static void put_field PARAMS ((unsigned char *, enum floatformat_byteorders,
3245                                unsigned int,
3246                                unsigned int,
3247                                unsigned int,
3248                                unsigned long));
3249
3250 /* Set a field which starts at START and is LEN bytes long.  DATA and
3251    TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
3252 static void
3253 put_field (data, order, total_len, start, len, stuff_to_put)
3254      unsigned char *data;
3255      enum floatformat_byteorders order;
3256      unsigned int total_len;
3257      unsigned int start;
3258      unsigned int len;
3259      unsigned long stuff_to_put;
3260 {
3261   unsigned int cur_byte;
3262   int cur_bitshift;
3263
3264   /* Start at the least significant part of the field.  */
3265   cur_byte = (start + len) / FLOATFORMAT_CHAR_BIT;
3266   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3267     cur_byte = (total_len / FLOATFORMAT_CHAR_BIT) - cur_byte - 1;
3268   cur_bitshift =
3269     ((start + len) % FLOATFORMAT_CHAR_BIT) - FLOATFORMAT_CHAR_BIT;
3270   *(data + cur_byte) &=
3271     ~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1) << (-cur_bitshift));
3272   *(data + cur_byte) |=
3273     (stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
3274   cur_bitshift += FLOATFORMAT_CHAR_BIT;
3275   if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3276     ++cur_byte;
3277   else
3278     --cur_byte;
3279
3280   /* Move towards the most significant part of the field.  */
3281   while (cur_bitshift < len)
3282     {
3283       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
3284         {
3285           /* This is the last byte.  */
3286           *(data + cur_byte) &=
3287             ~((1 << (len - cur_bitshift)) - 1);
3288           *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
3289         }
3290       else
3291         *(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
3292                               & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
3293       cur_bitshift += FLOATFORMAT_CHAR_BIT;
3294       if (order == floatformat_little || order == floatformat_littlebyte_bigword)
3295         ++cur_byte;
3296       else
3297         --cur_byte;
3298     }
3299 }
3300
3301 #ifdef HAVE_LONG_DOUBLE
3302 /* Return the fractional part of VALUE, and put the exponent of VALUE in *EPTR.
3303    The range of the returned value is >= 0.5 and < 1.0.  This is equivalent to
3304    frexp, but operates on the long double data type.  */
3305
3306 static long double ldfrexp PARAMS ((long double value, int *eptr));
3307
3308 static long double
3309 ldfrexp (value, eptr)
3310      long double value;
3311      int *eptr;
3312 {
3313   long double tmp;
3314   int exp;
3315
3316   /* Unfortunately, there are no portable functions for extracting the exponent
3317      of a long double, so we have to do it iteratively by multiplying or dividing
3318      by two until the fraction is between 0.5 and 1.0.  */
3319
3320   if (value < 0.0l)
3321     value = -value;
3322
3323   tmp = 1.0l;
3324   exp = 0;
3325
3326   if (value >= tmp)             /* Value >= 1.0 */
3327     while (value >= tmp)
3328       {
3329         tmp *= 2.0l;
3330         exp++;
3331       }
3332   else if (value != 0.0l)       /* Value < 1.0  and > 0.0 */
3333     {
3334       while (value < tmp)
3335         {
3336           tmp /= 2.0l;
3337           exp--;
3338         }
3339       tmp *= 2.0l;
3340       exp++;
3341     }
3342
3343   *eptr = exp;
3344   return value / tmp;
3345 }
3346 #endif /* HAVE_LONG_DOUBLE */
3347
3348
3349 /* The converse: convert the DOUBLEST *FROM to an extended float
3350    and store where TO points.  Neither FROM nor TO have any alignment
3351    restrictions.  */
3352
3353 void
3354 floatformat_from_doublest (fmt, from, to)
3355      CONST struct floatformat *fmt;
3356      DOUBLEST *from;
3357      char *to;
3358 {
3359   DOUBLEST dfrom;
3360   int exponent;
3361   DOUBLEST mant;
3362   unsigned int mant_bits, mant_off;
3363   int mant_bits_left;
3364   unsigned char *uto = (unsigned char *) to;
3365
3366   memcpy (&dfrom, from, sizeof (dfrom));
3367   memset (uto, 0, fmt->totalsize / FLOATFORMAT_CHAR_BIT);
3368   if (dfrom == 0)
3369     return;                     /* Result is zero */
3370   if (dfrom != dfrom)           /* Result is NaN */
3371     {
3372       /* From is NaN */
3373       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3374                  fmt->exp_len, fmt->exp_nan);
3375       /* Be sure it's not infinity, but NaN value is irrel */
3376       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3377                  32, 1);
3378       return;
3379     }
3380
3381   /* If negative, set the sign bit.  */
3382   if (dfrom < 0)
3383     {
3384       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->sign_start, 1, 1);
3385       dfrom = -dfrom;
3386     }
3387
3388   if (dfrom + dfrom == dfrom && dfrom != 0.0)   /* Result is Infinity */
3389     {
3390       /* Infinity exponent is same as NaN's.  */
3391       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start,
3392                  fmt->exp_len, fmt->exp_nan);
3393       /* Infinity mantissa is all zeroes.  */
3394       put_field (uto, fmt->byteorder, fmt->totalsize, fmt->man_start,
3395                  fmt->man_len, 0);
3396       return;
3397     }
3398
3399 #ifdef HAVE_LONG_DOUBLE
3400   mant = ldfrexp (dfrom, &exponent);
3401 #else
3402   mant = frexp (dfrom, &exponent);
3403 #endif
3404
3405   put_field (uto, fmt->byteorder, fmt->totalsize, fmt->exp_start, fmt->exp_len,
3406              exponent + fmt->exp_bias - 1);
3407
3408   mant_bits_left = fmt->man_len;
3409   mant_off = fmt->man_start;
3410   while (mant_bits_left > 0)
3411     {
3412       unsigned long mant_long;
3413       mant_bits = mant_bits_left < 32 ? mant_bits_left : 32;
3414
3415       mant *= 4294967296.0;
3416       mant_long = (unsigned long) mant;
3417       mant -= mant_long;
3418
3419       /* If the integer bit is implicit, then we need to discard it.
3420          If we are discarding a zero, we should be (but are not) creating
3421          a denormalized number which means adjusting the exponent
3422          (I think).  */
3423       if (mant_bits_left == fmt->man_len
3424           && fmt->intbit == floatformat_intbit_no)
3425         {
3426           mant_long <<= 1;
3427           mant_bits -= 1;
3428         }
3429
3430       if (mant_bits < 32)
3431         {
3432           /* The bits we want are in the most significant MANT_BITS bits of
3433              mant_long.  Move them to the least significant.  */
3434           mant_long >>= 32 - mant_bits;
3435         }
3436
3437       put_field (uto, fmt->byteorder, fmt->totalsize,
3438                  mant_off, mant_bits, mant_long);
3439       mant_off += mant_bits;
3440       mant_bits_left -= mant_bits;
3441     }
3442   if (fmt->byteorder == floatformat_littlebyte_bigword)
3443     {
3444       int count;
3445       unsigned char *swaplow = uto;
3446       unsigned char *swaphigh = uto + 4;
3447       unsigned char tmp;
3448
3449       for (count = 0; count < 4; count++)
3450         {
3451           tmp = *swaplow;
3452           *swaplow++ = *swaphigh;
3453           *swaphigh++ = tmp;
3454         }
3455     }
3456 }
3457
3458 /* temporary storage using circular buffer */
3459 #define NUMCELLS 16
3460 #define CELLSIZE 32
3461 static char *
3462 get_cell ()
3463 {
3464   static char buf[NUMCELLS][CELLSIZE];
3465   static int cell = 0;
3466   if (++cell >= NUMCELLS)
3467     cell = 0;
3468   return buf[cell];
3469 }
3470
3471 /* print routines to handle variable size regs, etc.
3472
3473    FIXME: Note that t_addr is a bfd_vma, which is currently either an
3474    unsigned long or unsigned long long, determined at configure time.
3475    If t_addr is an unsigned long long and sizeof (unsigned long long)
3476    is greater than sizeof (unsigned long), then I believe this code will
3477    probably lose, at least for little endian machines.  I believe that
3478    it would also be better to eliminate the switch on the absolute size
3479    of t_addr and replace it with a sequence of if statements that compare
3480    sizeof t_addr with sizeof the various types and do the right thing,
3481    which includes knowing whether or not the host supports long long.
3482    -fnf
3483
3484  */
3485
3486 int
3487 strlen_paddr (void)
3488 {
3489   return (TARGET_PTR_BIT / 8 * 2);
3490 }
3491
3492
3493 /* eliminate warning from compiler on 32-bit systems */
3494 static int thirty_two = 32;
3495
3496 char *
3497 paddr (CORE_ADDR addr)
3498 {
3499   char *paddr_str = get_cell ();
3500   switch (TARGET_PTR_BIT / 8)
3501     {
3502     case 8:
3503       sprintf (paddr_str, "%08lx%08lx",
3504                (unsigned long) (addr >> thirty_two), (unsigned long) (addr & 0xffffffff));
3505       break;
3506     case 4:
3507       sprintf (paddr_str, "%08lx", (unsigned long) addr);
3508       break;
3509     case 2:
3510       sprintf (paddr_str, "%04x", (unsigned short) (addr & 0xffff));
3511       break;
3512     default:
3513       sprintf (paddr_str, "%lx", (unsigned long) addr);
3514     }
3515   return paddr_str;
3516 }
3517
3518 char *
3519 paddr_nz (CORE_ADDR addr)
3520 {
3521   char *paddr_str = get_cell ();
3522   switch (TARGET_PTR_BIT / 8)
3523     {
3524     case 8:
3525       {
3526         unsigned long high = (unsigned long) (addr >> thirty_two);
3527         if (high == 0)
3528           sprintf (paddr_str, "%lx", (unsigned long) (addr & 0xffffffff));
3529         else
3530           sprintf (paddr_str, "%lx%08lx",
3531                    high, (unsigned long) (addr & 0xffffffff));
3532         break;
3533       }
3534     case 4:
3535       sprintf (paddr_str, "%lx", (unsigned long) addr);
3536       break;
3537     case 2:
3538       sprintf (paddr_str, "%x", (unsigned short) (addr & 0xffff));
3539       break;
3540     default:
3541       sprintf (paddr_str, "%lx", (unsigned long) addr);
3542     }
3543   return paddr_str;
3544 }
3545
3546 static void
3547 decimal2str (char *paddr_str, char *sign, ULONGEST addr)
3548 {
3549   /* steal code from valprint.c:print_decimal().  Should this worry
3550      about the real size of addr as the above does? */
3551   unsigned long temp[3];
3552   int i = 0;
3553   do
3554     {
3555       temp[i] = addr % (1000 * 1000 * 1000);
3556       addr /= (1000 * 1000 * 1000);
3557       i++;
3558     }
3559   while (addr != 0 && i < (sizeof (temp) / sizeof (temp[0])));
3560   switch (i)
3561     {
3562     case 1:
3563       sprintf (paddr_str, "%s%lu",
3564                sign, temp[0]);
3565       break;
3566     case 2:
3567       sprintf (paddr_str, "%s%lu%09lu",
3568                sign, temp[1], temp[0]);
3569       break;
3570     case 3:
3571       sprintf (paddr_str, "%s%lu%09lu%09lu",
3572                sign, temp[2], temp[1], temp[0]);
3573       break;
3574     default:
3575       abort ();
3576     }
3577 }
3578
3579 char *
3580 paddr_u (CORE_ADDR addr)
3581 {
3582   char *paddr_str = get_cell ();
3583   decimal2str (paddr_str, "", addr);
3584   return paddr_str;
3585 }
3586
3587 char *
3588 paddr_d (LONGEST addr)
3589 {
3590   char *paddr_str = get_cell ();
3591   if (addr < 0)
3592     decimal2str (paddr_str, "-", -addr);
3593   else
3594     decimal2str (paddr_str, "", addr);
3595   return paddr_str;
3596 }
3597
3598 char *
3599 preg (reg)
3600      t_reg reg;
3601 {
3602   char *preg_str = get_cell ();
3603   switch (sizeof (t_reg))
3604     {
3605     case 8:
3606       sprintf (preg_str, "%08lx%08lx",
3607                (unsigned long) (reg >> thirty_two), (unsigned long) (reg & 0xffffffff));
3608       break;
3609     case 4:
3610       sprintf (preg_str, "%08lx", (unsigned long) reg);
3611       break;
3612     case 2:
3613       sprintf (preg_str, "%04x", (unsigned short) (reg & 0xffff));
3614       break;
3615     default:
3616       sprintf (preg_str, "%lx", (unsigned long) reg);
3617     }
3618   return preg_str;
3619 }
3620
3621 char *
3622 preg_nz (reg)
3623      t_reg reg;
3624 {
3625   char *preg_str = get_cell ();
3626   switch (sizeof (t_reg))
3627     {
3628     case 8:
3629       {
3630         unsigned long high = (unsigned long) (reg >> thirty_two);
3631         if (high == 0)
3632           sprintf (preg_str, "%lx", (unsigned long) (reg & 0xffffffff));
3633         else
3634           sprintf (preg_str, "%lx%08lx",
3635                    high, (unsigned long) (reg & 0xffffffff));
3636         break;
3637       }
3638     case 4:
3639       sprintf (preg_str, "%lx", (unsigned long) reg);
3640       break;
3641     case 2:
3642       sprintf (preg_str, "%x", (unsigned short) (reg & 0xffff));
3643       break;
3644     default:
3645       sprintf (preg_str, "%lx", (unsigned long) reg);
3646     }
3647   return preg_str;
3648 }
3649
3650 /* Helper functions for INNER_THAN */
3651 int
3652 core_addr_lessthan (lhs, rhs)
3653      CORE_ADDR lhs;
3654      CORE_ADDR rhs;
3655 {
3656   return (lhs < rhs);
3657 }
3658
3659 int
3660 core_addr_greaterthan (lhs, rhs)
3661      CORE_ADDR lhs;
3662      CORE_ADDR rhs;
3663 {
3664   return (lhs > rhs);
3665 }