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