2003-04-06 Andrew Cagney <cagney@redhat.com>
[external/binutils.git] / gdb / objc-lang.c
1 /* Objective-C language support routines for GDB, the GNU debugger.
2
3    Copyright 2002, 2003 Free Software Foundation, Inc.
4
5    Contributed by Apple Computer, Inc.
6    Written by Michael Snyder.
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 59 Temple Place - Suite 330,
23    Boston, MA 02111-1307, USA.  */
24
25 #include "defs.h"
26 #include "symtab.h"
27 #include "gdbtypes.h"
28 #include "expression.h"
29 #include "parser-defs.h"
30 #include "language.h"
31 #include "c-lang.h"
32 #include "objc-lang.h"
33 #include "complaints.h"
34 #include "value.h"
35 #include "symfile.h"
36 #include "objfiles.h"
37 #include "gdb_string.h"         /* for strchr */
38 #include "target.h"             /* for target_has_execution */
39 #include "gdbcore.h"
40 #include "gdbcmd.h"
41 #include "frame.h"
42 #include "gdb_regex.h"
43 #include "regcache.h"
44 #include "block.h"
45
46 #include <ctype.h>
47
48 struct objc_object {
49   CORE_ADDR isa;
50 };
51
52 struct objc_class {
53   CORE_ADDR isa; 
54   CORE_ADDR super_class; 
55   CORE_ADDR name;               
56   long version;
57   long info;
58   long instance_size;
59   CORE_ADDR ivars;
60   CORE_ADDR methods;
61   CORE_ADDR cache;
62   CORE_ADDR protocols;
63 };
64
65 struct objc_super {
66   CORE_ADDR receiver;
67   CORE_ADDR class;
68 };
69
70 struct objc_method {
71   CORE_ADDR name;
72   CORE_ADDR types;
73   CORE_ADDR imp;
74 };
75
76 /* Complaints about ObjC classes, selectors, etc.  */
77
78 #if (!defined __GNUC__ || __GNUC__ < 2 || __GNUC_MINOR__ < (defined __cplusplus ? 6 : 4))
79 #define __CHECK_FUNCTION ((__const char *) 0)
80 #else
81 #define __CHECK_FUNCTION __PRETTY_FUNCTION__
82 #endif
83
84 #define CHECK(expression) \
85   ((void) ((expression) ? 0 : gdb_check (#expression, __FILE__, __LINE__, \
86                                          __CHECK_FUNCTION)))
87
88 #define CHECK_FATAL(expression) \
89   ((void) ((expression) ? 0 : gdb_check_fatal (#expression, __FILE__, \
90                               __LINE__, __CHECK_FUNCTION)))
91
92 static void 
93 gdb_check (const char *str, const char *file, 
94            unsigned int line, const char *func)
95 {
96   error ("assertion failure on line %u of \"%s\" in function \"%s\": %s\n",
97          line, file, func, str);
98 }
99
100 static void 
101 gdb_check_fatal (const char *str, const char *file, 
102                  unsigned int line, const char *func)
103 {
104   internal_error (file, line, 
105                   "assertion failure in function \"%s\": %s\n", func, str);
106 }
107
108 /* Lookup a structure type named "struct NAME", visible in lexical
109    block BLOCK.  If NOERR is nonzero, return zero if NAME is not
110    suitably defined.  */
111
112 struct symbol *
113 lookup_struct_typedef (char *name, struct block *block, int noerr)
114 {
115   register struct symbol *sym;
116
117   sym = lookup_symbol (name, block, STRUCT_NAMESPACE, 0, 
118                        (struct symtab **) NULL);
119
120   if (sym == NULL)
121     {
122       if (noerr)
123         return 0;
124       else 
125         error ("No struct type named %s.", name);
126     }
127   if (TYPE_CODE (SYMBOL_TYPE (sym)) != TYPE_CODE_STRUCT)
128     {
129       if (noerr)
130         return 0;
131       else
132         error ("This context has class, union or enum %s, not a struct.", 
133                name);
134     }
135   return sym;
136 }
137
138 CORE_ADDR 
139 lookup_objc_class (char *classname)
140 {
141   struct value * function, *classval;
142
143   if (! target_has_execution)
144     {
145       /* Can't call into inferior to lookup class.  */
146       return 0;
147     }
148
149   if (lookup_minimal_symbol("objc_lookUpClass", 0, 0))
150     function = find_function_in_inferior("objc_lookUpClass");
151   else if (lookup_minimal_symbol ("objc_lookup_class", 0, 0))
152     function = find_function_in_inferior("objc_lookup_class");
153   else
154     {
155       complaint (&symfile_complaints, "no way to lookup Objective-C classes");
156       return 0;
157     }
158
159   classval = value_string (classname, strlen (classname) + 1);
160   classval = value_coerce_array (classval);
161   return (CORE_ADDR) value_as_long (call_function_by_hand (function, 
162                                                            1, &classval));
163 }
164
165 int
166 lookup_child_selector (char *selname)
167 {
168   struct value * function, *selstring;
169
170   if (! target_has_execution)
171     {
172       /* Can't call into inferior to lookup selector.  */
173       return 0;
174     }
175
176   if (lookup_minimal_symbol("sel_getUid", 0, 0))
177     function = find_function_in_inferior("sel_getUid");
178   else if (lookup_minimal_symbol ("sel_get_any_uid", 0, 0))
179     function = find_function_in_inferior("sel_get_any_uid");
180   else
181     {
182       complaint (&symfile_complaints, "no way to lookup Objective-C selectors");
183       return 0;
184     }
185
186   selstring = value_coerce_array (value_string (selname, 
187                                                 strlen (selname) + 1));
188   return value_as_long (call_function_by_hand (function, 1, &selstring));
189 }
190
191 struct value * 
192 value_nsstring (char *ptr, int len)
193 {
194   struct value *stringValue[3];
195   struct value *function, *nsstringValue;
196   struct symbol *sym;
197   struct type *type;
198
199   if (!target_has_execution)
200     return 0;           /* Can't call into inferior to create NSString.  */
201
202   sym = lookup_struct_typedef("NSString", 0, 1);
203   if (sym == NULL)
204     sym = lookup_struct_typedef("NXString", 0, 1);
205   if (sym == NULL)
206     type = lookup_pointer_type(builtin_type_void);
207   else
208     type = lookup_pointer_type(SYMBOL_TYPE (sym));
209
210   stringValue[2] = value_string(ptr, len);
211   stringValue[2] = value_coerce_array(stringValue[2]);
212   /* _NSNewStringFromCString replaces "istr" after Lantern2A.  */
213   if (lookup_minimal_symbol("_NSNewStringFromCString", 0, 0))
214     {
215       function = find_function_in_inferior("_NSNewStringFromCString");
216       nsstringValue = call_function_by_hand(function, 1, &stringValue[2]);
217     }
218   else if (lookup_minimal_symbol("istr", 0, 0))
219     {
220       function = find_function_in_inferior("istr");
221       nsstringValue = call_function_by_hand(function, 1, &stringValue[2]);
222     }
223   else if (lookup_minimal_symbol("+[NSString stringWithCString:]", 0, 0))
224     {
225       function = find_function_in_inferior("+[NSString stringWithCString:]");
226       stringValue[0] = value_from_longest 
227         (builtin_type_long, lookup_objc_class ("NSString"));
228       stringValue[1] = value_from_longest 
229         (builtin_type_long, lookup_child_selector ("stringWithCString:"));
230       nsstringValue = call_function_by_hand(function, 3, &stringValue[0]);
231     }
232   else
233     error ("NSString: internal error -- no way to create new NSString");
234
235   VALUE_TYPE(nsstringValue) = type;
236   return nsstringValue;
237 }
238
239 /* Objective-C name demangling.  */
240
241 char *
242 objc_demangle (const char *mangled, int options)
243 {
244   char *demangled, *cp;
245
246   if (mangled[0] == '_' &&
247      (mangled[1] == 'i' || mangled[1] == 'c') &&
248       mangled[2] == '_')
249     {
250       cp = demangled = xmalloc(strlen(mangled) + 2);
251
252       if (mangled[1] == 'i')
253         *cp++ = '-';            /* for instance method */
254       else
255         *cp++ = '+';            /* for class    method */
256
257       *cp++ = '[';              /* opening left brace  */
258       strcpy(cp, mangled+3);    /* tack on the rest of the mangled name */
259
260       while (*cp && *cp == '_')
261         cp++;                   /* skip any initial underbars in class name */
262
263       cp = strchr(cp, '_');
264       if (!cp)                  /* find first non-initial underbar */
265         {
266           xfree(demangled);     /* not mangled name */
267           return NULL;
268         }
269       if (cp[1] == '_') {       /* easy case: no category name     */
270         *cp++ = ' ';            /* replace two '_' with one ' '    */
271         strcpy(cp, mangled + (cp - demangled) + 2);
272       }
273       else {
274         *cp++ = '(';            /* less easy case: category name */
275         cp = strchr(cp, '_');
276         if (!cp)
277           {
278             xfree(demangled);   /* not mangled name */
279             return NULL;
280           }
281         *cp++ = ')';
282         *cp++ = ' ';            /* overwriting 1st char of method name...  */
283         strcpy(cp, mangled + (cp - demangled)); /* get it back */
284       }
285
286       while (*cp && *cp == '_')
287         cp++;                   /* skip any initial underbars in method name */
288
289       for (; *cp; cp++)
290         if (*cp == '_')
291           *cp = ':';            /* replace remaining '_' with ':' */
292
293       *cp++ = ']';              /* closing right brace */
294       *cp++ = 0;                /* string terminator */
295       return demangled;
296     }
297   else
298     return NULL;        /* Not an objc mangled name.  */
299 }
300
301 /* Print the character C on STREAM as part of the contents of a
302    literal string whose delimiter is QUOTER.  Note that that format
303    for printing characters and strings is language specific.  */
304
305 static void
306 objc_emit_char (register int c, struct ui_file *stream, int quoter)
307 {
308
309   c &= 0xFF;                    /* Avoid sign bit follies.  */
310
311   if (PRINT_LITERAL_FORM (c))
312     {
313       if (c == '\\' || c == quoter)
314         {
315           fputs_filtered ("\\", stream);
316         }
317       fprintf_filtered (stream, "%c", c);
318     }
319   else
320     {
321       switch (c)
322         {
323         case '\n':
324           fputs_filtered ("\\n", stream);
325           break;
326         case '\b':
327           fputs_filtered ("\\b", stream);
328           break;
329         case '\t':
330           fputs_filtered ("\\t", stream);
331           break;
332         case '\f':
333           fputs_filtered ("\\f", stream);
334           break;
335         case '\r':
336           fputs_filtered ("\\r", stream);
337           break;
338         case '\033':
339           fputs_filtered ("\\e", stream);
340           break;
341         case '\007':
342           fputs_filtered ("\\a", stream);
343           break;
344         default:
345           fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
346           break;
347         }
348     }
349 }
350
351 static void
352 objc_printchar (int c, struct ui_file *stream)
353 {
354   fputs_filtered ("'", stream);
355   objc_emit_char (c, stream, '\'');
356   fputs_filtered ("'", stream);
357 }
358
359 /* Print the character string STRING, printing at most LENGTH
360    characters.  Printing stops early if the number hits print_max;
361    repeat counts are printed as appropriate.  Print ellipses at the
362    end if we had to stop before printing LENGTH characters, or if
363    FORCE_ELLIPSES.  */
364
365 static void
366 objc_printstr (struct ui_file *stream, char *string, 
367                unsigned int length, int width, int force_ellipses)
368 {
369   register unsigned int i;
370   unsigned int things_printed = 0;
371   int in_quotes = 0;
372   int need_comma = 0;
373   extern int inspect_it;
374
375   /* If the string was not truncated due to `set print elements', and
376      the last byte of it is a null, we don't print that, in
377      traditional C style.  */
378   if ((!force_ellipses) && length > 0 && string[length-1] == '\0')
379     length--;
380
381   if (length == 0)
382     {
383       fputs_filtered ("\"\"", stream);
384       return;
385     }
386
387   for (i = 0; i < length && things_printed < print_max; ++i)
388     {
389       /* Position of the character we are examining to see whether it
390          is repeated.  */
391       unsigned int rep1;
392       /* Number of repetitions we have detected so far.  */
393       unsigned int reps;
394
395       QUIT;
396
397       if (need_comma)
398         {
399           fputs_filtered (", ", stream);
400           need_comma = 0;
401         }
402
403       rep1 = i + 1;
404       reps = 1;
405       while (rep1 < length && string[rep1] == string[i])
406         {
407           ++rep1;
408           ++reps;
409         }
410
411       if (reps > repeat_count_threshold)
412         {
413           if (in_quotes)
414             {
415               if (inspect_it)
416                 fputs_filtered ("\\\", ", stream);
417               else
418                 fputs_filtered ("\", ", stream);
419               in_quotes = 0;
420             }
421           objc_printchar (string[i], stream);
422           fprintf_filtered (stream, " <repeats %u times>", reps);
423           i = rep1 - 1;
424           things_printed += repeat_count_threshold;
425           need_comma = 1;
426         }
427       else
428         {
429           if (!in_quotes)
430             {
431               if (inspect_it)
432                 fputs_filtered ("\\\"", stream);
433               else
434                 fputs_filtered ("\"", stream);
435               in_quotes = 1;
436             }
437           objc_emit_char (string[i], stream, '"');
438           ++things_printed;
439         }
440     }
441
442   /* Terminate the quotes if necessary.  */
443   if (in_quotes)
444     {
445       if (inspect_it)
446         fputs_filtered ("\\\"", stream);
447       else
448         fputs_filtered ("\"", stream);
449     }
450
451   if (force_ellipses || i < length)
452     fputs_filtered ("...", stream);
453 }
454
455 /* Create a fundamental C type using default reasonable for the
456    current target.
457
458    Some object/debugging file formats (DWARF version 1, COFF, etc) do
459    not define fundamental types such as "int" or "double".  Others
460    (stabs or DWARF version 2, etc) do define fundamental types.  For
461    the formats which don't provide fundamental types, gdb can create
462    such types using this function.
463
464    FIXME: Some compilers distinguish explicitly signed integral types
465    (signed short, signed int, signed long) from "regular" integral
466    types (short, int, long) in the debugging information.  There is
467    some disagreement as to how useful this feature is.  In particular,
468    gcc does not support this.  Also, only some debugging formats allow
469    the distinction to be passed on to a debugger.  For now, we always
470    just use "short", "int", or "long" as the type name, for both the
471    implicit and explicitly signed types.  This also makes life easier
472    for the gdb test suite since we don't have to account for the
473    differences in output depending upon what the compiler and
474    debugging format support.  We will probably have to re-examine the
475    issue when gdb starts taking it's fundamental type information
476    directly from the debugging information supplied by the compiler.
477    fnf@cygnus.com */
478
479 static struct type *
480 objc_create_fundamental_type (struct objfile *objfile, int typeid)
481 {
482   register struct type *type = NULL;
483
484   switch (typeid)
485     {
486       default:
487         /* FIXME: For now, if we are asked to produce a type not in
488            this language, create the equivalent of a C integer type
489            with the name "<?type?>".  When all the dust settles from
490            the type reconstruction work, this should probably become
491            an error.  */
492         type = init_type (TYPE_CODE_INT,
493                           TARGET_INT_BIT / TARGET_CHAR_BIT,
494                           0, "<?type?>", objfile);
495         warning ("internal error: no C/C++ fundamental type %d", typeid);
496         break;
497       case FT_VOID:
498         type = init_type (TYPE_CODE_VOID,
499                           TARGET_CHAR_BIT / TARGET_CHAR_BIT,
500                           0, "void", objfile);
501         break;
502       case FT_CHAR:
503         type = init_type (TYPE_CODE_INT,
504                           TARGET_CHAR_BIT / TARGET_CHAR_BIT,
505                           0, "char", objfile);
506         break;
507       case FT_SIGNED_CHAR:
508         type = init_type (TYPE_CODE_INT,
509                           TARGET_CHAR_BIT / TARGET_CHAR_BIT,
510                           0, "signed char", objfile);
511         break;
512       case FT_UNSIGNED_CHAR:
513         type = init_type (TYPE_CODE_INT,
514                           TARGET_CHAR_BIT / TARGET_CHAR_BIT,
515                           TYPE_FLAG_UNSIGNED, "unsigned char", objfile);
516         break;
517       case FT_SHORT:
518         type = init_type (TYPE_CODE_INT,
519                           TARGET_SHORT_BIT / TARGET_CHAR_BIT,
520                           0, "short", objfile);
521         break;
522       case FT_SIGNED_SHORT:
523         type = init_type (TYPE_CODE_INT,
524                           TARGET_SHORT_BIT / TARGET_CHAR_BIT,
525                           0, "short", objfile); /* FIXME-fnf */
526         break;
527       case FT_UNSIGNED_SHORT:
528         type = init_type (TYPE_CODE_INT,
529                           TARGET_SHORT_BIT / TARGET_CHAR_BIT,
530                           TYPE_FLAG_UNSIGNED, "unsigned short", objfile);
531         break;
532       case FT_INTEGER:
533         type = init_type (TYPE_CODE_INT,
534                           TARGET_INT_BIT / TARGET_CHAR_BIT,
535                           0, "int", objfile);
536         break;
537       case FT_SIGNED_INTEGER:
538         type = init_type (TYPE_CODE_INT,
539                           TARGET_INT_BIT / TARGET_CHAR_BIT,
540                           0, "int", objfile); /* FIXME -fnf */
541         break;
542       case FT_UNSIGNED_INTEGER:
543         type = init_type (TYPE_CODE_INT,
544                           TARGET_INT_BIT / TARGET_CHAR_BIT,
545                           TYPE_FLAG_UNSIGNED, "unsigned int", objfile);
546         break;
547       case FT_LONG:
548         type = init_type (TYPE_CODE_INT,
549                           TARGET_LONG_BIT / TARGET_CHAR_BIT,
550                           0, "long", objfile);
551         break;
552       case FT_SIGNED_LONG:
553         type = init_type (TYPE_CODE_INT,
554                           TARGET_LONG_BIT / TARGET_CHAR_BIT,
555                           0, "long", objfile); /* FIXME -fnf */
556         break;
557       case FT_UNSIGNED_LONG:
558         type = init_type (TYPE_CODE_INT,
559                           TARGET_LONG_BIT / TARGET_CHAR_BIT,
560                           TYPE_FLAG_UNSIGNED, "unsigned long", objfile);
561         break;
562       case FT_LONG_LONG:
563         type = init_type (TYPE_CODE_INT,
564                           TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
565                           0, "long long", objfile);
566         break;
567       case FT_SIGNED_LONG_LONG:
568         type = init_type (TYPE_CODE_INT,
569                           TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
570                           0, "signed long long", objfile);
571         break;
572       case FT_UNSIGNED_LONG_LONG:
573         type = init_type (TYPE_CODE_INT,
574                           TARGET_LONG_LONG_BIT / TARGET_CHAR_BIT,
575                           TYPE_FLAG_UNSIGNED, "unsigned long long", objfile);
576         break;
577       case FT_FLOAT:
578         type = init_type (TYPE_CODE_FLT,
579                           TARGET_FLOAT_BIT / TARGET_CHAR_BIT,
580                           0, "float", objfile);
581         break;
582       case FT_DBL_PREC_FLOAT:
583         type = init_type (TYPE_CODE_FLT,
584                           TARGET_DOUBLE_BIT / TARGET_CHAR_BIT,
585                           0, "double", objfile);
586         break;
587       case FT_EXT_PREC_FLOAT:
588         type = init_type (TYPE_CODE_FLT,
589                           TARGET_LONG_DOUBLE_BIT / TARGET_CHAR_BIT,
590                           0, "long double", objfile);
591         break;
592       }
593   return (type);
594 }
595
596 /* Determine if we are currently in the Objective-C dispatch function.
597    If so, get the address of the method function that the dispatcher
598    would call and use that as the function to step into instead. Also
599    skip over the trampoline for the function (if any).  This is better
600    for the user since they are only interested in stepping into the
601    method function anyway.  */
602 static CORE_ADDR 
603 objc_skip_trampoline (CORE_ADDR stop_pc)
604 {
605   CORE_ADDR real_stop_pc;
606   CORE_ADDR method_stop_pc;
607   
608   real_stop_pc = SKIP_TRAMPOLINE_CODE (stop_pc);
609
610   if (real_stop_pc != 0)
611     find_objc_msgcall (real_stop_pc, &method_stop_pc);
612   else
613     find_objc_msgcall (stop_pc, &method_stop_pc);
614
615   if (method_stop_pc)
616     {
617       real_stop_pc = SKIP_TRAMPOLINE_CODE (method_stop_pc);
618       if (real_stop_pc == 0)
619         real_stop_pc = method_stop_pc;
620     }
621
622   return real_stop_pc;
623 }
624
625
626 /* Table mapping opcodes into strings for printing operators
627    and precedences of the operators.  */
628
629 static const struct op_print objc_op_print_tab[] =
630   {
631     {",",  BINOP_COMMA, PREC_COMMA, 0},
632     {"=",  BINOP_ASSIGN, PREC_ASSIGN, 1},
633     {"||", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
634     {"&&", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
635     {"|",  BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
636     {"^",  BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
637     {"&",  BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
638     {"==", BINOP_EQUAL, PREC_EQUAL, 0},
639     {"!=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
640     {"<=", BINOP_LEQ, PREC_ORDER, 0},
641     {">=", BINOP_GEQ, PREC_ORDER, 0},
642     {">",  BINOP_GTR, PREC_ORDER, 0},
643     {"<",  BINOP_LESS, PREC_ORDER, 0},
644     {">>", BINOP_RSH, PREC_SHIFT, 0},
645     {"<<", BINOP_LSH, PREC_SHIFT, 0},
646     {"+",  BINOP_ADD, PREC_ADD, 0},
647     {"-",  BINOP_SUB, PREC_ADD, 0},
648     {"*",  BINOP_MUL, PREC_MUL, 0},
649     {"/",  BINOP_DIV, PREC_MUL, 0},
650     {"%",  BINOP_REM, PREC_MUL, 0},
651     {"@",  BINOP_REPEAT, PREC_REPEAT, 0},
652     {"-",  UNOP_NEG, PREC_PREFIX, 0},
653     {"!",  UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
654     {"~",  UNOP_COMPLEMENT, PREC_PREFIX, 0},
655     {"*",  UNOP_IND, PREC_PREFIX, 0},
656     {"&",  UNOP_ADDR, PREC_PREFIX, 0},
657     {"sizeof ", UNOP_SIZEOF, PREC_PREFIX, 0},
658     {"++", UNOP_PREINCREMENT, PREC_PREFIX, 0},
659     {"--", UNOP_PREDECREMENT, PREC_PREFIX, 0},
660     {NULL, 0, 0, 0}
661 };
662
663 struct type ** const (objc_builtin_types[]) = 
664 {
665   &builtin_type_int,
666   &builtin_type_long,
667   &builtin_type_short,
668   &builtin_type_char,
669   &builtin_type_float,
670   &builtin_type_double,
671   &builtin_type_void,
672   &builtin_type_long_long,
673   &builtin_type_signed_char,
674   &builtin_type_unsigned_char,
675   &builtin_type_unsigned_short,
676   &builtin_type_unsigned_int,
677   &builtin_type_unsigned_long,
678   &builtin_type_unsigned_long_long,
679   &builtin_type_long_double,
680   &builtin_type_complex,
681   &builtin_type_double_complex,
682   0
683 };
684
685 const struct language_defn objc_language_defn = {
686   "objective-c",                /* Language name */
687   language_objc,
688   objc_builtin_types,
689   range_check_off,
690   type_check_off,
691   case_sensitive_on,
692   objc_parse,
693   objc_error,
694   evaluate_subexp_standard,
695   objc_printchar,               /* Print a character constant */
696   objc_printstr,                /* Function to print string constant */
697   objc_emit_char,
698   objc_create_fundamental_type, /* Create fundamental type in this language */
699   c_print_type,                 /* Print a type using appropriate syntax */
700   c_val_print,                  /* Print a value using appropriate syntax */
701   c_value_print,                /* Print a top-level value */
702   objc_skip_trampoline,         /* Language specific skip_trampoline */
703   objc_demangle,                /* Language specific symbol demangler */
704   {"",     "",    "",  ""},     /* Binary format info */
705   {"0%lo",  "0",   "o", ""},    /* Octal format info */
706   {"%ld",   "",    "d", ""},    /* Decimal format info */
707   {"0x%lx", "0x",  "x", ""},    /* Hex format info */
708   objc_op_print_tab,            /* Expression operators for printing */
709   1,                            /* C-style arrays */
710   0,                            /* String lower bound */
711   &builtin_type_char,           /* Type of string elements */
712   LANG_MAGIC
713 };
714
715 /*
716  * ObjC:
717  * Following functions help construct Objective-C message calls 
718  */
719
720 struct selname          /* For parsing Objective-C.  */
721   {
722     struct selname *next;
723     char *msglist_sel;
724     int msglist_len;
725   };
726
727 static int msglist_len;
728 static struct selname *selname_chain;
729 static char *msglist_sel;
730
731 void
732 start_msglist(void)
733 {
734   register struct selname *new = 
735     (struct selname *) xmalloc (sizeof (struct selname));
736
737   new->next = selname_chain;
738   new->msglist_len = msglist_len;
739   new->msglist_sel = msglist_sel;
740   msglist_len = 0;
741   msglist_sel = (char *)xmalloc(1);
742   *msglist_sel = 0;
743   selname_chain = new;
744 }
745
746 void
747 add_msglist(struct stoken *str, int addcolon)
748 {
749   char *s, *p;
750   int len, plen;
751
752   if (str == 0) {               /* Unnamed arg, or...  */
753     if (addcolon == 0) {        /* variable number of args.  */
754       msglist_len++;
755       return;
756     }
757     p = "";
758     plen = 0;
759   } else {
760     p = str->ptr;
761     plen = str->length;
762   }
763   len = plen + strlen(msglist_sel) + 2;
764   s = (char *)xmalloc(len);
765   strcpy(s, msglist_sel);
766   strncat(s, p, plen);
767   xfree(msglist_sel);
768   msglist_sel = s;
769   if (addcolon) {
770     s[len-2] = ':';
771     s[len-1] = 0;
772     msglist_len++;
773   } else
774     s[len-2] = '\0';
775 }
776
777 int
778 end_msglist(void)
779 {
780   register int val = msglist_len;
781   register struct selname *sel = selname_chain;
782   register char *p = msglist_sel;
783   int selid;
784
785   selname_chain = sel->next;
786   msglist_len = sel->msglist_len;
787   msglist_sel = sel->msglist_sel;
788   selid = lookup_child_selector(p);
789   if (!selid)
790     error("Can't find selector \"%s\"", p);
791   write_exp_elt_longcst (selid);
792   xfree(p);
793   write_exp_elt_longcst (val);  /* Number of args */
794   xfree(sel);
795
796   return val;
797 }
798
799 /*
800  * Function: specialcmp (char *a, char *b)
801  *
802  * Special strcmp: treats ']' and ' ' as end-of-string.
803  * Used for qsorting lists of objc methods (either by class or selector).
804  */
805
806 int specialcmp(char *a, char *b)
807 {
808   while (*a && *a != ' ' && *a != ']' && *b && *b != ' ' && *b != ']')
809     {
810       if (*a != *b)
811         return *a - *b;
812       a++, b++;
813     }
814   if (*a && *a != ' ' && *a != ']')
815     return  1;          /* a is longer therefore greater */
816   if (*b && *b != ' ' && *b != ']')
817     return -1;          /* a is shorter therefore lesser */
818   return    0;          /* a and b are identical */
819 }
820
821 /*
822  * Function: compare_selectors (const void *, const void *)
823  *
824  * Comparison function for use with qsort.  Arguments are symbols or
825  * msymbols Compares selector part of objc method name alphabetically.
826  */
827
828 static int
829 compare_selectors (const void *a, const void *b)
830 {
831   char *aname, *bname;
832
833   aname = SYMBOL_PRINT_NAME (*(struct symbol **) a);
834   bname = SYMBOL_PRINT_NAME (*(struct symbol **) b);
835   if (aname == NULL || bname == NULL)
836     error ("internal: compare_selectors(1)");
837
838   aname = strchr(aname, ' ');
839   bname = strchr(bname, ' ');
840   if (aname == NULL || bname == NULL)
841     error ("internal: compare_selectors(2)");
842
843   return specialcmp (aname+1, bname+1);
844 }
845
846 /*
847  * Function: selectors_info (regexp, from_tty)
848  *
849  * Implements the "Info selectors" command.  Takes an optional regexp
850  * arg.  Lists all objective c selectors that match the regexp.  Works
851  * by grepping thru all symbols for objective c methods.  Output list
852  * is sorted and uniqued. 
853  */
854
855 static void
856 selectors_info (char *regexp, int from_tty)
857 {
858   struct objfile        *objfile;
859   struct minimal_symbol *msymbol;
860   char                  *name;
861   char                  *val;
862   int                    matches = 0;
863   int                    maxlen  = 0;
864   int                    ix;
865   char                   myregexp[2048];
866   char                   asel[256];
867   struct symbol        **sym_arr;
868   int                    plusminus = 0;
869
870   if (regexp == NULL)
871     strcpy(myregexp, ".*]");    /* Null input, match all objc methods.  */
872   else
873     {
874       if (*regexp == '+' || *regexp == '-')
875         { /* User wants only class methods or only instance methods.  */
876           plusminus = *regexp++;
877           while (*regexp == ' ' || *regexp == '\t')
878             regexp++;
879         }
880       if (*regexp == '\0')
881         strcpy(myregexp, ".*]");
882       else
883         {
884           strcpy(myregexp, regexp);
885           if (myregexp[strlen(myregexp) - 1] == '$') /* end of selector */
886             myregexp[strlen(myregexp) - 1] = ']';    /* end of method name */
887           else
888             strcat(myregexp, ".*]");
889         }
890     }
891
892   if (regexp != NULL)
893     {
894       val = re_comp (myregexp);
895       if (val != 0)
896         error ("Invalid regexp (%s): %s", val, regexp);
897     }
898
899   /* First time thru is JUST to get max length and count.  */
900   ALL_MSYMBOLS (objfile, msymbol)
901     {
902       QUIT;
903       name = SYMBOL_NATURAL_NAME (msymbol);
904       if (name &&
905          (name[0] == '-' || name[0] == '+') &&
906           name[1] == '[')               /* Got a method name.  */
907         {
908           /* Filter for class/instance methods.  */
909           if (plusminus && name[0] != plusminus)
910             continue;
911           /* Find selector part.  */
912           name = (char *) strchr(name+2, ' ');
913           if (regexp == NULL || re_exec(++name) != 0)
914             { 
915               char *mystart = name;
916               char *myend   = (char *) strchr(mystart, ']');
917               
918               if (myend && (myend - mystart > maxlen))
919                 maxlen = myend - mystart;       /* Get longest selector.  */
920               matches++;
921             }
922         }
923     }
924   if (matches)
925     {
926       printf_filtered ("Selectors matching \"%s\":\n\n", 
927                        regexp ? regexp : "*");
928
929       sym_arr = alloca (matches * sizeof (struct symbol *));
930       matches = 0;
931       ALL_MSYMBOLS (objfile, msymbol)
932         {
933           QUIT;
934           name = SYMBOL_NATURAL_NAME (msymbol);
935           if (name &&
936              (name[0] == '-' || name[0] == '+') &&
937               name[1] == '[')           /* Got a method name.  */
938             {
939               /* Filter for class/instance methods.  */
940               if (plusminus && name[0] != plusminus)
941                 continue;
942               /* Find selector part.  */
943               name = (char *) strchr(name+2, ' ');
944               if (regexp == NULL || re_exec(++name) != 0)
945                 sym_arr[matches++] = (struct symbol *) msymbol;
946             }
947         }
948
949       qsort (sym_arr, matches, sizeof (struct minimal_symbol *), 
950              compare_selectors);
951       /* Prevent compare on first iteration.  */
952       asel[0] = 0;
953       for (ix = 0; ix < matches; ix++)  /* Now do the output.  */
954         {
955           char *p = asel;
956
957           QUIT;
958           name = SYMBOL_NATURAL_NAME (sym_arr[ix]);
959           name = strchr (name, ' ') + 1;
960           if (p[0] && specialcmp(name, p) == 0)
961             continue;           /* Seen this one already (not unique).  */
962
963           /* Copy selector part.  */
964           while (*name && *name != ']')
965             *p++ = *name++;
966           *p++ = '\0';
967           /* Print in columns.  */
968           puts_filtered_tabular(asel, maxlen + 1, 0);
969         }
970       begin_line();
971     }
972   else
973     printf_filtered ("No selectors matching \"%s\"\n", regexp ? regexp : "*");
974 }
975
976 /*
977  * Function: compare_classes (const void *, const void *)
978  *
979  * Comparison function for use with qsort.  Arguments are symbols or
980  * msymbols Compares class part of objc method name alphabetically. 
981  */
982
983 static int
984 compare_classes (const void *a, const void *b)
985 {
986   char *aname, *bname;
987
988   aname = SYMBOL_PRINT_NAME (*(struct symbol **) a);
989   bname = SYMBOL_PRINT_NAME (*(struct symbol **) b);
990   if (aname == NULL || bname == NULL)
991     error ("internal: compare_classes(1)");
992
993   return specialcmp (aname+1, bname+1);
994 }
995
996 /*
997  * Function: classes_info(regexp, from_tty)
998  *
999  * Implements the "info classes" command for objective c classes.
1000  * Lists all objective c classes that match the optional regexp.
1001  * Works by grepping thru the list of objective c methods.  List will
1002  * be sorted and uniqued (since one class may have many methods).
1003  * BUGS: will not list a class that has no methods. 
1004  */
1005
1006 static void
1007 classes_info (char *regexp, int from_tty)
1008 {
1009   struct objfile        *objfile;
1010   struct minimal_symbol *msymbol;
1011   char                  *name;
1012   char                  *val;
1013   int                    matches = 0;
1014   int                    maxlen  = 0;
1015   int                    ix;
1016   char                   myregexp[2048];
1017   char                   aclass[256];
1018   struct symbol        **sym_arr;
1019
1020   if (regexp == NULL)
1021     strcpy(myregexp, ".* ");    /* Null input: match all objc classes.  */
1022   else
1023     {
1024       strcpy(myregexp, regexp);
1025       if (myregexp[strlen(myregexp) - 1] == '$')
1026         /* In the method name, the end of the class name is marked by ' '.  */
1027         myregexp[strlen(myregexp) - 1] = ' ';
1028       else
1029         strcat(myregexp, ".* ");
1030     }
1031
1032   if (regexp != NULL)
1033     {
1034       val = re_comp (myregexp);
1035       if (val != 0)
1036         error ("Invalid regexp (%s): %s", val, regexp);
1037     }
1038
1039   /* First time thru is JUST to get max length and count.  */
1040   ALL_MSYMBOLS (objfile, msymbol)
1041     {
1042       QUIT;
1043       name = SYMBOL_NATURAL_NAME (msymbol);
1044       if (name &&
1045          (name[0] == '-' || name[0] == '+') &&
1046           name[1] == '[')                       /* Got a method name.  */
1047         if (regexp == NULL || re_exec(name+2) != 0)
1048           { 
1049             /* Compute length of classname part.  */
1050             char *mystart = name + 2;
1051             char *myend   = (char *) strchr(mystart, ' ');
1052             
1053             if (myend && (myend - mystart > maxlen))
1054               maxlen = myend - mystart;
1055             matches++;
1056           }
1057     }
1058   if (matches)
1059     {
1060       printf_filtered ("Classes matching \"%s\":\n\n", 
1061                        regexp ? regexp : "*");
1062       sym_arr = alloca (matches * sizeof (struct symbol *));
1063       matches = 0;
1064       ALL_MSYMBOLS (objfile, msymbol)
1065         {
1066           QUIT;
1067           name = SYMBOL_NATURAL_NAME (msymbol);
1068           if (name &&
1069              (name[0] == '-' || name[0] == '+') &&
1070               name[1] == '[')                   /* Got a method name.  */
1071             if (regexp == NULL || re_exec(name+2) != 0)
1072                 sym_arr[matches++] = (struct symbol *) msymbol;
1073         }
1074
1075       qsort (sym_arr, matches, sizeof (struct minimal_symbol *), 
1076              compare_classes);
1077       /* Prevent compare on first iteration.  */
1078       aclass[0] = 0;
1079       for (ix = 0; ix < matches; ix++)  /* Now do the output.  */
1080         {
1081           char *p = aclass;
1082
1083           QUIT;
1084           name = SYMBOL_NATURAL_NAME (sym_arr[ix]);
1085           name += 2;
1086           if (p[0] && specialcmp(name, p) == 0)
1087             continue;   /* Seen this one already (not unique).  */
1088
1089           /* Copy class part of method name.  */
1090           while (*name && *name != ' ')
1091             *p++ = *name++;
1092           *p++ = '\0';
1093           /* Print in columns.  */
1094           puts_filtered_tabular(aclass, maxlen + 1, 0);
1095         }
1096       begin_line();
1097     }
1098   else
1099     printf_filtered ("No classes matching \"%s\"\n", regexp ? regexp : "*");
1100 }
1101
1102 /* 
1103  * Function: find_imps (char *selector, struct symbol **sym_arr)
1104  *
1105  * Input:  a string representing a selector
1106  *         a pointer to an array of symbol pointers
1107  *         possibly a pointer to a symbol found by the caller.
1108  *
1109  * Output: number of methods that implement that selector.  Side
1110  * effects: The array of symbol pointers is filled with matching syms.
1111  *
1112  * By analogy with function "find_methods" (symtab.c), builds a list
1113  * of symbols matching the ambiguous input, so that "decode_line_2"
1114  * (symtab.c) can list them and ask the user to choose one or more.
1115  * In this case the matches are objective c methods
1116  * ("implementations") matching an objective c selector.
1117  *
1118  * Note that it is possible for a normal (c-style) function to have
1119  * the same name as an objective c selector.  To prevent the selector
1120  * from eclipsing the function, we allow the caller (decode_line_1) to
1121  * search for such a function first, and if it finds one, pass it in
1122  * to us.  We will then integrate it into the list.  We also search
1123  * for one here, among the minsyms.
1124  *
1125  * NOTE: if NUM_DEBUGGABLE is non-zero, the sym_arr will be divided
1126  *       into two parts: debuggable (struct symbol) syms, and
1127  *       non_debuggable (struct minimal_symbol) syms.  The debuggable
1128  *       ones will come first, before NUM_DEBUGGABLE (which will thus
1129  *       be the index of the first non-debuggable one). 
1130  */
1131
1132 /*
1133  * Function: total_number_of_imps (char *selector);
1134  *
1135  * Input:  a string representing a selector 
1136  * Output: number of methods that implement that selector.
1137  *
1138  * By analogy with function "total_number_of_methods", this allows
1139  * decode_line_1 (symtab.c) to detect if there are objective c methods
1140  * matching the input, and to allocate an array of pointers to them
1141  * which can be manipulated by "decode_line_2" (also in symtab.c).
1142  */
1143
1144 char * 
1145 parse_selector (char *method, char **selector)
1146 {
1147   char *s1 = NULL;
1148   char *s2 = NULL;
1149   int found_quote = 0;
1150
1151   char *nselector = NULL;
1152
1153   CHECK (selector != NULL);
1154
1155   s1 = method;
1156
1157   while (isspace (*s1))
1158     s1++;
1159   if (*s1 == '\'') 
1160     {
1161       found_quote = 1;
1162       s1++;
1163     }
1164   while (isspace (*s1))
1165     s1++;
1166    
1167   nselector = s1;
1168   s2 = s1;
1169
1170   for (;;) {
1171     if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
1172       *s1++ = *s2;
1173     else if (isspace (*s2))
1174       ;
1175     else if ((*s2 == '\0') || (*s2 == '\''))
1176       break;
1177     else
1178       return NULL;
1179     s2++;
1180   }
1181   *s1++ = '\0';
1182
1183   while (isspace (*s2))
1184     s2++;
1185   if (found_quote)
1186     {
1187       if (*s2 == '\'') 
1188         s2++;
1189       while (isspace (*s2))
1190         s2++;
1191     }
1192
1193   if (selector != NULL)
1194     *selector = nselector;
1195
1196   return s2;
1197 }
1198
1199 char * 
1200 parse_method (char *method, char *type, char **class, 
1201               char **category, char **selector)
1202 {
1203   char *s1 = NULL;
1204   char *s2 = NULL;
1205   int found_quote = 0;
1206
1207   char ntype = '\0';
1208   char *nclass = NULL;
1209   char *ncategory = NULL;
1210   char *nselector = NULL;
1211
1212   CHECK (type != NULL);
1213   CHECK (class != NULL);
1214   CHECK (category != NULL);
1215   CHECK (selector != NULL);
1216   
1217   s1 = method;
1218
1219   while (isspace (*s1))
1220     s1++;
1221   if (*s1 == '\'') 
1222     {
1223       found_quote = 1;
1224       s1++;
1225     }
1226   while (isspace (*s1))
1227     s1++;
1228   
1229   if ((s1[0] == '+') || (s1[0] == '-'))
1230     ntype = *s1++;
1231
1232   while (isspace (*s1))
1233     s1++;
1234
1235   if (*s1 != '[')
1236     return NULL;
1237   s1++;
1238
1239   nclass = s1;
1240   while (isalnum (*s1) || (*s1 == '_'))
1241     s1++;
1242   
1243   s2 = s1;
1244   while (isspace (*s2))
1245     s2++;
1246   
1247   if (*s2 == '(')
1248     {
1249       s2++;
1250       while (isspace (*s2))
1251         s2++;
1252       ncategory = s2;
1253       while (isalnum (*s2) || (*s2 == '_'))
1254         s2++;
1255       *s2++ = '\0';
1256     }
1257
1258   /* Truncate the class name now that we're not using the open paren.  */
1259   *s1++ = '\0';
1260
1261   nselector = s2;
1262   s1 = s2;
1263
1264   for (;;) {
1265     if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
1266       *s1++ = *s2;
1267     else if (isspace (*s2))
1268       ;
1269     else if (*s2 == ']')
1270       break;
1271     else
1272       return NULL;
1273     s2++;
1274   }
1275   *s1++ = '\0';
1276   s2++;
1277
1278   while (isspace (*s2))
1279     s2++;
1280   if (found_quote)
1281     {
1282       if (*s2 != '\'') 
1283         return NULL;
1284       s2++;
1285       while (isspace (*s2))
1286         s2++;
1287     }
1288
1289   if (type != NULL)
1290     *type = ntype;
1291   if (class != NULL)
1292     *class = nclass;
1293   if (category != NULL)
1294     *category = ncategory;
1295   if (selector != NULL)
1296     *selector = nselector;
1297
1298   return s2;
1299 }
1300
1301 static void
1302 find_methods (struct symtab *symtab, char type, 
1303               const char *class, const char *category, 
1304               const char *selector, struct symbol **syms, 
1305               unsigned int *nsym, unsigned int *ndebug)
1306 {
1307   struct objfile *objfile = NULL;
1308   struct minimal_symbol *msymbol = NULL;
1309   struct block *block = NULL;
1310   struct symbol *sym = NULL;
1311
1312   char *symname = NULL;
1313
1314   char ntype = '\0';
1315   char *nclass = NULL;
1316   char *ncategory = NULL;
1317   char *nselector = NULL;
1318
1319   unsigned int csym = 0;
1320   unsigned int cdebug = 0;
1321
1322   static char *tmp = NULL;
1323   static unsigned int tmplen = 0;
1324
1325   CHECK (nsym != NULL);
1326   CHECK (ndebug != NULL);
1327
1328   if (symtab)
1329     block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), STATIC_BLOCK);
1330
1331   ALL_MSYMBOLS (objfile, msymbol)
1332     {
1333       QUIT;
1334
1335       if ((msymbol->type != mst_text) && (msymbol->type != mst_file_text))
1336         /* Not a function or method.  */
1337         continue;
1338
1339       if (symtab)
1340         if ((SYMBOL_VALUE_ADDRESS (msymbol) <  BLOCK_START (block)) ||
1341             (SYMBOL_VALUE_ADDRESS (msymbol) >= BLOCK_END (block)))
1342           /* Not in the specified symtab.  */
1343           continue;
1344
1345       symname = SYMBOL_NATURAL_NAME (msymbol);
1346       if (symname == NULL)
1347         continue;
1348
1349       if ((symname[0] != '-' && symname[0] != '+') || (symname[1] != '['))
1350         /* Not a method name.  */
1351         continue;
1352       
1353       while ((strlen (symname) + 1) >= tmplen)
1354         {
1355           tmplen = (tmplen == 0) ? 1024 : tmplen * 2;
1356           tmp = xrealloc (tmp, tmplen);
1357         }
1358       strcpy (tmp, symname);
1359
1360       if (parse_method (tmp, &ntype, &nclass, &ncategory, &nselector) == NULL)
1361         continue;
1362       
1363       if ((type != '\0') && (ntype != type))
1364         continue;
1365
1366       if ((class != NULL) 
1367           && ((nclass == NULL) || (strcmp (class, nclass) != 0)))
1368         continue;
1369
1370       if ((category != NULL) && 
1371           ((ncategory == NULL) || (strcmp (category, ncategory) != 0)))
1372         continue;
1373
1374       if ((selector != NULL) && 
1375           ((nselector == NULL) || (strcmp (selector, nselector) != 0)))
1376         continue;
1377
1378       sym = find_pc_function (SYMBOL_VALUE_ADDRESS (msymbol));
1379       if (sym != NULL)
1380         {
1381           const char *newsymname = SYMBOL_NATURAL_NAME (sym);
1382           
1383           if (strcmp (symname, newsymname) == 0)
1384             {
1385               /* Found a high-level method sym: swap it into the
1386                  lower part of sym_arr (below num_debuggable).  */
1387               if (syms != NULL)
1388                 {
1389                   syms[csym] = syms[cdebug];
1390                   syms[cdebug] = sym;
1391                 }
1392               csym++;
1393               cdebug++;
1394             }
1395           else
1396             {
1397               warning (
1398 "debugging symbol \"%s\" does not match minimal symbol (\"%s\"); ignoring",
1399                        newsymname, symname);
1400               if (syms != NULL)
1401                 syms[csym] = (struct symbol *) msymbol;
1402               csym++;
1403             }
1404         }
1405       else 
1406         {
1407           /* Found a non-debuggable method symbol.  */
1408           if (syms != NULL)
1409             syms[csym] = (struct symbol *) msymbol;
1410           csym++;
1411         }
1412     }
1413
1414   if (nsym != NULL)
1415     *nsym = csym;
1416   if (ndebug != NULL)
1417     *ndebug = cdebug;
1418 }
1419
1420 char *find_imps (struct symtab *symtab, struct block *block,
1421                  char *method, struct symbol **syms, 
1422                  unsigned int *nsym, unsigned int *ndebug)
1423 {
1424   char type = '\0';
1425   char *class = NULL;
1426   char *category = NULL;
1427   char *selector = NULL;
1428
1429   unsigned int csym = 0;
1430   unsigned int cdebug = 0;
1431
1432   unsigned int ncsym = 0;
1433   unsigned int ncdebug = 0;
1434
1435   char *buf = NULL;
1436   char *tmp = NULL;
1437
1438   CHECK (nsym != NULL);
1439   CHECK (ndebug != NULL);
1440
1441   if (nsym != NULL)
1442     *nsym = 0;
1443   if (ndebug != NULL)
1444     *ndebug = 0;
1445
1446   buf = (char *) alloca (strlen (method) + 1);
1447   strcpy (buf, method);
1448   tmp = parse_method (buf, &type, &class, &category, &selector);
1449
1450   if (tmp == NULL) {
1451     
1452     struct symtab *sym_symtab = NULL;
1453     struct symbol *sym = NULL;
1454     struct minimal_symbol *msym = NULL;
1455     
1456     strcpy (buf, method);
1457     tmp = parse_selector (buf, &selector);
1458     
1459     if (tmp == NULL)
1460       return NULL;
1461     
1462     sym = lookup_symbol (selector, block, VAR_NAMESPACE, 0, &sym_symtab);
1463     if (sym != NULL) 
1464       {
1465         if (syms)
1466           syms[csym] = sym;
1467         csym++;
1468         cdebug++;
1469       }
1470
1471     if (sym == NULL)
1472       msym = lookup_minimal_symbol (selector, 0, 0);
1473
1474     if (msym != NULL) 
1475       {
1476         if (syms)
1477           syms[csym] = (struct symbol *)msym;
1478         csym++;
1479       }
1480   }
1481
1482   if (syms != NULL)
1483     find_methods (symtab, type, class, category, selector, 
1484                   syms + csym, &ncsym, &ncdebug);
1485   else
1486     find_methods (symtab, type, class, category, selector, 
1487                   NULL, &ncsym, &ncdebug);
1488
1489   /* If we didn't find any methods, just return.  */
1490   if (ncsym == 0 && ncdebug == 0)
1491     return method;
1492
1493   /* Take debug symbols from the second batch of symbols and swap them
1494    * with debug symbols from the first batch.  Repeat until either the
1495    * second section is out of debug symbols or the first section is
1496    * full of debug symbols.  Either way we have all debug symbols
1497    * packed to the beginning of the buffer.  
1498    */
1499
1500   if (syms != NULL) 
1501     {
1502       while ((cdebug < csym) && (ncdebug > 0))
1503         {
1504           struct symbol *s = NULL;
1505           /* First non-debugging symbol.  */
1506           unsigned int i = cdebug;
1507           /* Last of second batch of debug symbols.  */
1508           unsigned int j = csym + ncdebug - 1;
1509
1510           s = syms[j];
1511           syms[j] = syms[i];
1512           syms[i] = s;
1513
1514           /* We've moved a symbol from the second debug section to the
1515              first one.  */
1516           cdebug++;
1517           ncdebug--;
1518         }
1519     }
1520
1521   csym += ncsym;
1522   cdebug += ncdebug;
1523
1524   if (nsym != NULL)
1525     *nsym = csym;
1526   if (ndebug != NULL)
1527     *ndebug = cdebug;
1528
1529   if (syms == NULL)
1530     return method + (tmp - buf);
1531
1532   if (csym > 1)
1533     {
1534       /* Sort debuggable symbols.  */
1535       if (cdebug > 1)
1536         qsort (syms, cdebug, sizeof (struct minimal_symbol *), 
1537                compare_classes);
1538       
1539       /* Sort minimal_symbols.  */
1540       if ((csym - cdebug) > 1)
1541         qsort (&syms[cdebug], csym - cdebug, 
1542                sizeof (struct minimal_symbol *), compare_classes);
1543     }
1544   /* Terminate the sym_arr list.  */
1545   syms[csym] = 0;
1546
1547   return method + (tmp - buf);
1548 }
1549
1550 void 
1551 print_object_command (char *args, int from_tty)
1552 {
1553   struct value *object, *function, *description;
1554   CORE_ADDR string_addr, object_addr;
1555   int i = 0;
1556   char c = -1;
1557
1558   if (!args || !*args)
1559     error (
1560 "The 'print-object' command requires an argument (an Objective-C object)");
1561
1562   {
1563     struct expression *expr = parse_expression (args);
1564     register struct cleanup *old_chain = 
1565       make_cleanup (free_current_contents, &expr);
1566     int pc = 0;
1567
1568     object = expr->language_defn->evaluate_exp (builtin_type_void_data_ptr,
1569                                                 expr, &pc, EVAL_NORMAL);
1570     do_cleanups (old_chain);
1571   }
1572
1573   /* Validate the address for sanity.  */
1574   object_addr = value_as_long (object);
1575   read_memory (object_addr, &c, 1);
1576
1577   function = find_function_in_inferior ("_NSPrintForDebugger");
1578   if (function == NULL)
1579     error ("Unable to locate _NSPrintForDebugger in child process");
1580
1581   description = call_function_by_hand (function, 1, &object);
1582
1583   string_addr = value_as_long (description);
1584   if (string_addr == 0)
1585     error ("object returns null description");
1586
1587   read_memory (string_addr + i++, &c, 1);
1588   if (c != '\0')
1589     do
1590       { /* Read and print characters up to EOS.  */
1591         QUIT;
1592         printf_filtered ("%c", c);
1593         read_memory (string_addr + i++, &c, 1);
1594       } while (c != 0);
1595   else
1596     printf_filtered("<object returns empty description>");
1597   printf_filtered ("\n");
1598 }
1599
1600 /* The data structure 'methcalls' is used to detect method calls (thru
1601  * ObjC runtime lib functions objc_msgSend, objc_msgSendSuper, etc.),
1602  * and ultimately find the method being called. 
1603  */
1604
1605 struct objc_methcall {
1606   char *name;
1607  /* Return instance method to be called.  */
1608   int (*stop_at) (CORE_ADDR, CORE_ADDR *);
1609   /* Start of pc range corresponding to method invocation.  */
1610   CORE_ADDR begin;
1611   /* End of pc range corresponding to method invocation.  */
1612   CORE_ADDR end;
1613 };
1614
1615 static int resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc);
1616 static int resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1617 static int resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc);
1618 static int resolve_msgsend_super_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1619
1620 static struct objc_methcall methcalls[] = {
1621   { "_objc_msgSend", resolve_msgsend, 0, 0},
1622   { "_objc_msgSend_stret", resolve_msgsend_stret, 0, 0},
1623   { "_objc_msgSendSuper", resolve_msgsend_super, 0, 0},
1624   { "_objc_msgSendSuper_stret", resolve_msgsend_super_stret, 0, 0},
1625   { "_objc_getClass", NULL, 0, 0},
1626   { "_objc_getMetaClass", NULL, 0, 0}
1627 };
1628
1629 #define nmethcalls (sizeof (methcalls) / sizeof (methcalls[0]))
1630
1631 /* The following function, "find_objc_msgsend", fills in the data
1632  * structure "objc_msgs" by finding the addresses of each of the
1633  * (currently four) functions that it holds (of which objc_msgSend is
1634  * the first).  This must be called each time symbols are loaded, in
1635  * case the functions have moved for some reason.  
1636  */
1637
1638 void 
1639 find_objc_msgsend (void)
1640 {
1641   unsigned int i;
1642   for (i = 0; i < nmethcalls; i++) {
1643
1644     struct minimal_symbol *func;
1645
1646     /* Try both with and without underscore.  */
1647     func = lookup_minimal_symbol (methcalls[i].name, NULL, NULL);
1648     if ((func == NULL) && (methcalls[i].name[0] == '_')) {
1649       func = lookup_minimal_symbol (methcalls[i].name + 1, NULL, NULL);
1650     }
1651     if (func == NULL) { 
1652       methcalls[i].begin = 0;
1653       methcalls[i].end = 0;
1654       continue; 
1655     }
1656     
1657     methcalls[i].begin = SYMBOL_VALUE_ADDRESS (func);
1658     do {
1659       methcalls[i].end = SYMBOL_VALUE_ADDRESS (++func);
1660     } while (methcalls[i].begin == methcalls[i].end);
1661   }
1662 }
1663
1664 /* find_objc_msgcall (replaces pc_off_limits)
1665  *
1666  * ALL that this function now does is to determine whether the input
1667  * address ("pc") is the address of one of the Objective-C message
1668  * dispatch functions (mainly objc_msgSend or objc_msgSendSuper), and
1669  * if so, it returns the address of the method that will be called.
1670  *
1671  * The old function "pc_off_limits" used to do a lot of other things
1672  * in addition, such as detecting shared library jump stubs and
1673  * returning the address of the shlib function that would be called.
1674  * That functionality has been moved into the SKIP_TRAMPOLINE_CODE and
1675  * IN_SOLIB_TRAMPOLINE macros, which are resolved in the target-
1676  * dependent modules.  
1677  */
1678
1679 struct objc_submethod_helper_data {
1680   int (*f) (CORE_ADDR, CORE_ADDR *);
1681   CORE_ADDR pc;
1682   CORE_ADDR *new_pc;
1683 };
1684
1685 int 
1686 find_objc_msgcall_submethod_helper (void * arg)
1687 {
1688   struct objc_submethod_helper_data *s = 
1689     (struct objc_submethod_helper_data *) arg;
1690
1691   if (s->f (s->pc, s->new_pc) == 0) 
1692     return 1;
1693   else 
1694     return 0;
1695 }
1696
1697 int 
1698 find_objc_msgcall_submethod (int (*f) (CORE_ADDR, CORE_ADDR *),
1699                              CORE_ADDR pc, 
1700                              CORE_ADDR *new_pc)
1701 {
1702   struct objc_submethod_helper_data s;
1703
1704   s.f = f;
1705   s.pc = pc;
1706   s.new_pc = new_pc;
1707
1708   if (catch_errors (find_objc_msgcall_submethod_helper,
1709                     (void *) &s,
1710                     "Unable to determine target of Objective-C method call (ignoring):\n",
1711                     RETURN_MASK_ALL) == 0) 
1712     return 1;
1713   else 
1714     return 0;
1715 }
1716
1717 int 
1718 find_objc_msgcall (CORE_ADDR pc, CORE_ADDR *new_pc)
1719 {
1720   unsigned int i;
1721
1722   find_objc_msgsend ();
1723   if (new_pc != NULL)
1724     {
1725       *new_pc = 0;
1726     }
1727
1728   for (i = 0; i < nmethcalls; i++) 
1729     if ((pc >= methcalls[i].begin) && (pc < methcalls[i].end)) 
1730       {
1731         if (methcalls[i].stop_at != NULL) 
1732           return find_objc_msgcall_submethod (methcalls[i].stop_at, 
1733                                               pc, new_pc);
1734         else 
1735           return 0;
1736       }
1737
1738   return 0;
1739 }
1740
1741 void
1742 _initialize_objc_language (void)
1743 {
1744   add_language (&objc_language_defn);
1745   add_info ("selectors", selectors_info,    /* INFO SELECTORS command.  */
1746             "All Objective-C selectors, or those matching REGEXP.");
1747   add_info ("classes", classes_info,        /* INFO CLASSES   command.  */
1748             "All Objective-C classes, or those matching REGEXP.");
1749   add_com ("print-object", class_vars, print_object_command, 
1750            "Ask an Objective-C object to print itself.");
1751   add_com_alias ("po", "print-object", class_vars, 1);
1752 }
1753
1754 #if defined (__powerpc__) || defined (__ppc__)
1755 static unsigned long FETCH_ARGUMENT (int i)
1756 {
1757   return read_register (3 + i);
1758 }
1759 #elif defined (__i386__)
1760 static unsigned long FETCH_ARGUMENT (int i)
1761 {
1762   CORE_ADDR stack = read_register (SP_REGNUM);
1763   return read_memory_unsigned_integer (stack + (4 * (i + 1)), 4);
1764 }
1765 #elif defined (__sparc__)
1766 static unsigned long FETCH_ARGUMENT (int i)
1767 {
1768   return read_register (O0_REGNUM + i);
1769 }
1770 #elif defined (__hppa__) || defined (__hppa)
1771 static unsigned long FETCH_ARGUMENT (int i)
1772 {
1773   return read_register (R0_REGNUM + 26 - i);
1774 }
1775 #else
1776 #error unknown architecture
1777 #endif
1778
1779 #if defined (__hppa__) || defined (__hppa)
1780 static CORE_ADDR CONVERT_FUNCPTR (CORE_ADDR pc)
1781 {
1782   if (pc & 0x2)
1783     pc = (CORE_ADDR) read_memory_integer (pc & ~0x3, 4);
1784
1785   return pc;
1786 }
1787 #else
1788 static CORE_ADDR CONVERT_FUNCPTR (CORE_ADDR pc)
1789 {
1790   return pc;
1791 }
1792 #endif
1793
1794 static void 
1795 read_objc_method (CORE_ADDR addr, struct objc_method *method)
1796 {
1797   method->name  = read_memory_unsigned_integer (addr + 0, 4);
1798   method->types = read_memory_unsigned_integer (addr + 4, 4);
1799   method->imp   = read_memory_unsigned_integer (addr + 8, 4);
1800 }
1801
1802 static 
1803 unsigned long read_objc_methlist_nmethods (CORE_ADDR addr)
1804 {
1805   return read_memory_unsigned_integer (addr + 4, 4);
1806 }
1807
1808 static void 
1809 read_objc_methlist_method (CORE_ADDR addr, unsigned long num, 
1810                            struct objc_method *method)
1811 {
1812   CHECK_FATAL (num < read_objc_methlist_nmethods (addr));
1813   read_objc_method (addr + 8 + (12 * num), method);
1814 }
1815   
1816 static void 
1817 read_objc_object (CORE_ADDR addr, struct objc_object *object)
1818 {
1819   object->isa = read_memory_unsigned_integer (addr, 4);
1820 }
1821
1822 static void 
1823 read_objc_super (CORE_ADDR addr, struct objc_super *super)
1824 {
1825   super->receiver = read_memory_unsigned_integer (addr, 4);
1826   super->class = read_memory_unsigned_integer (addr + 4, 4);
1827 };
1828
1829 static void 
1830 read_objc_class (CORE_ADDR addr, struct objc_class *class)
1831 {
1832   class->isa = read_memory_unsigned_integer (addr, 4);
1833   class->super_class = read_memory_unsigned_integer (addr + 4, 4);
1834   class->name = read_memory_unsigned_integer (addr + 8, 4);
1835   class->version = read_memory_unsigned_integer (addr + 12, 4);
1836   class->info = read_memory_unsigned_integer (addr + 16, 4);
1837   class->instance_size = read_memory_unsigned_integer (addr + 18, 4);
1838   class->ivars = read_memory_unsigned_integer (addr + 24, 4);
1839   class->methods = read_memory_unsigned_integer (addr + 28, 4);
1840   class->cache = read_memory_unsigned_integer (addr + 32, 4);
1841   class->protocols = read_memory_unsigned_integer (addr + 36, 4);
1842 }
1843
1844 CORE_ADDR
1845 find_implementation_from_class (CORE_ADDR class, CORE_ADDR sel)
1846 {
1847   CORE_ADDR subclass = class;
1848
1849   while (subclass != 0) 
1850     {
1851
1852       struct objc_class class_str;
1853       unsigned mlistnum = 0;
1854
1855       read_objc_class (subclass, &class_str);
1856
1857       for (;;) 
1858         {
1859           CORE_ADDR mlist;
1860           unsigned long nmethods;
1861           unsigned long i;
1862       
1863           mlist = read_memory_unsigned_integer (class_str.methods + 
1864                                                 (4 * mlistnum), 4);
1865           if (mlist == 0) 
1866             break;
1867
1868           nmethods = read_objc_methlist_nmethods (mlist);
1869
1870           for (i = 0; i < nmethods; i++) 
1871             {
1872               struct objc_method meth_str;
1873               read_objc_methlist_method (mlist, i, &meth_str);
1874
1875 #if 0
1876               fprintf (stderr, 
1877                        "checking method 0x%lx against selector 0x%lx\n", 
1878                        meth_str.name, sel);
1879 #endif
1880
1881               if (meth_str.name == sel) 
1882                 return CONVERT_FUNCPTR (meth_str.imp);
1883             }
1884           mlistnum++;
1885         }
1886       subclass = class_str.super_class;
1887     }
1888
1889   return 0;
1890 }
1891
1892 CORE_ADDR
1893 find_implementation (CORE_ADDR object, CORE_ADDR sel)
1894 {
1895   struct objc_object ostr;
1896
1897   if (object == 0)
1898     return 0;
1899   read_objc_object (object, &ostr);
1900   if (ostr.isa == 0)
1901     return 0;
1902
1903   return find_implementation_from_class (ostr.isa, sel);
1904 }
1905
1906 static int
1907 resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc)
1908 {
1909   CORE_ADDR object;
1910   CORE_ADDR sel;
1911   CORE_ADDR res;
1912
1913   object = FETCH_ARGUMENT (0);
1914   sel = FETCH_ARGUMENT (1);
1915
1916   res = find_implementation (object, sel);
1917   if (new_pc != 0)
1918     *new_pc = res;
1919   if (res == 0)
1920     return 1;
1921   return 0;
1922 }
1923
1924 static int
1925 resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc)
1926 {
1927   CORE_ADDR object;
1928   CORE_ADDR sel;
1929   CORE_ADDR res;
1930
1931   object = FETCH_ARGUMENT (1);
1932   sel = FETCH_ARGUMENT (2);
1933
1934   res = find_implementation (object, sel);
1935   if (new_pc != 0)
1936     *new_pc = res;
1937   if (res == 0)
1938     return 1;
1939   return 0;
1940 }
1941
1942 static int
1943 resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc)
1944 {
1945   struct objc_super sstr;
1946
1947   CORE_ADDR super;
1948   CORE_ADDR sel;
1949   CORE_ADDR res;
1950
1951   super = FETCH_ARGUMENT (0);
1952   sel = FETCH_ARGUMENT (1);
1953
1954   read_objc_super (super, &sstr);
1955   if (sstr.class == 0)
1956     return 0;
1957   
1958   res = find_implementation_from_class (sstr.class, sel);
1959   if (new_pc != 0)
1960     *new_pc = res;
1961   if (res == 0)
1962     return 1;
1963   return 0;
1964 }
1965
1966 static int
1967 resolve_msgsend_super_stret (CORE_ADDR pc, CORE_ADDR *new_pc)
1968 {
1969   struct objc_super sstr;
1970
1971   CORE_ADDR super;
1972   CORE_ADDR sel;
1973   CORE_ADDR res;
1974
1975   super = FETCH_ARGUMENT (1);
1976   sel = FETCH_ARGUMENT (2);
1977
1978   read_objc_super (super, &sstr);
1979   if (sstr.class == 0)
1980     return 0;
1981   
1982   res = find_implementation_from_class (sstr.class, sel);
1983   if (new_pc != 0)
1984     *new_pc = res;
1985   if (res == 0)
1986     return 1;
1987   return 0;
1988 }