Automatic date update in version.in
[binutils-gdb.git] / gdb / objc-lang.c
blobe492c82845b3889b6e6dde7f6c9129e8300596dc
1 /* Objective-C language support routines for GDB, the GNU debugger.
3 Copyright (C) 2002-2024 Free Software Foundation, Inc.
5 Contributed by Apple Computer, Inc.
6 Written by Michael Snyder.
8 This file is part of GDB.
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 3 of the License, or
13 (at your option) any later version.
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.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "symtab.h"
24 #include "gdbtypes.h"
25 #include "expression.h"
26 #include "parser-defs.h"
27 #include "language.h"
28 #include "varobj.h"
29 #include "c-lang.h"
30 #include "objc-lang.h"
31 #include "complaints.h"
32 #include "value.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "target.h"
36 #include "gdbcore.h"
37 #include "gdbcmd.h"
38 #include "frame.h"
39 #include "gdbsupport/gdb_regex.h"
40 #include "regcache.h"
41 #include "block.h"
42 #include "infcall.h"
43 #include "valprint.h"
44 #include "cli/cli-utils.h"
45 #include "c-exp.h"
47 #include <ctype.h>
48 #include <algorithm>
50 struct objc_object {
51 CORE_ADDR isa;
54 struct objc_class {
55 CORE_ADDR isa;
56 CORE_ADDR super_class;
57 CORE_ADDR name;
58 long version;
59 long info;
60 long instance_size;
61 CORE_ADDR ivars;
62 CORE_ADDR methods;
63 CORE_ADDR cache;
64 CORE_ADDR protocols;
67 struct objc_super {
68 CORE_ADDR receiver;
69 CORE_ADDR theclass;
72 struct objc_method {
73 CORE_ADDR name;
74 CORE_ADDR types;
75 CORE_ADDR imp;
78 static const registry<objfile>::key<unsigned int> objc_objfile_data;
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. */
84 struct symbol *
85 lookup_struct_typedef (const char *name, const struct block *block, int noerr)
87 struct symbol *sym;
89 sym = lookup_symbol (name, block, SEARCH_STRUCT_DOMAIN, 0).symbol;
91 if (sym == NULL)
93 if (noerr)
94 return 0;
95 else
96 error (_("No struct type named %s."), name);
98 if (sym->type ()->code () != TYPE_CODE_STRUCT)
100 if (noerr)
101 return 0;
102 else
103 error (_("This context has class, union or enum %s, not a struct."),
104 name);
106 return sym;
109 CORE_ADDR
110 lookup_objc_class (struct gdbarch *gdbarch, const char *classname)
112 struct type *char_type = builtin_type (gdbarch)->builtin_char;
113 struct value * function, *classval;
115 if (! target_has_execution ())
117 /* Can't call into inferior to lookup class. */
118 return 0;
121 if (lookup_minimal_symbol("objc_lookUpClass", 0, 0).minsym)
122 function = find_function_in_inferior("objc_lookUpClass", NULL);
123 else if (lookup_minimal_symbol ("objc_lookup_class", 0, 0).minsym)
124 function = find_function_in_inferior("objc_lookup_class", NULL);
125 else
127 complaint (_("no way to lookup Objective-C classes"));
128 return 0;
131 classval = value_string (classname, strlen (classname) + 1, char_type);
132 classval = value_coerce_array (classval);
133 return (CORE_ADDR) value_as_long (call_function_by_hand (function,
134 NULL,
135 classval));
138 CORE_ADDR
139 lookup_child_selector (struct gdbarch *gdbarch, const char *selname)
141 struct type *char_type = builtin_type (gdbarch)->builtin_char;
142 struct value * function, *selstring;
144 if (! target_has_execution ())
146 /* Can't call into inferior to lookup selector. */
147 return 0;
150 if (lookup_minimal_symbol("sel_getUid", 0, 0).minsym)
151 function = find_function_in_inferior("sel_getUid", NULL);
152 else if (lookup_minimal_symbol ("sel_get_any_uid", 0, 0).minsym)
153 function = find_function_in_inferior("sel_get_any_uid", NULL);
154 else
156 complaint (_("no way to lookup Objective-C selectors"));
157 return 0;
160 selstring = value_coerce_array (value_string (selname,
161 strlen (selname) + 1,
162 char_type));
163 return value_as_long (call_function_by_hand (function, NULL, selstring));
166 struct value *
167 value_nsstring (struct gdbarch *gdbarch, const char *ptr, int len)
169 struct type *char_type = builtin_type (gdbarch)->builtin_char;
170 struct value *stringValue[3];
171 struct value *function, *nsstringValue;
172 struct symbol *sym;
173 struct type *type;
175 if (!target_has_execution ())
176 return 0; /* Can't call into inferior to create NSString. */
178 stringValue[2] = value_string(ptr, len, char_type);
179 stringValue[2] = value_coerce_array(stringValue[2]);
180 /* _NSNewStringFromCString replaces "istr" after Lantern2A. */
181 if (lookup_minimal_symbol("_NSNewStringFromCString", 0, 0).minsym)
183 function = find_function_in_inferior("_NSNewStringFromCString", NULL);
184 nsstringValue = call_function_by_hand(function, NULL, stringValue[2]);
186 else if (lookup_minimal_symbol("istr", 0, 0).minsym)
188 function = find_function_in_inferior("istr", NULL);
189 nsstringValue = call_function_by_hand(function, NULL, stringValue[2]);
191 else if (lookup_minimal_symbol("+[NSString stringWithCString:]", 0, 0).minsym)
193 function
194 = find_function_in_inferior("+[NSString stringWithCString:]", NULL);
195 type = builtin_type (gdbarch)->builtin_long;
197 stringValue[0] = value_from_longest
198 (type, lookup_objc_class (gdbarch, "NSString"));
199 stringValue[1] = value_from_longest
200 (type, lookup_child_selector (gdbarch, "stringWithCString:"));
201 nsstringValue = call_function_by_hand(function, NULL, stringValue);
203 else
204 error (_("NSString: internal error -- no way to create new NSString"));
206 sym = lookup_struct_typedef("NSString", 0, 1);
207 if (sym == NULL)
208 sym = lookup_struct_typedef("NXString", 0, 1);
209 if (sym == NULL)
210 type = builtin_type (gdbarch)->builtin_data_ptr;
211 else
212 type = lookup_pointer_type(sym->type ());
214 nsstringValue->deprecated_set_type (type);
215 return nsstringValue;
218 /* Class representing the Objective-C language. */
220 class objc_language : public language_defn
222 public:
223 objc_language ()
224 : language_defn (language_objc)
225 { /* Nothing. */ }
227 /* See language.h. */
229 const char *name () const override
230 { return "objective-c"; }
232 /* See language.h. */
234 const char *natural_name () const override
235 { return "Objective-C"; }
237 /* See language.h. */
239 const std::vector<const char *> &filename_extensions () const override
241 static const std::vector<const char *> extensions = { ".m" };
242 return extensions;
245 /* See language.h. */
246 void language_arch_info (struct gdbarch *gdbarch,
247 struct language_arch_info *lai) const override
249 c_language_arch_info (gdbarch, lai);
252 /* See language.h. */
253 bool sniff_from_mangled_name
254 (const char *mangled, gdb::unique_xmalloc_ptr<char> *demangled)
255 const override
257 *demangled = demangle_symbol (mangled, 0);
258 return *demangled != NULL;
261 /* See language.h. */
263 gdb::unique_xmalloc_ptr<char> demangle_symbol (const char *mangled,
264 int options) const override;
266 /* See language.h. */
268 bool can_print_type_offsets () const override
270 return true;
273 /* See language.h. */
275 void print_type (struct type *type, const char *varstring,
276 struct ui_file *stream, int show, int level,
277 const struct type_print_options *flags) const override
279 c_print_type (type, varstring, stream, show, level, la_language, flags);
282 /* See language.h. */
284 CORE_ADDR skip_trampoline (const frame_info_ptr &frame,
285 CORE_ADDR stop_pc) const override
287 struct gdbarch *gdbarch = get_frame_arch (frame);
288 CORE_ADDR real_stop_pc;
289 CORE_ADDR method_stop_pc;
291 /* Determine if we are currently in the Objective-C dispatch function.
292 If so, get the address of the method function that the dispatcher
293 would call and use that as the function to step into instead. Also
294 skip over the trampoline for the function (if any). This is better
295 for the user since they are only interested in stepping into the
296 method function anyway. */
298 real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
300 if (real_stop_pc != 0)
301 find_objc_msgcall (real_stop_pc, &method_stop_pc);
302 else
303 find_objc_msgcall (stop_pc, &method_stop_pc);
305 if (method_stop_pc)
307 real_stop_pc = gdbarch_skip_trampoline_code
308 (gdbarch, frame, method_stop_pc);
309 if (real_stop_pc == 0)
310 real_stop_pc = method_stop_pc;
313 return real_stop_pc;
316 /* See language.h. */
318 const char *name_of_this () const override
319 { return "self"; }
321 /* See language.h. */
323 enum macro_expansion macro_expansion () const override
324 { return macro_expansion_c; }
327 /* See declaration of objc_language::demangle_symbol above. */
329 gdb::unique_xmalloc_ptr<char>
330 objc_language::demangle_symbol (const char *mangled, int options) const
332 char *demangled, *cp;
334 if (mangled[0] == '_'
335 && (mangled[1] == 'i' || mangled[1] == 'c')
336 && mangled[2] == '_')
338 cp = demangled = (char *) xmalloc (strlen (mangled) + 2);
340 if (mangled[1] == 'i')
341 *cp++ = '-'; /* for instance method */
342 else
343 *cp++ = '+'; /* for class method */
345 *cp++ = '['; /* opening left brace */
346 strcpy(cp, mangled+3); /* Tack on the rest of the mangled name. */
348 while (*cp != '\0' && *cp == '_')
349 cp++; /* Skip any initial underbars in class
350 name. */
352 cp = strchr(cp, '_');
353 if (cp == nullptr) /* Find first non-initial underbar. */
355 xfree(demangled); /* not mangled name */
356 return nullptr;
358 if (cp[1] == '_') /* Easy case: no category name. */
360 *cp++ = ' '; /* Replace two '_' with one ' '. */
361 strcpy(cp, mangled + (cp - demangled) + 2);
363 else
365 *cp++ = '('; /* Less easy case: category name. */
366 cp = strchr(cp, '_');
367 if (cp == nullptr)
369 xfree(demangled); /* not mangled name */
370 return nullptr;
372 *cp++ = ')';
373 *cp++ = ' '; /* Overwriting 1st char of method name... */
374 strcpy(cp, mangled + (cp - demangled)); /* Get it back. */
377 while (*cp != '\0' && *cp == '_')
378 cp++; /* Skip any initial underbars in
379 method name. */
381 for (; *cp != '\0'; cp++)
382 if (*cp == '_')
383 *cp = ':'; /* Replace remaining '_' with ':'. */
385 *cp++ = ']'; /* closing right brace */
386 *cp++ = 0; /* string terminator */
387 return gdb::unique_xmalloc_ptr<char> (demangled);
389 else
390 return nullptr; /* Not an objc mangled name. */
393 /* Single instance of the class representing the Objective-C language. */
395 static objc_language objc_language_defn;
398 * ObjC:
399 * Following functions help construct Objective-C message calls.
402 struct selname /* For parsing Objective-C. */
404 struct selname *next;
405 char *msglist_sel;
406 int msglist_len;
409 static int msglist_len;
410 static struct selname *selname_chain;
411 static char *msglist_sel;
413 void
414 start_msglist(void)
416 struct selname *newobj = XNEW (struct selname);
418 newobj->next = selname_chain;
419 newobj->msglist_len = msglist_len;
420 newobj->msglist_sel = msglist_sel;
421 msglist_len = 0;
422 msglist_sel = (char *)xmalloc(1);
423 *msglist_sel = 0;
424 selname_chain = newobj;
427 void
428 add_msglist(struct stoken *str, int addcolon)
430 char *s;
431 const char *p;
432 int len, plen;
434 if (str == 0) /* Unnamed arg, or... */
436 if (addcolon == 0) /* variable number of args. */
438 msglist_len++;
439 return;
441 p = "";
442 plen = 0;
444 else
446 p = str->ptr;
447 plen = str->length;
449 len = plen + strlen(msglist_sel) + 2;
450 s = (char *)xmalloc(len);
451 strcpy(s, msglist_sel);
452 strncat(s, p, plen);
453 xfree(msglist_sel);
454 msglist_sel = s;
455 if (addcolon)
457 s[len-2] = ':';
458 s[len-1] = 0;
459 msglist_len++;
461 else
462 s[len-2] = '\0';
466 end_msglist (struct parser_state *ps)
468 int val = msglist_len;
469 struct selname *sel = selname_chain;
470 char *p = msglist_sel;
471 CORE_ADDR selid;
473 std::vector<expr::operation_up> args = ps->pop_vector (val);
474 expr::operation_up target = ps->pop ();
476 selname_chain = sel->next;
477 msglist_len = sel->msglist_len;
478 msglist_sel = sel->msglist_sel;
479 selid = lookup_child_selector (ps->gdbarch (), p);
480 if (!selid)
481 error (_("Can't find selector \"%s\""), p);
483 ps->push_new<expr::objc_msgcall_operation> (selid, std::move (target),
484 std::move (args));
486 xfree(p);
487 xfree(sel);
489 return val;
493 * Function: specialcmp (const char *a, const char *b)
495 * Special strcmp: treats ']' and ' ' as end-of-string.
496 * Used for qsorting lists of objc methods (either by class or selector).
499 static int
500 specialcmp (const char *a, const char *b)
502 while (*a && *a != ' ' && *a != ']' && *b && *b != ' ' && *b != ']')
504 if (*a != *b)
505 return *a - *b;
506 a++, b++;
508 if (*a && *a != ' ' && *a != ']')
509 return 1; /* a is longer therefore greater. */
510 if (*b && *b != ' ' && *b != ']')
511 return -1; /* a is shorter therefore lesser. */
512 return 0; /* a and b are identical. */
516 * Function: compare_selectors (const void *, const void *)
518 * Comparison function for use with qsort. Arguments are symbols or
519 * msymbols Compares selector part of objc method name alphabetically.
522 static int
523 compare_selectors (const void *a, const void *b)
525 const char *aname, *bname;
527 aname = (*(struct symbol **) a)->print_name ();
528 bname = (*(struct symbol **) b)->print_name ();
529 if (aname == NULL || bname == NULL)
530 error (_("internal: compare_selectors(1)"));
532 aname = strchr(aname, ' ');
533 bname = strchr(bname, ' ');
534 if (aname == NULL || bname == NULL)
535 error (_("internal: compare_selectors(2)"));
537 return specialcmp (aname+1, bname+1);
541 * Function: selectors_info (regexp, from_tty)
543 * Implements the "Info selectors" command. Takes an optional regexp
544 * arg. Lists all objective c selectors that match the regexp. Works
545 * by grepping thru all symbols for objective c methods. Output list
546 * is sorted and uniqued.
549 static void
550 info_selectors_command (const char *regexp, int from_tty)
552 const char *name;
553 char *val;
554 int matches = 0;
555 int maxlen = 0;
556 int ix;
557 char myregexp[2048];
558 char asel[256];
559 struct symbol **sym_arr;
560 int plusminus = 0;
562 if (regexp == NULL)
563 strcpy(myregexp, ".*]"); /* Null input, match all objc methods. */
564 else
566 if (*regexp == '+' || *regexp == '-')
567 { /* User wants only class methods or only instance methods. */
568 plusminus = *regexp++;
569 while (*regexp == ' ' || *regexp == '\t')
570 regexp++;
572 if (*regexp == '\0')
573 strcpy(myregexp, ".*]");
574 else
576 /* Allow a few extra bytes because of the strcat below. */
577 if (sizeof (myregexp) < strlen (regexp) + 4)
578 error (_("Regexp is too long: %s"), regexp);
579 strcpy(myregexp, regexp);
580 if (myregexp[strlen(myregexp) - 1] == '$') /* end of selector */
581 myregexp[strlen(myregexp) - 1] = ']'; /* end of method name */
582 else
583 strcat(myregexp, ".*]");
587 if (regexp != NULL)
589 val = re_comp (myregexp);
590 if (val != 0)
591 error (_("Invalid regexp (%s): %s"), val, regexp);
594 /* First time thru is JUST to get max length and count. */
595 for (objfile *objfile : current_program_space->objfiles ())
597 for (minimal_symbol *msymbol : objfile->msymbols ())
599 QUIT;
600 name = msymbol->natural_name ();
601 if (name
602 && (name[0] == '-' || name[0] == '+')
603 && name[1] == '[') /* Got a method name. */
605 /* Filter for class/instance methods. */
606 if (plusminus && name[0] != plusminus)
607 continue;
608 /* Find selector part. */
609 name = (char *) strchr (name+2, ' ');
610 if (name == NULL)
612 complaint (_("Bad method name '%s'"),
613 msymbol->natural_name ());
614 continue;
616 if (regexp == NULL || re_exec(++name) != 0)
618 const char *mystart = name;
619 const char *myend = strchr (mystart, ']');
621 if (myend && (myend - mystart > maxlen))
622 maxlen = myend - mystart; /* Get longest selector. */
623 matches++;
628 if (matches)
630 gdb_printf (_("Selectors matching \"%s\":\n\n"),
631 regexp ? regexp : "*");
633 sym_arr = XALLOCAVEC (struct symbol *, matches);
634 matches = 0;
635 for (objfile *objfile : current_program_space->objfiles ())
637 for (minimal_symbol *msymbol : objfile->msymbols ())
639 QUIT;
640 name = msymbol->natural_name ();
641 if (name &&
642 (name[0] == '-' || name[0] == '+') &&
643 name[1] == '[') /* Got a method name. */
645 /* Filter for class/instance methods. */
646 if (plusminus && name[0] != plusminus)
647 continue;
648 /* Find selector part. */
649 name = (char *) strchr(name+2, ' ');
650 if (regexp == NULL || re_exec(++name) != 0)
651 sym_arr[matches++] = (struct symbol *) msymbol;
656 qsort (sym_arr, matches, sizeof (struct minimal_symbol *),
657 compare_selectors);
658 /* Prevent compare on first iteration. */
659 asel[0] = 0;
660 for (ix = 0; ix < matches; ix++) /* Now do the output. */
662 char *p = asel;
664 QUIT;
665 name = sym_arr[ix]->natural_name ();
666 name = strchr (name, ' ') + 1;
667 if (p[0] && specialcmp(name, p) == 0)
668 continue; /* Seen this one already (not unique). */
670 /* Copy selector part. */
671 while (*name && *name != ']')
672 *p++ = *name++;
673 *p++ = '\0';
674 /* Print in columns. */
675 puts_tabular(asel, maxlen + 1, 0);
677 begin_line();
679 else
680 gdb_printf (_("No selectors matching \"%s\"\n"),
681 regexp ? regexp : "*");
685 * Function: compare_classes (const void *, const void *)
687 * Comparison function for use with qsort. Arguments are symbols or
688 * msymbols Compares class part of objc method name alphabetically.
691 static int
692 compare_classes (const void *a, const void *b)
694 const char *aname, *bname;
696 aname = (*(struct symbol **) a)->print_name ();
697 bname = (*(struct symbol **) b)->print_name ();
698 if (aname == NULL || bname == NULL)
699 error (_("internal: compare_classes(1)"));
701 return specialcmp (aname+1, bname+1);
705 * Function: classes_info(regexp, from_tty)
707 * Implements the "info classes" command for objective c classes.
708 * Lists all objective c classes that match the optional regexp.
709 * Works by grepping thru the list of objective c methods. List will
710 * be sorted and uniqued (since one class may have many methods).
711 * BUGS: will not list a class that has no methods.
714 static void
715 info_classes_command (const char *regexp, int from_tty)
717 const char *name;
718 char *val;
719 int matches = 0;
720 int maxlen = 0;
721 int ix;
722 char myregexp[2048];
723 char aclass[256];
724 struct symbol **sym_arr;
726 if (regexp == NULL)
727 strcpy(myregexp, ".* "); /* Null input: match all objc classes. */
728 else
730 /* Allow a few extra bytes because of the strcat below. */
731 if (sizeof (myregexp) < strlen (regexp) + 4)
732 error (_("Regexp is too long: %s"), regexp);
733 strcpy(myregexp, regexp);
734 if (myregexp[strlen(myregexp) - 1] == '$')
735 /* In the method name, the end of the class name is marked by ' '. */
736 myregexp[strlen(myregexp) - 1] = ' ';
737 else
738 strcat(myregexp, ".* ");
741 if (regexp != NULL)
743 val = re_comp (myregexp);
744 if (val != 0)
745 error (_("Invalid regexp (%s): %s"), val, regexp);
748 /* First time thru is JUST to get max length and count. */
749 for (objfile *objfile : current_program_space->objfiles ())
751 for (minimal_symbol *msymbol : objfile->msymbols ())
753 QUIT;
754 name = msymbol->natural_name ();
755 if (name &&
756 (name[0] == '-' || name[0] == '+') &&
757 name[1] == '[') /* Got a method name. */
758 if (regexp == NULL || re_exec(name+2) != 0)
760 /* Compute length of classname part. */
761 const char *mystart = name + 2;
762 const char *myend = strchr (mystart, ' ');
764 if (myend && (myend - mystart > maxlen))
765 maxlen = myend - mystart;
766 matches++;
770 if (matches)
772 gdb_printf (_("Classes matching \"%s\":\n\n"),
773 regexp ? regexp : "*");
774 sym_arr = XALLOCAVEC (struct symbol *, matches);
775 matches = 0;
776 for (objfile *objfile : current_program_space->objfiles ())
778 for (minimal_symbol *msymbol : objfile->msymbols ())
780 QUIT;
781 name = msymbol->natural_name ();
782 if (name &&
783 (name[0] == '-' || name[0] == '+') &&
784 name[1] == '[') /* Got a method name. */
785 if (regexp == NULL || re_exec(name+2) != 0)
786 sym_arr[matches++] = (struct symbol *) msymbol;
790 qsort (sym_arr, matches, sizeof (struct minimal_symbol *),
791 compare_classes);
792 /* Prevent compare on first iteration. */
793 aclass[0] = 0;
794 for (ix = 0; ix < matches; ix++) /* Now do the output. */
796 char *p = aclass;
798 QUIT;
799 name = sym_arr[ix]->natural_name ();
800 name += 2;
801 if (p[0] && specialcmp(name, p) == 0)
802 continue; /* Seen this one already (not unique). */
804 /* Copy class part of method name. */
805 while (*name && *name != ' ')
806 *p++ = *name++;
807 *p++ = '\0';
808 /* Print in columns. */
809 puts_tabular(aclass, maxlen + 1, 0);
811 begin_line();
813 else
814 gdb_printf (_("No classes matching \"%s\"\n"), regexp ? regexp : "*");
817 static char *
818 parse_selector (char *method, char **selector)
820 char *s1 = NULL;
821 char *s2 = NULL;
822 int found_quote = 0;
824 char *nselector = NULL;
826 gdb_assert (selector != NULL);
828 s1 = method;
830 s1 = skip_spaces (s1);
831 if (*s1 == '\'')
833 found_quote = 1;
834 s1++;
836 s1 = skip_spaces (s1);
838 nselector = s1;
839 s2 = s1;
841 for (;;)
843 if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
844 *s1++ = *s2;
845 else if (isspace (*s2))
847 else if ((*s2 == '\0') || (*s2 == '\''))
848 break;
849 else
850 return NULL;
851 s2++;
853 *s1++ = '\0';
855 s2 = skip_spaces (s2);
856 if (found_quote)
858 if (*s2 == '\'')
859 s2++;
860 s2 = skip_spaces (s2);
863 if (selector != NULL)
864 *selector = nselector;
866 return s2;
869 static char *
870 parse_method (char *method, char *type, char **theclass,
871 char **category, char **selector)
873 char *s1 = NULL;
874 char *s2 = NULL;
875 int found_quote = 0;
877 char ntype = '\0';
878 char *nclass = NULL;
879 char *ncategory = NULL;
880 char *nselector = NULL;
882 gdb_assert (type != NULL);
883 gdb_assert (theclass != NULL);
884 gdb_assert (category != NULL);
885 gdb_assert (selector != NULL);
887 s1 = method;
889 s1 = skip_spaces (s1);
890 if (*s1 == '\'')
892 found_quote = 1;
893 s1++;
895 s1 = skip_spaces (s1);
897 if ((s1[0] == '+') || (s1[0] == '-'))
898 ntype = *s1++;
900 s1 = skip_spaces (s1);
902 if (*s1 != '[')
903 return NULL;
904 s1++;
906 nclass = s1;
907 while (isalnum (*s1) || (*s1 == '_'))
908 s1++;
910 s2 = s1;
911 s2 = skip_spaces (s2);
913 if (*s2 == '(')
915 s2++;
916 s2 = skip_spaces (s2);
917 ncategory = s2;
918 while (isalnum (*s2) || (*s2 == '_'))
919 s2++;
920 *s2++ = '\0';
923 /* Truncate the class name now that we're not using the open paren. */
924 *s1++ = '\0';
926 nselector = s2;
927 s1 = s2;
929 for (;;)
931 if (isalnum (*s2) || (*s2 == '_') || (*s2 == ':'))
932 *s1++ = *s2;
933 else if (isspace (*s2))
935 else if (*s2 == ']')
936 break;
937 else
938 return NULL;
939 s2++;
941 *s1++ = '\0';
942 s2++;
944 s2 = skip_spaces (s2);
945 if (found_quote)
947 if (*s2 != '\'')
948 return NULL;
949 s2++;
950 s2 = skip_spaces (s2);
953 if (type != NULL)
954 *type = ntype;
955 if (theclass != NULL)
956 *theclass = nclass;
957 if (category != NULL)
958 *category = ncategory;
959 if (selector != NULL)
960 *selector = nselector;
962 return s2;
965 static void
966 find_methods (char type, const char *theclass, const char *category,
967 const char *selector,
968 std::vector<const char *> *symbol_names)
970 const char *symname = NULL;
972 char ntype = '\0';
973 char *nclass = NULL;
974 char *ncategory = NULL;
975 char *nselector = NULL;
977 static char *tmp = NULL;
978 static unsigned int tmplen = 0;
980 gdb_assert (symbol_names != NULL);
982 for (objfile *objfile : current_program_space->objfiles ())
984 unsigned int *objc_csym;
986 /* The objfile_csym variable counts the number of ObjC methods
987 that this objfile defines. We save that count as a private
988 objfile data. If we have already determined that this objfile
989 provides no ObjC methods, we can skip it entirely. */
991 unsigned int objfile_csym = 0;
993 objc_csym = objc_objfile_data.get (objfile);
994 if (objc_csym != NULL && *objc_csym == 0)
995 /* There are no ObjC symbols in this objfile. Skip it entirely. */
996 continue;
998 for (minimal_symbol *msymbol : objfile->msymbols ())
1000 QUIT;
1002 /* Check the symbol name first as this can be done entirely without
1003 sending any query to the target. */
1004 symname = msymbol->natural_name ();
1005 if (symname == NULL)
1006 continue;
1008 if ((symname[0] != '-' && symname[0] != '+') || (symname[1] != '['))
1009 /* Not a method name. */
1010 continue;
1012 objfile_csym++;
1014 /* Now that thinks are a bit sane, clean up the symname. */
1015 while ((strlen (symname) + 1) >= tmplen)
1017 tmplen = (tmplen == 0) ? 1024 : tmplen * 2;
1018 tmp = (char *) xrealloc (tmp, tmplen);
1020 strcpy (tmp, symname);
1022 if (parse_method (tmp, &ntype, &nclass,
1023 &ncategory, &nselector) == NULL)
1024 continue;
1026 if ((type != '\0') && (ntype != type))
1027 continue;
1029 if ((theclass != NULL)
1030 && ((nclass == NULL) || (strcmp (theclass, nclass) != 0)))
1031 continue;
1033 if ((category != NULL) &&
1034 ((ncategory == NULL) || (strcmp (category, ncategory) != 0)))
1035 continue;
1037 if ((selector != NULL) &&
1038 ((nselector == NULL) || (strcmp (selector, nselector) != 0)))
1039 continue;
1041 symbol_names->push_back (symname);
1044 if (objc_csym == NULL)
1045 objc_csym = objc_objfile_data.emplace (objfile, objfile_csym);
1046 else
1047 /* Count of ObjC methods in this objfile should be constant. */
1048 gdb_assert (*objc_csym == objfile_csym);
1052 /* Uniquify a vector of strings. */
1054 static void
1055 uniquify_strings (std::vector<const char *> *strings)
1057 if (strings->empty ())
1058 return;
1060 std::sort (strings->begin (), strings->end (), compare_cstrings);
1061 strings->erase (std::unique (strings->begin (), strings->end (), streq),
1062 strings->end ());
1066 * Function: find_imps (const char *selector, struct symbol **sym_arr)
1068 * Input: a string representing a selector
1069 * a pointer to an array of symbol pointers
1070 * possibly a pointer to a symbol found by the caller.
1072 * Output: number of methods that implement that selector. Side
1073 * effects: The array of symbol pointers is filled with matching syms.
1075 * By analogy with function "find_methods" (symtab.c), builds a list
1076 * of symbols matching the ambiguous input, so that "decode_line_2"
1077 * (symtab.c) can list them and ask the user to choose one or more.
1078 * In this case the matches are objective c methods
1079 * ("implementations") matching an objective c selector.
1081 * Note that it is possible for a normal (c-style) function to have
1082 * the same name as an objective c selector. To prevent the selector
1083 * from eclipsing the function, we allow the caller (decode_line_1) to
1084 * search for such a function first, and if it finds one, pass it in
1085 * to us. We will then integrate it into the list. We also search
1086 * for one here, among the minsyms.
1088 * NOTE: if NUM_DEBUGGABLE is non-zero, the sym_arr will be divided
1089 * into two parts: debuggable (struct symbol) syms, and
1090 * non_debuggable (struct minimal_symbol) syms. The debuggable
1091 * ones will come first, before NUM_DEBUGGABLE (which will thus
1092 * be the index of the first non-debuggable one).
1095 const char *
1096 find_imps (const char *method, std::vector<const char *> *symbol_names)
1098 char type = '\0';
1099 char *theclass = NULL;
1100 char *category = NULL;
1101 char *selector = NULL;
1103 char *buf = NULL;
1104 char *tmp = NULL;
1106 int selector_case = 0;
1108 gdb_assert (symbol_names != NULL);
1110 buf = (char *) alloca (strlen (method) + 1);
1111 strcpy (buf, method);
1112 tmp = parse_method (buf, &type, &theclass, &category, &selector);
1114 if (tmp == NULL)
1116 strcpy (buf, method);
1117 tmp = parse_selector (buf, &selector);
1119 if (tmp == NULL)
1120 return NULL;
1122 selector_case = 1;
1125 find_methods (type, theclass, category, selector, symbol_names);
1127 /* If we hit the "selector" case, and we found some methods, then
1128 add the selector itself as a symbol, if it exists. */
1129 if (selector_case && !symbol_names->empty ())
1131 struct symbol *sym = lookup_symbol (selector, NULL, SEARCH_VFT,
1132 0).symbol;
1134 if (sym != NULL)
1135 symbol_names->push_back (sym->natural_name ());
1136 else
1138 struct bound_minimal_symbol msym
1139 = lookup_minimal_symbol (selector, 0, 0);
1141 if (msym.minsym != NULL)
1142 symbol_names->push_back (msym.minsym->natural_name ());
1146 uniquify_strings (symbol_names);
1148 return method + (tmp - buf);
1151 static void
1152 print_object_command (const char *args, int from_tty)
1154 struct value *object, *function, *description;
1155 CORE_ADDR string_addr, object_addr;
1156 int i = 0;
1157 gdb_byte c = 0;
1159 if (!args || !*args)
1160 error (
1161 "The 'print-object' command requires an argument (an Objective-C object)");
1164 expression_up expr = parse_expression (args);
1166 object = expr->evaluate (builtin_type (expr->gdbarch)->builtin_data_ptr);
1169 /* Validate the address for sanity. */
1170 object_addr = value_as_long (object);
1171 read_memory (object_addr, &c, 1);
1173 function = find_function_in_inferior ("_NSPrintForDebugger", NULL);
1174 if (function == NULL)
1175 error (_("Unable to locate _NSPrintForDebugger in child process"));
1177 description = call_function_by_hand (function, NULL, object);
1179 string_addr = value_as_long (description);
1180 if (string_addr == 0)
1181 error (_("object returns null description"));
1183 read_memory (string_addr + i++, &c, 1);
1184 if (c != 0)
1186 { /* Read and print characters up to EOS. */
1187 QUIT;
1188 gdb_printf ("%c", c);
1189 read_memory (string_addr + i++, &c, 1);
1190 } while (c != 0);
1191 else
1192 gdb_printf(_("<object returns empty description>"));
1193 gdb_printf ("\n");
1196 /* The data structure 'methcalls' is used to detect method calls (thru
1197 * ObjC runtime lib functions objc_msgSend, objc_msgSendSuper, etc.),
1198 * and ultimately find the method being called.
1201 struct objc_methcall {
1202 const char *name;
1203 /* Return instance method to be called. */
1204 int (*stop_at) (CORE_ADDR, CORE_ADDR *);
1205 /* Start of pc range corresponding to method invocation. */
1206 CORE_ADDR begin;
1207 /* End of pc range corresponding to method invocation. */
1208 CORE_ADDR end;
1211 static int resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc);
1212 static int resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1213 static int resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc);
1214 static int resolve_msgsend_super_stret (CORE_ADDR pc, CORE_ADDR *new_pc);
1216 static struct objc_methcall methcalls[] = {
1217 { "_objc_msgSend", resolve_msgsend, 0, 0},
1218 { "_objc_msgSend_stret", resolve_msgsend_stret, 0, 0},
1219 { "_objc_msgSendSuper", resolve_msgsend_super, 0, 0},
1220 { "_objc_msgSendSuper_stret", resolve_msgsend_super_stret, 0, 0},
1221 { "_objc_getClass", NULL, 0, 0},
1222 { "_objc_getMetaClass", NULL, 0, 0}
1225 #define nmethcalls (sizeof (methcalls) / sizeof (methcalls[0]))
1227 /* The following function, "find_objc_msgsend", fills in the data
1228 * structure "objc_msgs" by finding the addresses of each of the
1229 * (currently four) functions that it holds (of which objc_msgSend is
1230 * the first). This must be called each time symbols are loaded, in
1231 * case the functions have moved for some reason.
1234 static void
1235 find_objc_msgsend (void)
1237 unsigned int i;
1239 for (i = 0; i < nmethcalls; i++)
1241 struct bound_minimal_symbol func;
1243 /* Try both with and without underscore. */
1244 func = lookup_bound_minimal_symbol (methcalls[i].name);
1245 if ((func.minsym == NULL) && (methcalls[i].name[0] == '_'))
1247 func = lookup_bound_minimal_symbol (methcalls[i].name + 1);
1249 if (func.minsym == NULL)
1251 methcalls[i].begin = 0;
1252 methcalls[i].end = 0;
1253 continue;
1256 methcalls[i].begin = func.value_address ();
1257 methcalls[i].end = minimal_symbol_upper_bound (func);
1261 /* find_objc_msgcall (replaces pc_off_limits)
1263 * ALL that this function now does is to determine whether the input
1264 * address ("pc") is the address of one of the Objective-C message
1265 * dispatch functions (mainly objc_msgSend or objc_msgSendSuper), and
1266 * if so, it returns the address of the method that will be called.
1268 * The old function "pc_off_limits" used to do a lot of other things
1269 * in addition, such as detecting shared library jump stubs and
1270 * returning the address of the shlib function that would be called.
1271 * That functionality has been moved into the gdbarch_skip_trampoline_code and
1272 * IN_SOLIB_TRAMPOLINE macros, which are resolved in the target-
1273 * dependent modules.
1276 static int
1277 find_objc_msgcall_submethod (int (*f) (CORE_ADDR, CORE_ADDR *),
1278 CORE_ADDR pc,
1279 CORE_ADDR *new_pc)
1283 if (f (pc, new_pc) == 0)
1284 return 1;
1286 catch (const gdb_exception_error &ex)
1288 exception_fprintf (gdb_stderr, ex,
1289 "Unable to determine target of "
1290 "Objective-C method call (ignoring):\n");
1293 return 0;
1296 int
1297 find_objc_msgcall (CORE_ADDR pc, CORE_ADDR *new_pc)
1299 unsigned int i;
1301 find_objc_msgsend ();
1302 if (new_pc != NULL)
1304 *new_pc = 0;
1307 for (i = 0; i < nmethcalls; i++)
1308 if ((pc >= methcalls[i].begin) && (pc < methcalls[i].end))
1310 if (methcalls[i].stop_at != NULL)
1311 return find_objc_msgcall_submethod (methcalls[i].stop_at,
1312 pc, new_pc);
1313 else
1314 return 0;
1317 return 0;
1320 void _initialize_objc_language ();
1321 void
1322 _initialize_objc_language ()
1324 add_info ("selectors", info_selectors_command,
1325 _("All Objective-C selectors, or those matching REGEXP."));
1326 add_info ("classes", info_classes_command,
1327 _("All Objective-C classes, or those matching REGEXP."));
1328 cmd_list_element *print_object_cmd
1329 = add_com ("print-object", class_vars, print_object_command,
1330 _("Ask an Objective-C object to print itself."));
1331 add_com_alias ("po", print_object_cmd, class_vars, 1);
1334 static void
1335 read_objc_method (struct gdbarch *gdbarch, CORE_ADDR addr,
1336 struct objc_method *method)
1338 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1340 method->name = read_memory_unsigned_integer (addr + 0, 4, byte_order);
1341 method->types = read_memory_unsigned_integer (addr + 4, 4, byte_order);
1342 method->imp = read_memory_unsigned_integer (addr + 8, 4, byte_order);
1345 static unsigned long
1346 read_objc_methlist_nmethods (struct gdbarch *gdbarch, CORE_ADDR addr)
1348 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1350 return read_memory_unsigned_integer (addr + 4, 4, byte_order);
1353 static void
1354 read_objc_methlist_method (struct gdbarch *gdbarch, CORE_ADDR addr,
1355 unsigned long num, struct objc_method *method)
1357 gdb_assert (num < read_objc_methlist_nmethods (gdbarch, addr));
1358 read_objc_method (gdbarch, addr + 8 + (12 * num), method);
1361 static void
1362 read_objc_object (struct gdbarch *gdbarch, CORE_ADDR addr,
1363 struct objc_object *object)
1365 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1367 object->isa = read_memory_unsigned_integer (addr, 4, byte_order);
1370 static void
1371 read_objc_super (struct gdbarch *gdbarch, CORE_ADDR addr,
1372 struct objc_super *super)
1374 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1376 super->receiver = read_memory_unsigned_integer (addr, 4, byte_order);
1377 super->theclass = read_memory_unsigned_integer (addr + 4, 4, byte_order);
1380 static void
1381 read_objc_class (struct gdbarch *gdbarch, CORE_ADDR addr,
1382 struct objc_class *theclass)
1384 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1386 theclass->isa = read_memory_unsigned_integer (addr, 4, byte_order);
1387 theclass->super_class = read_memory_unsigned_integer (addr + 4, 4, byte_order);
1388 theclass->name = read_memory_unsigned_integer (addr + 8, 4, byte_order);
1389 theclass->version = read_memory_unsigned_integer (addr + 12, 4, byte_order);
1390 theclass->info = read_memory_unsigned_integer (addr + 16, 4, byte_order);
1391 theclass->instance_size = read_memory_unsigned_integer (addr + 18, 4,
1392 byte_order);
1393 theclass->ivars = read_memory_unsigned_integer (addr + 24, 4, byte_order);
1394 theclass->methods = read_memory_unsigned_integer (addr + 28, 4, byte_order);
1395 theclass->cache = read_memory_unsigned_integer (addr + 32, 4, byte_order);
1396 theclass->protocols = read_memory_unsigned_integer (addr + 36, 4, byte_order);
1399 static CORE_ADDR
1400 find_implementation_from_class (struct gdbarch *gdbarch,
1401 CORE_ADDR theclass, CORE_ADDR sel)
1403 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1404 CORE_ADDR subclass = theclass;
1406 while (subclass != 0)
1409 struct objc_class class_str;
1410 unsigned mlistnum = 0;
1412 read_objc_class (gdbarch, subclass, &class_str);
1414 for (;;)
1416 CORE_ADDR mlist;
1417 unsigned long nmethods;
1418 unsigned long i;
1420 mlist = read_memory_unsigned_integer (class_str.methods +
1421 (4 * mlistnum),
1422 4, byte_order);
1423 if (mlist == 0)
1424 break;
1426 nmethods = read_objc_methlist_nmethods (gdbarch, mlist);
1428 for (i = 0; i < nmethods; i++)
1430 struct objc_method meth_str;
1432 read_objc_methlist_method (gdbarch, mlist, i, &meth_str);
1434 if (meth_str.name == sel)
1435 /* FIXME: hppa arch was doing a pointer dereference
1436 here. There needs to be a better way to do that. */
1437 return meth_str.imp;
1439 mlistnum++;
1441 subclass = class_str.super_class;
1444 return 0;
1447 static CORE_ADDR
1448 find_implementation (struct gdbarch *gdbarch,
1449 CORE_ADDR object, CORE_ADDR sel)
1451 struct objc_object ostr;
1453 if (object == 0)
1454 return 0;
1455 read_objc_object (gdbarch, object, &ostr);
1456 if (ostr.isa == 0)
1457 return 0;
1459 return find_implementation_from_class (gdbarch, ostr.isa, sel);
1462 static int
1463 resolve_msgsend (CORE_ADDR pc, CORE_ADDR *new_pc)
1465 frame_info_ptr frame = get_current_frame ();
1466 struct gdbarch *gdbarch = get_frame_arch (frame);
1467 struct type *ptr_type = builtin_type (gdbarch)->builtin_func_ptr;
1469 CORE_ADDR object;
1470 CORE_ADDR sel;
1471 CORE_ADDR res;
1473 object = gdbarch_fetch_pointer_argument (gdbarch, frame, 0, ptr_type);
1474 sel = gdbarch_fetch_pointer_argument (gdbarch, frame, 1, ptr_type);
1476 res = find_implementation (gdbarch, object, sel);
1477 if (new_pc != 0)
1478 *new_pc = res;
1479 if (res == 0)
1480 return 1;
1481 return 0;
1484 static int
1485 resolve_msgsend_stret (CORE_ADDR pc, CORE_ADDR *new_pc)
1487 frame_info_ptr frame = get_current_frame ();
1488 struct gdbarch *gdbarch = get_frame_arch (frame);
1489 struct type *ptr_type = builtin_type (gdbarch)->builtin_func_ptr;
1491 CORE_ADDR object;
1492 CORE_ADDR sel;
1493 CORE_ADDR res;
1495 object = gdbarch_fetch_pointer_argument (gdbarch, frame, 1, ptr_type);
1496 sel = gdbarch_fetch_pointer_argument (gdbarch, frame, 2, ptr_type);
1498 res = find_implementation (gdbarch, object, sel);
1499 if (new_pc != 0)
1500 *new_pc = res;
1501 if (res == 0)
1502 return 1;
1503 return 0;
1506 static int
1507 resolve_msgsend_super (CORE_ADDR pc, CORE_ADDR *new_pc)
1509 frame_info_ptr frame = get_current_frame ();
1510 struct gdbarch *gdbarch = get_frame_arch (frame);
1511 struct type *ptr_type = builtin_type (gdbarch)->builtin_func_ptr;
1513 struct objc_super sstr;
1515 CORE_ADDR super;
1516 CORE_ADDR sel;
1517 CORE_ADDR res;
1519 super = gdbarch_fetch_pointer_argument (gdbarch, frame, 0, ptr_type);
1520 sel = gdbarch_fetch_pointer_argument (gdbarch, frame, 1, ptr_type);
1522 read_objc_super (gdbarch, super, &sstr);
1523 if (sstr.theclass == 0)
1524 return 0;
1526 res = find_implementation_from_class (gdbarch, sstr.theclass, sel);
1527 if (new_pc != 0)
1528 *new_pc = res;
1529 if (res == 0)
1530 return 1;
1531 return 0;
1534 static int
1535 resolve_msgsend_super_stret (CORE_ADDR pc, CORE_ADDR *new_pc)
1537 frame_info_ptr frame = get_current_frame ();
1538 struct gdbarch *gdbarch = get_frame_arch (frame);
1539 struct type *ptr_type = builtin_type (gdbarch)->builtin_func_ptr;
1541 struct objc_super sstr;
1543 CORE_ADDR super;
1544 CORE_ADDR sel;
1545 CORE_ADDR res;
1547 super = gdbarch_fetch_pointer_argument (gdbarch, frame, 1, ptr_type);
1548 sel = gdbarch_fetch_pointer_argument (gdbarch, frame, 2, ptr_type);
1550 read_objc_super (gdbarch, super, &sstr);
1551 if (sstr.theclass == 0)
1552 return 0;
1554 res = find_implementation_from_class (gdbarch, sstr.theclass, sel);
1555 if (new_pc != 0)
1556 *new_pc = res;
1557 if (res == 0)
1558 return 1;
1559 return 0;