OSDN Git Service

2003-02-19 David Carlton <carlton@math.stanford.edu>
[pf3gnuchains/pf3gnuchains3x.git] / gdb / objc-lang.c
1 /* Objective-C language support routines for GDB, the GNU debugger.
2
3    Copyright 2002 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   if (!(sym = lookup_struct_typedef("NSString", 0, 1)) &&
203       !(sym = lookup_struct_typedef("NXString", 0, 1)))
204     type = lookup_pointer_type(builtin_type_void);
205   else
206     type = lookup_pointer_type(SYMBOL_TYPE (sym));
207
208   stringValue[2] = value_string(ptr, len);
209   stringValue[2] = value_coerce_array(stringValue[2]);
210   /* _NSNewStringFromCString replaces "istr" after Lantern2A.  */
211   if (lookup_minimal_symbol("_NSNewStringFromCString", 0, 0))
212     {
213       function = find_function_in_inferior("_NSNewStringFromCString");
214       nsstringValue = call_function_by_hand(function, 1, &stringValue[2]);
215     }
216   else if (lookup_minimal_symbol("istr", 0, 0))
217     {
218       function = find_function_in_inferior("istr");
219       nsstringValue = call_function_by_hand(function, 1, &stringValue[2]);
220     }
221   else if (lookup_minimal_symbol("+[NSString stringWithCString:]", 0, 0))
222     {
223       function = find_function_in_inferior("+[NSString stringWithCString:]");
224       stringValue[0] = value_from_longest 
225         (builtin_type_long, lookup_objc_class ("NSString"));
226       stringValue[1] = value_from_longest 
227         (builtin_type_long, lookup_child_selector ("stringWithCString:"));
228       nsstringValue = call_function_by_hand(function, 3, &stringValue[0]);
229     }
230   else
231     error ("NSString: internal error -- no way to create new NSString");
232
233   VALUE_TYPE(nsstringValue) = type;
234   return nsstringValue;
235 }
236
237 /* Objective-C name demangling.  */
238
239 char *
240 objc_demangle (const char *mangled)
241 {
242   char *demangled, *cp;
243
244   if (mangled[0] == '_' &&
245      (mangled[1] == 'i' || mangled[1] == 'c') &&
246       mangled[2] == '_')
247     {
248       cp = demangled = xmalloc(strlen(mangled) + 2);
249
250       if (mangled[1] == 'i')
251         *cp++ = '-';            /* for instance method */
252       else
253         *cp++ = '+';            /* for class    method */
254
255       *cp++ = '[';              /* opening left brace  */
256       strcpy(cp, mangled+3);    /* tack on the rest of the mangled name */
257
258       while (*cp && *cp == '_')
259         cp++;                   /* skip any initial underbars in class name */
260
261       cp = strchr(cp, '_');
262       if (!cp)                  /* find first non-initial underbar */
263         {
264           xfree(demangled);     /* not mangled name */
265           return NULL;
266         }
267       if (cp[1] == '_') {       /* easy case: no category name     */
268         *cp++ = ' ';            /* replace two '_' with one ' '    */
269         strcpy(cp, mangled + (cp - demangled) + 2);
270       }
271       else {
272         *cp++ = '(';            /* less easy case: category name */
273         cp = strchr(cp, '_');
274         if (!cp)
275           {
276             xfree(demangled);   /* not mangled name */
277             return NULL;
278           }
279         *cp++ = ')';
280         *cp++ = ' ';            /* overwriting 1st char of method name...  */
281         strcpy(cp, mangled + (cp - demangled)); /* get it back */
282       }
283
284       while (*cp && *cp == '_')
285         cp++;                   /* skip any initial underbars in method name */
286
287       for (; *cp; cp++)
288         if (*cp == '_')
289           *cp = ':';            /* replace remaining '_' with ':' */
290
291       *cp++ = ']';              /* closing right brace */
292       *cp++ = 0;                /* string terminator */
293       return demangled;
294     }
295   else
296     return NULL;        /* Not an objc mangled name.  */
297 }
298
299 /* Print the character C on STREAM as part of the contents of a
300    literal string whose delimiter is QUOTER.  Note that that format
301    for printing characters and strings is language specific.  */
302
303 static void
304 objc_emit_char (register int c, struct ui_file *stream, int quoter)
305 {
306
307   c &= 0xFF;                    /* Avoid sign bit follies.  */
308
309   if (PRINT_LITERAL_FORM (c))
310     {
311       if (c == '\\' || c == quoter)
312         {
313           fputs_filtered ("\\", stream);
314         }
315       fprintf_filtered (stream, "%c", c);
316     }
317   else
318     {
319       switch (c)
320         {
321         case '\n':
322           fputs_filtered ("\\n", stream);
323           break;
324         case '\b':
325           fputs_filtered ("\\b", stream);
326           break;
327         case '\t':
328           fputs_filtered ("\\t", stream);
329           break;
330         case '\f':
331           fputs_filtered ("\\f", stream);
332           break;
333         case '\r':
334           fputs_filtered ("\\r", stream);
335           break;
336         case '\033':
337           fputs_filtered ("\\e", stream);
338           break;
339         case '\007':
340           fputs_filtered ("\\a", stream);
341           break;
342         default:
343           fprintf_filtered (stream, "\\%.3o", (unsigned int) c);
344           break;
345         }
346     }
347 }
348
349 static void
350 objc_printchar (int c, struct ui_file *stream)
351 {
352   fputs_filtered ("'", stream);
353   objc_emit_char (c, stream, '\'');
354   fputs_filtered ("'", stream);
355 }
356
357 /* Print the character string STRING, printing at most LENGTH
358    characters.  Printing stops early if the number hits print_max;
359    repeat counts are printed as appropriate.  Print ellipses at the
360    end if we had to stop before printing LENGTH characters, or if
361    FORCE_ELLIPSES.  */
362
363 static void
364 objc_printstr (struct ui_file *stream, char *string, 
365                unsigned int length, int width, int force_ellipses)
366 {
367   register unsigned int i;
368   unsigned int things_printed = 0;
369   int in_quotes = 0;
370   int need_comma = 0;
371   extern int inspect_it;
372   extern int repeat_count_threshold;
373   extern int print_max;
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
597 /* Table mapping opcodes into strings for printing operators
598    and precedences of the operators.  */
599
600 static const struct op_print objc_op_print_tab[] =
601   {
602     {",",  BINOP_COMMA, PREC_COMMA, 0},
603     {"=",  BINOP_ASSIGN, PREC_ASSIGN, 1},
604     {"||", BINOP_LOGICAL_OR, PREC_LOGICAL_OR, 0},
605     {"&&", BINOP_LOGICAL_AND, PREC_LOGICAL_AND, 0},
606     {"|",  BINOP_BITWISE_IOR, PREC_BITWISE_IOR, 0},
607     {"^",  BINOP_BITWISE_XOR, PREC_BITWISE_XOR, 0},
608     {"&",  BINOP_BITWISE_AND, PREC_BITWISE_AND, 0},
609     {"==", BINOP_EQUAL, PREC_EQUAL, 0},
610     {"!=", BINOP_NOTEQUAL, PREC_EQUAL, 0},
611     {"<=", BINOP_LEQ, PREC_ORDER, 0},
612     {">=", BINOP_GEQ, PREC_ORDER, 0},
613     {">",  BINOP_GTR, PREC_ORDER, 0},
614     {"<",  BINOP_LESS, PREC_ORDER, 0},
615     {">>", BINOP_RSH, PREC_SHIFT, 0},
616     {"<<", BINOP_LSH, PREC_SHIFT, 0},
617     {"+",  BINOP_ADD, PREC_ADD, 0},
618     {"-",  BINOP_SUB, PREC_ADD, 0},
619     {"*",  BINOP_MUL, PREC_MUL, 0},
620     {"/",  BINOP_DIV, PREC_MUL, 0},
621     {"%",  BINOP_REM, PREC_MUL, 0},
622     {"@",  BINOP_REPEAT, PREC_REPEAT, 0},
623     {"-",  UNOP_NEG, PREC_PREFIX, 0},
624     {"!",  UNOP_LOGICAL_NOT, PREC_PREFIX, 0},
625     {"~",  UNOP_COMPLEMENT, PREC_PREFIX, 0},
626     {"*",  UNOP_IND, PREC_PREFIX, 0},
627     {"&",  UNOP_ADDR, PREC_PREFIX, 0},
628     {"sizeof ", UNOP_SIZEOF, PREC_PREFIX, 0},
629     {"++", UNOP_PREINCREMENT, PREC_PREFIX, 0},
630     {"--", UNOP_PREDECREMENT, PREC_PREFIX, 0},
631     {NULL, 0, 0, 0}
632 };
633
634 struct type ** const (objc_builtin_types[]) = 
635 {
636   &builtin_type_int,
637   &builtin_type_long,
638   &builtin_type_short,
639   &builtin_type_char,
640   &builtin_type_float,
641   &builtin_type_double,
642   &builtin_type_void,
643   &builtin_type_long_long,
644   &builtin_type_signed_char,
645   &builtin_type_unsigned_char,
646   &builtin_type_unsigned_short,
647   &builtin_type_unsigned_int,
648   &builtin_type_unsigned_long,
649   &builtin_type_unsigned_long_long,
650   &builtin_type_long_double,
651   &builtin_type_complex,
652   &builtin_type_double_complex,
653   0
654 };
655
656 const struct language_defn objc_language_defn = {
657   "objective-c",                /* Language name */
658   language_objc,
659   objc_builtin_types,
660   range_check_off,
661   type_check_off,
662   case_sensitive_on,
663   objc_parse,
664   objc_error,
665   evaluate_subexp_standard,
666   objc_printchar,               /* Print a character constant */
667   objc_printstr,                /* Function to print string constant */
668   objc_emit_char,
669   objc_create_fundamental_type, /* Create fundamental type in this language */
670   c_print_type,                 /* Print a type using appropriate syntax */
671   c_val_print,                  /* Print a value using appropriate syntax */
672   c_value_print,                /* Print a top-level value */
673   {"",     "",    "",  ""},     /* Binary format info */
674   {"0%lo",  "0",   "o", ""},    /* Octal format info */
675   {"%ld",   "",    "d", ""},    /* Decimal format info */
676   {"0x%lx", "0x",  "x", ""},    /* Hex format info */
677   objc_op_print_tab,            /* Expression operators for printing */
678   1,                            /* C-style arrays */
679   0,                            /* String lower bound */
680   &builtin_type_char,           /* Type of string elements */
681   LANG_MAGIC
682 };
683
684 /*
685  * ObjC:
686  * Following functions help construct Objective-C message calls 
687  */
688
689 struct selname          /* For parsing Objective-C.  */
690   {
691     struct selname *next;
692     char *msglist_sel;
693     int msglist_len;
694   };
695
696 static int msglist_len;
697 static struct selname *selname_chain;
698 static char *msglist_sel;
699
700 void
701 start_msglist(void)
702 {
703   register struct selname *new = 
704     (struct selname *) xmalloc (sizeof (struct selname));
705
706   new->next = selname_chain;
707   new->msglist_len = msglist_len;
708   new->msglist_sel = msglist_sel;
709   msglist_len = 0;
710   msglist_sel = (char *)xmalloc(1);
711   *msglist_sel = 0;
712   selname_chain = new;
713 }
714
715 void
716 add_msglist(struct stoken *str, int addcolon)
717 {
718   char *s, *p;
719   int len, plen;
720
721   if (str == 0) {               /* Unnamed arg, or...  */
722     if (addcolon == 0) {        /* variable number of args.  */
723       msglist_len++;
724       return;
725     }
726     p = "";
727     plen = 0;
728   } else {
729     p = str->ptr;
730     plen = str->length;
731   }
732   len = plen + strlen(msglist_sel) + 2;
733   s = (char *)xmalloc(len);
734   strcpy(s, msglist_sel);
735   strncat(s, p, plen);
736   xfree(msglist_sel);
737   msglist_sel = s;
738   if (addcolon) {
739     s[len-2] = ':';
740     s[len-1] = 0;
741     msglist_len++;
742   } else
743     s[len-2] = '\0';
744 }
745
746 int
747 end_msglist(void)
748 {
749   register int val = msglist_len;
750   register struct selname *sel = selname_chain;
751   register char *p = msglist_sel;
752   int selid;
753
754   selname_chain = sel->next;
755   msglist_len = sel->msglist_len;
756   msglist_sel = sel->msglist_sel;
757   selid = lookup_child_selector(p);
758   if (!selid)
759     error("Can't find selector \"%s\"", p);
760   write_exp_elt_longcst (selid);
761   xfree(p);
762   write_exp_elt_longcst (val);  /* Number of args */
763   xfree(sel);
764
765   return val;
766 }
767
768 /*
769  * Function: specialcmp (char *a, char *b)
770  *
771  * Special strcmp: treats ']' and ' ' as end-of-string.
772  * Used for qsorting lists of objc methods (either by class or selector).
773  */
774
775 int specialcmp(char *a, char *b)
776 {
777   while (*a && *a != ' ' && *a != ']' && *b && *b != ' ' && *b != ']')
778     {
779       if (*a != *b)
780         return *a - *b;
781       a++, b++;
782     }
783   if (*a && *a != ' ' && *a != ']')
784     return  1;          /* a is longer therefore greater */
785   if (*b && *b != ' ' && *b != ']')
786     return -1;          /* a is shorter therefore lesser */
787   return    0;          /* a and b are identical */
788 }
789
790 /*
791  * Function: compare_selectors (const void *, const void *)
792  *
793  * Comparison function for use with qsort.  Arguments are symbols or
794  * msymbols Compares selector part of objc method name alphabetically.
795  */
796
797 static int
798 compare_selectors (const void *a, const void *b)
799 {
800   char *aname, *bname;
801
802   aname = SYMBOL_SOURCE_NAME (*(struct symbol **) a);
803   bname = SYMBOL_SOURCE_NAME (*(struct symbol **) b);
804   if (aname == NULL || bname == NULL)
805     error ("internal: compare_selectors(1)");
806
807   aname = strchr(aname, ' ');
808   bname = strchr(bname, ' ');
809   if (aname == NULL || bname == NULL)
810     error ("internal: compare_selectors(2)");
811
812   return specialcmp (aname+1, bname+1);
813 }
814
815 /*
816  * Function: selectors_info (regexp, from_tty)
817  *
818  * Implements the "Info selectors" command.  Takes an optional regexp
819  * arg.  Lists all objective c selectors that match the regexp.  Works
820  * by grepping thru all symbols for objective c methods.  Output list
821  * is sorted and uniqued. 
822  */
823
824 static void
825 selectors_info (char *regexp, int from_tty)
826 {
827   struct objfile        *objfile;
828   struct minimal_symbol *msymbol;
829   char                  *name;
830   char                  *val;
831   int                    matches = 0;
832   int                    maxlen  = 0;
833   int                    ix;
834   char                   myregexp[2048];
835   char                   asel[256];
836   struct symbol        **sym_arr;
837   int                    plusminus = 0;
838
839   if (regexp == NULL)
840     strcpy(myregexp, ".*]");    /* Null input, match all objc methods.  */
841   else
842     {
843       if (*regexp == '+' || *regexp == '-')
844         { /* User wants only class methods or only instance methods.  */
845           plusminus = *regexp++;
846           while (*regexp == ' ' || *regexp == '\t')
847             regexp++;
848         }
849       if (*regexp == '\0')
850         strcpy(myregexp, ".*]");
851       else
852         {
853           strcpy(myregexp, regexp);
854           if (myregexp[strlen(myregexp) - 1] == '$') /* end of selector */
855             myregexp[strlen(myregexp) - 1] = ']';    /* end of method name */
856           else
857             strcat(myregexp, ".*]");
858         }
859     }
860
861   if (regexp != NULL)
862     if (0 != (val = re_comp (myregexp)))
863       error ("Invalid regexp (%s): %s", val, regexp);
864
865   /* First time thru is JUST to get max length and count.  */
866   ALL_MSYMBOLS (objfile, msymbol)
867     {
868       QUIT;
869       name = SYMBOL_DEMANGLED_NAME (msymbol);
870       if (name == NULL)
871         name = SYMBOL_NAME (msymbol);
872       if (name &&
873          (name[0] == '-' || name[0] == '+') &&
874           name[1] == '[')               /* Got a method name.  */
875         {
876           /* Filter for class/instance methods.  */
877           if (plusminus && name[0] != plusminus)
878             continue;
879           /* Find selector part.  */
880           name = (char *) strchr(name+2, ' ');
881           if (regexp == NULL || re_exec(++name) != 0)
882             { 
883               char *mystart = name;
884               char *myend   = (char *) strchr(mystart, ']');
885               
886               if (myend && (myend - mystart > maxlen))
887                 maxlen = myend - mystart;       /* Get longest selector.  */
888               matches++;
889             }
890         }
891     }
892   if (matches)
893     {
894       printf_filtered ("Selectors matching \"%s\":\n\n", 
895                        regexp ? regexp : "*");
896
897       sym_arr = alloca (matches * sizeof (struct symbol *));
898       matches = 0;
899       ALL_MSYMBOLS (objfile, msymbol)
900         {
901           QUIT;
902           name = SYMBOL_DEMANGLED_NAME (msymbol);
903           if (name == NULL)
904             name = SYMBOL_NAME (msymbol);
905           if (name &&
906              (name[0] == '-' || name[0] == '+') &&
907               name[1] == '[')           /* Got a method name.  */
908             {
909               /* Filter for class/instance methods.  */
910               if (plusminus && name[0] != plusminus)
911                 continue;
912               /* Find selector part.  */
913               name = (char *) strchr(name+2, ' ');
914               if (regexp == NULL || re_exec(++name) != 0)
915                 sym_arr[matches++] = (struct symbol *) msymbol;
916             }
917         }
918
919       qsort (sym_arr, matches, sizeof (struct minimal_symbol *), 
920              compare_selectors);
921       /* Prevent compare on first iteration.  */
922       asel[0] = 0;
923       for (ix = 0; ix < matches; ix++)  /* Now do the output.  */
924         {
925           char *p = asel;
926
927           QUIT;
928           name = SYMBOL_DEMANGLED_NAME (sym_arr[ix]);
929           if (name == NULL)
930             name = SYMBOL_NAME (sym_arr[ix]);
931           name = strchr (name, ' ') + 1;
932           if (p[0] && specialcmp(name, p) == 0)
933             continue;           /* Seen this one already (not unique).  */
934
935           /* Copy selector part.  */
936           while (*name && *name != ']')
937             *p++ = *name++;
938           *p++ = '\0';
939           /* Print in columns.  */
940           puts_filtered_tabular(asel, maxlen + 1, 0);
941         }
942       begin_line();
943     }
944   else
945     printf_filtered ("No selectors matching \"%s\"\n", regexp ? regexp : "*");
946 }
947
948 /*
949  * Function: compare_classes (const void *, const void *)
950  *
951  * Comparison function for use with qsort.  Arguments are symbols or
952  * msymbols Compares class part of objc method name alphabetically. 
953  */
954
955 static int
956 compare_classes (const void *a, const void *b)
957 {
958   char *aname, *bname;
959
960   aname = SYMBOL_SOURCE_NAME (*(struct symbol **) a);
961   bname = SYMBOL_SOURCE_NAME (*(struct symbol **) b);
962   if (aname == NULL || bname == NULL)
963     error ("internal: compare_classes(1)");
964
965   return specialcmp (aname+1, bname+1);
966 }
967
968 /*
969  * Function: classes_info(regexp, from_tty)
970  *
971  * Implements the "info classes" command for objective c classes.
972  * Lists all objective c classes that match the optional regexp.
973  * Works by grepping thru the list of objective c methods.  List will
974  * be sorted and uniqued (since one class may have many methods).
975  * BUGS: will not list a class that has no methods. 
976  */
977
978 static void
979 classes_info (char *regexp, int from_tty)
980 {
981   struct objfile        *objfile;
982   struct minimal_symbol *msymbol;
983   char                  *name;
984   char                  *val;
985   int                    matches = 0;
986   int                    maxlen  = 0;
987   int                    ix;
988   char                   myregexp[2048];
989   char                   aclass[256];
990   struct symbol        **sym_arr;
991
992   if (regexp == NULL)
993     strcpy(myregexp, ".* ");    /* Null input: match all objc classes.  */
994   else
995     {
996       strcpy(myregexp, regexp);
997       if (myregexp[strlen(myregexp) - 1] == '$')
998         /* In the method name, the end of the class name is marked by ' '.  */
999         myregexp[strlen(myregexp) - 1] = ' ';
1000       else
1001         strcat(myregexp, ".* ");
1002     }
1003
1004   if (regexp != NULL)
1005     if (0 != (val = re_comp (myregexp)))
1006       error ("Invalid regexp (%s): %s", val, regexp);
1007
1008   /* First time thru is JUST to get max length and count.  */
1009   ALL_MSYMBOLS (objfile, msymbol)
1010     {
1011       QUIT;
1012       name = SYMBOL_DEMANGLED_NAME (msymbol);
1013       if (name == NULL)
1014         name = SYMBOL_NAME (msymbol);
1015       if (name &&
1016          (name[0] == '-' || name[0] == '+') &&
1017           name[1] == '[')                       /* Got a method name.  */
1018         if (regexp == NULL || re_exec(name+2) != 0)
1019           { 
1020             /* Compute length of classname part.  */
1021             char *mystart = name + 2;
1022             char *myend   = (char *) strchr(mystart, ' ');
1023             
1024             if (myend && (myend - mystart > maxlen))
1025               maxlen = myend - mystart;
1026             matches++;
1027           }
1028     }
1029   if (matches)
1030     {
1031       printf_filtered ("Classes matching \"%s\":\n\n", 
1032                        regexp ? regexp : "*");
1033       sym_arr = alloca (matches * sizeof (struct symbol *));
1034       matches = 0;
1035       ALL_MSYMBOLS (objfile, msymbol)
1036         {
1037           QUIT;
1038           name = SYMBOL_DEMANGLED_NAME (msymbol);
1039           if (name == NULL)
1040             name = SYMBOL_NAME (msymbol);
1041           if (name &&
1042              (name[0] == '-' || name[0] == '+') &&
1043               name[1] == '[')                   /* Got a method name.  */
1044             if (regexp == NULL || re_exec(name+2) != 0)
1045                 sym_arr[matches++] = (struct symbol *) msymbol;
1046         }
1047
1048       qsort (sym_arr, matches, sizeof (struct minimal_symbol *), 
1049              compare_classes);
1050       /* Prevent compare on first iteration.  */
1051       aclass[0] = 0;
1052       for (ix = 0; ix < matches; ix++)  /* Now do the output.  */
1053         {
1054           char *p = aclass;
1055
1056           QUIT;
1057           name = SYMBOL_DEMANGLED_NAME (sym_arr[ix]);
1058           if (name == NULL)
1059             name = SYMBOL_NAME (sym_arr[ix]);
1060           name += 2;
1061           if (p[0] && specialcmp(name, p) == 0)
1062             continue;   /* Seen this one already (not unique).  */
1063
1064           /* Copy class part of method name.  */
1065           while (*name && *name != ' ')
1066             *p++ = *name++;
1067           *p++ = '\0';
1068           /* Print in columns.  */
1069           puts_filtered_tabular(aclass, maxlen + 1, 0);
1070         }
1071       begin_line();
1072     }
1073   else
1074     printf_filtered ("No classes matching \"%s\"\n", regexp ? regexp : "*");
1075 }
1076
1077 /* 
1078  * Function: find_imps (char *selector, struct symbol **sym_arr)
1079  *
1080  * Input:  a string representing a selector
1081  *         a pointer to an array of symbol pointers
1082  *         possibly a pointer to a symbol found by the caller.
1083  *
1084  * Output: number of methods that implement that selector.  Side
1085  * effects: The array of symbol pointers is filled with matching syms.
1086  *
1087  * By analogy with function "find_methods" (symtab.c), builds a list
1088  * of symbols matching the ambiguous input, so that "decode_line_2"
1089  * (symtab.c) can list them and ask the user to choose one or more.
1090  * In this case the matches are objective c methods
1091  * ("implementations") matching an objective c selector.
1092  *
1093  * Note that it is possible for a normal (c-style) function to have
1094  * the same name as an objective c selector.  To prevent the selector
1095  * from eclipsing the function, we allow the caller (decode_line_1) to
1096  * search for such a function first, and if it finds one, pass it in
1097  * to us.  We will then integrate it into the list.  We also search
1098  * for one here, among the minsyms.
1099  *
1100  * NOTE: if NUM_DEBUGGABLE is non-zero, the sym_arr will be divided
1101  *       into two parts: debuggable (struct symbol) syms, and
1102  *       non_debuggable (struct minimal_symbol) syms.  The debuggable
1103  *       ones will come first, before NUM_DEBUGGABLE (which will thus
1104  *       be the index of the first non-debuggable one). 
1105  */
1106
1107 /*
1108  * Function: total_number_of_imps (char *selector);
1109  *
1110  * Input:  a string representing a selector 
1111  * Output: number of methods that implement that selector.
1112  *
1113  * By analogy with function "total_number_of_methods", this allows
1114  * decode_line_1 (symtab.c) to detect if there are objective c methods
1115  * matching the input, and to allocate an array of pointers to them
1116  * which can be manipulated by "decode_line_2" (also in symtab.c).
1117  */
1118
1119 char * 
1120 parse_selector (char *method, char **selector)
1121 {
1122   char *s1 = NULL;
1123   char *s2 = NULL;
1124   int found_quote = 0;
1125
1126   char *nselector = NULL;
1127
1128   CHECK (selector != NULL);
1129
1130   s1 = method;
1131
1132   while (isspace (*s1))
1133     s1++;
1134   if (*s1 == '\'') 
1135     {
1136       found_quote = 1;
1137       s1++;
1138     }
1139   while (isspace (*s1))
1140     s1++;
1141    
1142   nselector = s1;
1143   s2 = s1;
1144
1145   for (;;) {
1146     if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
1147       *s1++ = *s2;
1148     else if (isspace (*s2))
1149       ;
1150     else if ((*s2 == '\0') || (*s2 == '\''))
1151       break;
1152     else
1153       return NULL;
1154     s2++;
1155   }
1156   *s1++ = '\0';
1157
1158   while (isspace (*s2))
1159     s2++;
1160   if (found_quote)
1161     {
1162       if (*s2 == '\'') 
1163         s2++;
1164       while (isspace (*s2))
1165         s2++;
1166     }
1167
1168   if (selector != NULL)
1169     *selector = nselector;
1170
1171   return s2;
1172 }
1173
1174 char * 
1175 parse_method (char *method, char *type, char **class, 
1176               char **category, char **selector)
1177 {
1178   char *s1 = NULL;
1179   char *s2 = NULL;
1180   int found_quote = 0;
1181
1182   char ntype = '\0';
1183   char *nclass = NULL;
1184   char *ncategory = NULL;
1185   char *nselector = NULL;
1186
1187   CHECK (type != NULL);
1188   CHECK (class != NULL);
1189   CHECK (category != NULL);
1190   CHECK (selector != NULL);
1191   
1192   s1 = method;
1193
1194   while (isspace (*s1))
1195     s1++;
1196   if (*s1 == '\'') 
1197     {
1198       found_quote = 1;
1199       s1++;
1200     }
1201   while (isspace (*s1))
1202     s1++;
1203   
1204   if ((s1[0] == '+') || (s1[0] == '-'))
1205     ntype = *s1++;
1206
1207   while (isspace (*s1))
1208     s1++;
1209
1210   if (*s1 != '[')
1211     return NULL;
1212   s1++;
1213
1214   nclass = s1;
1215   while (isalnum (*s1) || (*s1 == '_'))
1216     s1++;
1217   
1218   s2 = s1;
1219   while (isspace (*s2))
1220     s2++;
1221   
1222   if (*s2 == '(')
1223     {
1224       s2++;
1225       while (isspace (*s2))
1226         s2++;
1227       ncategory = s2;
1228       while (isalnum (*s2) || (*s2 == '_'))
1229         s2++;
1230       *s2++ = '\0';
1231     }
1232
1233   /* Truncate the class name now that we're not using the open paren.  */
1234   *s1++ = '\0';
1235
1236   nselector = s2;
1237   s1 = s2;
1238
1239   for (;;) {
1240     if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
1241       *s1++ = *s2;
1242     else if (isspace (*s2))
1243       ;
1244     else if (*s2 == ']')
1245       break;
1246     else
1247       return NULL;
1248     s2++;
1249   }
1250   *s1++ = '\0';
1251   s2++;
1252
1253   while (isspace (*s2))
1254     s2++;
1255   if (found_quote)
1256     {
1257       if (*s2 != '\'') 
1258         return NULL;
1259       s2++;
1260       while (isspace (*s2))
1261         s2++;
1262     }
1263
1264   if (type != NULL)
1265     *type = ntype;
1266   if (class != NULL)
1267     *class = nclass;
1268   if (category != NULL)
1269     *category = ncategory;
1270   if (selector != NULL)
1271     *selector = nselector;
1272
1273   return s2;
1274 }
1275
1276 void
1277 find_methods (struct symtab *symtab, char type, 
1278               const char *class, const char *category, 
1279               const char *selector, struct symbol **syms, 
1280               unsigned int *nsym, unsigned int *ndebug)
1281 {
1282   struct objfile *objfile = NULL;
1283   struct minimal_symbol *msymbol = NULL;
1284   struct block *block = NULL;
1285   struct symbol *sym = NULL;
1286
1287   char *symname = NULL;
1288
1289   char ntype = '\0';
1290   char *nclass = NULL;
1291   char *ncategory = NULL;
1292   char *nselector = NULL;
1293
1294   unsigned int csym = 0;
1295   unsigned int cdebug = 0;
1296
1297   static char *tmp = NULL;
1298   static unsigned int tmplen = 0;
1299
1300   CHECK (nsym != NULL);
1301   CHECK (ndebug != NULL);
1302
1303   if (symtab)
1304     block = BLOCKVECTOR_BLOCK (BLOCKVECTOR (symtab), STATIC_BLOCK);
1305
1306   ALL_MSYMBOLS (objfile, msymbol)
1307     {
1308       QUIT;
1309
1310       if ((msymbol->type != mst_text) && (msymbol->type != mst_file_text))
1311         /* Not a function or method.  */
1312         continue;
1313
1314       if (symtab)
1315         if ((SYMBOL_VALUE_ADDRESS (msymbol) <  BLOCK_START (block)) ||
1316             (SYMBOL_VALUE_ADDRESS (msymbol) >= BLOCK_END (block)))
1317           /* Not in the specified symtab.  */
1318           continue;
1319
1320       symname = SYMBOL_DEMANGLED_NAME (msymbol);
1321       if (symname == NULL)
1322         symname = SYMBOL_NAME (msymbol);
1323       if (symname == NULL)
1324         continue;
1325
1326       if ((symname[0] != '-' && symname[0] != '+') || (symname[1] != '['))
1327         /* Not a method name.  */
1328         continue;
1329       
1330       while ((strlen (symname) + 1) >= tmplen)
1331         {
1332           tmplen = (tmplen == 0) ? 1024 : tmplen * 2;
1333           tmp = xrealloc (tmp, tmplen);
1334         }
1335       strcpy (tmp, symname);
1336
1337       if (parse_method (tmp, &ntype, &nclass, &ncategory, &nselector) == NULL)
1338         continue;
1339       
1340       if ((type != '\0') && (ntype != type))
1341         continue;
1342
1343       if ((class != NULL) 
1344           && ((nclass == NULL) || (strcmp (class, nclass) != 0)))
1345         continue;
1346
1347       if ((category != NULL) && 
1348           ((ncategory == NULL) || (strcmp (category, ncategory) != 0)))
1349         continue;
1350
1351       if ((selector != NULL) && 
1352           ((nselector == NULL) || (strcmp (selector, nselector) != 0)))
1353         continue;
1354
1355       sym = find_pc_function (SYMBOL_VALUE_ADDRESS (msymbol));
1356       if (sym != NULL)
1357         {
1358           const char *newsymname = SYMBOL_DEMANGLED_NAME (sym);
1359           
1360           if (newsymname == NULL)
1361             newsymname = SYMBOL_NAME (sym);
1362           if (strcmp (symname, newsymname) == 0)
1363             {
1364               /* Found a high-level method sym: swap it into the
1365                  lower part of sym_arr (below num_debuggable).  */
1366               if (syms != NULL)
1367                 {
1368                   syms[csym] = syms[cdebug];
1369                   syms[cdebug] = sym;
1370                 }
1371               csym++;
1372               cdebug++;
1373             }
1374           else
1375             {
1376               warning (
1377 "debugging symbol \"%s\" does not match minimal symbol (\"%s\"); ignoring",
1378                        newsymname, symname);
1379               if (syms != NULL)
1380                 syms[csym] = (struct symbol *) msymbol;
1381               csym++;
1382             }
1383         }
1384       else 
1385         {
1386           /* Found a non-debuggable method symbol.  */
1387           if (syms != NULL)
1388             syms[csym] = (struct symbol *) msymbol;
1389           csym++;
1390         }
1391     }
1392
1393   if (nsym != NULL)
1394     *nsym = csym;
1395   if (ndebug != NULL)
1396     *ndebug = cdebug;
1397 }
1398
1399 char *find_imps (struct symtab *symtab, struct block *block,
1400                  char *method, struct symbol **syms, 
1401                  unsigned int *nsym, unsigned int *ndebug)
1402 {
1403   char type = '\0';
1404   char *class = NULL;
1405   char *category = NULL;
1406   char *selector = NULL;
1407
1408   unsigned int csym = 0;
1409   unsigned int cdebug = 0;
1410
1411   unsigned int ncsym = 0;
1412   unsigned int ncdebug = 0;
1413
1414   char *buf = NULL;
1415   char *tmp = NULL;
1416
1417   CHECK (nsym != NULL);
1418   CHECK (ndebug != NULL);
1419
1420   if (nsym != NULL)
1421     *nsym = 0;
1422   if (ndebug != NULL)
1423     *ndebug = 0;
1424
1425   buf = (char *) alloca (strlen (method) + 1);
1426   strcpy (buf, method);
1427   tmp = parse_method (buf, &type, &class, &category, &selector);
1428
1429   if (tmp == NULL) {
1430     
1431     struct symtab *sym_symtab = NULL;
1432     struct symbol *sym = NULL;
1433     struct minimal_symbol *msym = NULL;
1434     
1435     strcpy (buf, method);
1436     tmp = parse_selector (buf, &selector);
1437     
1438     if (tmp == NULL)
1439       return NULL;
1440     
1441     sym = lookup_symbol (selector, block, VAR_NAMESPACE, 0, &sym_symtab);
1442     if (sym != NULL) 
1443       {
1444         if (syms)
1445           syms[csym] = sym;
1446         csym++;
1447         cdebug++;
1448       }
1449
1450     if (sym == NULL)
1451       msym = lookup_minimal_symbol (selector, 0, 0);
1452
1453     if (msym != NULL) 
1454       {
1455         if (syms)
1456           syms[csym] = (struct symbol *)msym;
1457         csym++;
1458       }
1459   }
1460
1461   if (syms != NULL)
1462     find_methods (symtab, type, class, category, selector, 
1463                   syms + csym, &ncsym, &ncdebug);
1464   else
1465     find_methods (symtab, type, class, category, selector, 
1466                   NULL, &ncsym, &ncdebug);
1467
1468   /* If we didn't find any methods, just return.  */
1469   if (ncsym == 0 && ncdebug == 0)
1470     return method;
1471
1472   /* Take debug symbols from the second batch of symbols and swap them
1473    * with debug symbols from the first batch.  Repeat until either the
1474    * second section is out of debug symbols or the first section is
1475    * full of debug symbols.  Either way we have all debug symbols
1476    * packed to the beginning of the buffer.  
1477    */
1478
1479   if (syms != NULL) 
1480     {
1481       while ((cdebug < csym) && (ncdebug > 0))
1482         {
1483           struct symbol *s = NULL;
1484           /* First non-debugging symbol.  */
1485           unsigned int i = cdebug;
1486           /* Last of second batch of debug symbols.  */
1487           unsigned int j = csym + ncdebug - 1;
1488
1489           s = syms[j];
1490           syms[j] = syms[i];
1491           syms[i] = s;
1492
1493           /* We've moved a symbol from the second debug section to the
1494              first one.  */
1495           cdebug++;
1496           ncdebug--;
1497         }
1498     }
1499
1500   csym += ncsym;
1501   cdebug += ncdebug;
1502
1503   if (nsym != NULL)
1504     *nsym = csym;
1505   if (ndebug != NULL)
1506     *ndebug = cdebug;
1507
1508   if (syms == NULL)
1509     return method + (tmp - buf);
1510
1511   if (csym > 1)
1512     {
1513       /* Sort debuggable symbols.  */
1514       if (cdebug > 1)
1515         qsort (syms, cdebug, sizeof (struct minimal_symbol *), 
1516                compare_classes);
1517       
1518       /* Sort minimal_symbols.  */
1519       if ((csym - cdebug) > 1)
1520         qsort (&syms[cdebug], csym - cdebug, 
1521                sizeof (struct minimal_symbol *), compare_classes);
1522     }
1523   /* Terminate the sym_arr list.  */
1524   syms[csym] = 0;
1525
1526   return method + (tmp - buf);
1527 }
1528
1529 void 
1530 print_object_command (char *args, int from_tty)
1531 {
1532   struct value *object, *function, *description;
1533   CORE_ADDR string_addr, object_addr;
1534   int i = 0;
1535   char c = -1;
1536
1537   if (!args || !*args)
1538     error (
1539 "The 'print-object' command requires an argument (an Objective-C object)");
1540
1541   {
1542     struct expression *expr = parse_expression (args);
1543     register struct cleanup *old_chain = 
1544       make_cleanup (free_current_contents, &expr);
1545     int pc = 0;
1546
1547     object = expr->language_defn->evaluate_exp (builtin_type_void_data_ptr,
1548                                                 expr, &pc, EVAL_NORMAL);
1549     do_cleanups (old_chain);
1550   }
1551
1552   /* Validate the address for sanity.  */
1553   object_addr = value_as_long (object);
1554   read_memory (object_addr, &c, 1);
1555
1556   function = find_function_in_inferior ("_NSPrintForDebugger");
1557   if (function == NULL)
1558     error ("Unable to locate _NSPrintForDebugger in child process");
1559
1560   description = call_function_by_hand (function, 1, &object);
1561
1562   string_addr = value_as_long (description);
1563   if (string_addr == 0)
1564     error ("object returns null description");
1565
1566   read_memory (string_addr + i++, &c, 1);
1567   if (c != '\0')
1568     do
1569       { /* Read and print characters up to EOS.  */
1570         QUIT;
1571         printf_filtered ("%c", c);
1572         read_memory (string_addr + i++, &c, 1);
1573       } while (c != 0);
1574   else
1575     printf_filtered("<object returns empty description>");
1576   printf_filtered ("\n");
1577 }
1578
1579 /* The data structure 'methcalls' is used to detect method calls (thru
1580  * ObjC runtime lib functions objc_msgSend, objc_msgSendSuper, etc.),
1581  * and ultimately find the method being called. 
1582  */
1583
1584 struct objc_methcall {
1585   char *name;
1586  /* Return instance method to be called.  */
1587   int (*stop_at) (CORE_ADDR, CORE_ADDR *);
1588   /* Start of pc range corresponding to method invocation.  */
1589   CORE_ADDR begin;
1590   /* End of pc range corresponding to method invocation.  */
1591   CORE_ADDR end;
1592 };
1593
1594 static int resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc);
1595 static int resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1596 static int resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc);
1597 static int resolve_msgsend_super_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1598
1599 static struct objc_methcall methcalls[] = {
1600   { "_objc_msgSend", resolve_msgsend, 0, 0},
1601   { "_objc_msgSend_stret", resolve_msgsend_stret, 0, 0},
1602   { "_objc_msgSendSuper", resolve_msgsend_super, 0, 0},
1603   { "_objc_msgSendSuper_stret", resolve_msgsend_super_stret, 0, 0},
1604   { "_objc_getClass", NULL, 0, 0},
1605   { "_objc_getMetaClass", NULL, 0, 0}
1606 };
1607
1608 #define nmethcalls (sizeof (methcalls) / sizeof (methcalls[0]))
1609
1610 /* The following function, "find_objc_msgsend", fills in the data
1611  * structure "objc_msgs" by finding the addresses of each of the
1612  * (currently four) functions that it holds (of which objc_msgSend is
1613  * the first).  This must be called each time symbols are loaded, in
1614  * case the functions have moved for some reason.  
1615  */
1616
1617 void 
1618 find_objc_msgsend (void)
1619 {
1620   unsigned int i;
1621   for (i = 0; i < nmethcalls; i++) {
1622
1623     struct minimal_symbol *func;
1624
1625     /* Try both with and without underscore.  */
1626     func = lookup_minimal_symbol (methcalls[i].name, NULL, NULL);
1627     if ((func == NULL) && (methcalls[i].name[0] == '_')) {
1628       func = lookup_minimal_symbol (methcalls[i].name + 1, NULL, NULL);
1629     }
1630     if (func == NULL) { 
1631       methcalls[i].begin = 0;
1632       methcalls[i].end = 0;
1633       continue; 
1634     }
1635     
1636     methcalls[i].begin = SYMBOL_VALUE_ADDRESS (func);
1637     do {
1638       methcalls[i].end = SYMBOL_VALUE_ADDRESS (++func);
1639     } while (methcalls[i].begin == methcalls[i].end);
1640   }
1641 }
1642
1643 /* find_objc_msgcall (replaces pc_off_limits)
1644  *
1645  * ALL that this function now does is to determine whether the input
1646  * address ("pc") is the address of one of the Objective-C message
1647  * dispatch functions (mainly objc_msgSend or objc_msgSendSuper), and
1648  * if so, it returns the address of the method that will be called.
1649  *
1650  * The old function "pc_off_limits" used to do a lot of other things
1651  * in addition, such as detecting shared library jump stubs and
1652  * returning the address of the shlib function that would be called.
1653  * That functionality has been moved into the SKIP_TRAMPOLINE_CODE and
1654  * IN_SOLIB_TRAMPOLINE macros, which are resolved in the target-
1655  * dependent modules.  
1656  */
1657
1658 struct objc_submethod_helper_data {
1659   int (*f) (CORE_ADDR, CORE_ADDR *);
1660   CORE_ADDR pc;
1661   CORE_ADDR *new_pc;
1662 };
1663
1664 int 
1665 find_objc_msgcall_submethod_helper (void * arg)
1666 {
1667   struct objc_submethod_helper_data *s = 
1668     (struct objc_submethod_helper_data *) arg;
1669
1670   if (s->f (s->pc, s->new_pc) == 0) 
1671     return 1;
1672   else 
1673     return 0;
1674 }
1675
1676 int 
1677 find_objc_msgcall_submethod (int (*f) (CORE_ADDR, CORE_ADDR *),
1678                              CORE_ADDR pc, 
1679                              CORE_ADDR *new_pc)
1680 {
1681   struct objc_submethod_helper_data s;
1682
1683   s.f = f;
1684   s.pc = pc;
1685   s.new_pc = new_pc;
1686
1687   if (catch_errors (find_objc_msgcall_submethod_helper,
1688                     (void *) &s,
1689                     "Unable to determine target of Objective-C method call (ignoring):\n",
1690                     RETURN_MASK_ALL) == 0) 
1691     return 1;
1692   else 
1693     return 0;
1694 }
1695
1696 int 
1697 find_objc_msgcall (CORE_ADDR pc, CORE_ADDR *new_pc)
1698 {
1699   unsigned int i;
1700
1701   find_objc_msgsend ();
1702   if (new_pc != NULL) { *new_pc = 0; }
1703
1704   for (i = 0; i < nmethcalls; i++) 
1705     if ((pc >= methcalls[i].begin) && (pc < methcalls[i].end)) 
1706       {
1707         if (methcalls[i].stop_at != NULL) 
1708           return find_objc_msgcall_submethod (methcalls[i].stop_at, 
1709                                               pc, new_pc);
1710         else 
1711           return 0;
1712       }
1713
1714   return 0;
1715 }
1716
1717 void
1718 _initialize_objc_language (void)
1719 {
1720   add_language (&objc_language_defn);
1721   add_info ("selectors", selectors_info,    /* INFO SELECTORS command.  */
1722             "All Objective-C selectors, or those matching REGEXP.");
1723   add_info ("classes", classes_info,        /* INFO CLASSES   command.  */
1724             "All Objective-C classes, or those matching REGEXP.");
1725   add_com ("print-object", class_vars, print_object_command, 
1726            "Ask an Objective-C object to print itself.");
1727   add_com_alias ("po", "print-object", class_vars, 1);
1728 }
1729
1730 #if defined (__powerpc__) || defined (__ppc__)
1731 static unsigned long FETCH_ARGUMENT (int i)
1732 {
1733   return read_register (3 + i);
1734 }
1735 #elif defined (__i386__)
1736 static unsigned long FETCH_ARGUMENT (int i)
1737 {
1738   CORE_ADDR stack = read_register (SP_REGNUM);
1739   return read_memory_unsigned_integer (stack + (4 * (i + 1)), 4);
1740 }
1741 #elif defined (__sparc__)
1742 static unsigned long FETCH_ARGUMENT (int i)
1743 {
1744   return read_register (O0_REGNUM + i);
1745 }
1746 #elif defined (__hppa__) || defined (__hppa)
1747 static unsigned long FETCH_ARGUMENT (int i)
1748 {
1749   return read_register (R0_REGNUM + 26 - i);
1750 }
1751 #else
1752 #error unknown architecture
1753 #endif
1754
1755 #if defined (__hppa__) || defined (__hppa)
1756 static CORE_ADDR CONVERT_FUNCPTR (CORE_ADDR pc)
1757 {
1758   if (pc & 0x2)
1759     pc = (CORE_ADDR) read_memory_integer (pc & ~0x3, 4);
1760
1761   return pc;
1762 }
1763 #else
1764 static CORE_ADDR CONVERT_FUNCPTR (CORE_ADDR pc)
1765 {
1766   return pc;
1767 }
1768 #endif
1769
1770 static void 
1771 read_objc_method (CORE_ADDR addr, struct objc_method *method)
1772 {
1773   method->name  = read_memory_unsigned_integer (addr + 0, 4);
1774   method->types = read_memory_unsigned_integer (addr + 4, 4);
1775   method->imp   = read_memory_unsigned_integer (addr + 8, 4);
1776 }
1777
1778 static 
1779 unsigned long read_objc_methlist_nmethods (CORE_ADDR addr)
1780 {
1781   return read_memory_unsigned_integer (addr + 4, 4);
1782 }
1783
1784 static void 
1785 read_objc_methlist_method (CORE_ADDR addr, unsigned long num, 
1786                            struct objc_method *method)
1787 {
1788   CHECK_FATAL (num < read_objc_methlist_nmethods (addr));
1789   read_objc_method (addr + 8 + (12 * num), method);
1790 }
1791   
1792 static void 
1793 read_objc_object (CORE_ADDR addr, struct objc_object *object)
1794 {
1795   object->isa = read_memory_unsigned_integer (addr, 4);
1796 }
1797
1798 static void 
1799 read_objc_super (CORE_ADDR addr, struct objc_super *super)
1800 {
1801   super->receiver = read_memory_unsigned_integer (addr, 4);
1802   super->class = read_memory_unsigned_integer (addr + 4, 4);
1803 };
1804
1805 static void 
1806 read_objc_class (CORE_ADDR addr, struct objc_class *class)
1807 {
1808   class->isa = read_memory_unsigned_integer (addr, 4);
1809   class->super_class = read_memory_unsigned_integer (addr + 4, 4);
1810   class->name = read_memory_unsigned_integer (addr + 8, 4);
1811   class->version = read_memory_unsigned_integer (addr + 12, 4);
1812   class->info = read_memory_unsigned_integer (addr + 16, 4);
1813   class->instance_size = read_memory_unsigned_integer (addr + 18, 4);
1814   class->ivars = read_memory_unsigned_integer (addr + 24, 4);
1815   class->methods = read_memory_unsigned_integer (addr + 28, 4);
1816   class->cache = read_memory_unsigned_integer (addr + 32, 4);
1817   class->protocols = read_memory_unsigned_integer (addr + 36, 4);
1818 }
1819
1820 CORE_ADDR
1821 find_implementation_from_class (CORE_ADDR class, CORE_ADDR sel)
1822 {
1823   CORE_ADDR subclass = class;
1824
1825   while (subclass != 0) 
1826     {
1827
1828       struct objc_class class_str;
1829       unsigned mlistnum = 0;
1830
1831       read_objc_class (subclass, &class_str);
1832
1833       for (;;) 
1834         {
1835           CORE_ADDR mlist;
1836           unsigned long nmethods;
1837           unsigned long i;
1838       
1839           mlist = read_memory_unsigned_integer (class_str.methods + 
1840                                                 (4 * mlistnum), 4);
1841           if (mlist == 0) 
1842             break;
1843
1844           nmethods = read_objc_methlist_nmethods (mlist);
1845
1846           for (i = 0; i < nmethods; i++) 
1847             {
1848               struct objc_method meth_str;
1849               read_objc_methlist_method (mlist, i, &meth_str);
1850
1851 #if 0
1852               fprintf (stderr, 
1853                        "checking method 0x%lx against selector 0x%lx\n", 
1854                        meth_str.name, sel);
1855 #endif
1856
1857               if (meth_str.name == sel) 
1858                 return CONVERT_FUNCPTR (meth_str.imp);
1859             }
1860           mlistnum++;
1861         }
1862       subclass = class_str.super_class;
1863     }
1864
1865   return 0;
1866 }
1867
1868 CORE_ADDR
1869 find_implementation (CORE_ADDR object, CORE_ADDR sel)
1870 {
1871   struct objc_object ostr;
1872
1873   if (object == 0)
1874     return 0;
1875   read_objc_object (object, &ostr);
1876   if (ostr.isa == 0)
1877     return 0;
1878
1879   return find_implementation_from_class (ostr.isa, sel);
1880 }
1881
1882 static int
1883 resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc)
1884 {
1885   CORE_ADDR object;
1886   CORE_ADDR sel;
1887   CORE_ADDR res;
1888
1889   object = FETCH_ARGUMENT (0);
1890   sel = FETCH_ARGUMENT (1);
1891
1892   res = find_implementation (object, sel);
1893   if (new_pc != 0)
1894     *new_pc = res;
1895   if (res == 0)
1896     return 1;
1897   return 0;
1898 }
1899
1900 static int
1901 resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc)
1902 {
1903   CORE_ADDR object;
1904   CORE_ADDR sel;
1905   CORE_ADDR res;
1906
1907   object = FETCH_ARGUMENT (1);
1908   sel = FETCH_ARGUMENT (2);
1909
1910   res = find_implementation (object, sel);
1911   if (new_pc != 0)
1912     *new_pc = res;
1913   if (res == 0)
1914     return 1;
1915   return 0;
1916 }
1917
1918 static int
1919 resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc)
1920 {
1921   struct objc_super sstr;
1922
1923   CORE_ADDR super;
1924   CORE_ADDR sel;
1925   CORE_ADDR res;
1926
1927   super = FETCH_ARGUMENT (0);
1928   sel = FETCH_ARGUMENT (1);
1929
1930   read_objc_super (super, &sstr);
1931   if (sstr.class == 0)
1932     return 0;
1933   
1934   res = find_implementation_from_class (sstr.class, 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_stret (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 (1);
1952   sel = FETCH_ARGUMENT (2);
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 }