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