1 /* GNU Objective C Runtime class related functions
2 Copyright (C) 1993-2017 Free Software Foundation, Inc.
3 Contributed by Kresten Krab Thorup and Dennis Glatting.
5 Lock-free class table code designed and written from scratch by
8 This file is part of GCC.
10 GCC is free software; you can redistribute it and/or modify it under the
11 terms of the GNU General Public License as published by the Free Software
12 Foundation; either version 3, or (at your option) any later version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
19 Under Section 7 of GPL version 3, you are granted additional
20 permissions described in the GCC Runtime Library Exception, version
21 3.1, as published by the Free Software Foundation.
23 You should have received a copy of the GNU General Public License and
24 a copy of the GCC Runtime Library Exception along with this program;
25 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
26 <http://www.gnu.org/licenses/>. */
28 /* The code in this file critically affects class method invocation
29 speed. This long preamble comment explains why, and the issues
32 One of the traditional weaknesses of the GNU Objective-C runtime is
33 that class method invocations are slow. The reason is that when you
36 array = [NSArray new];
38 this gets basically compiled into the equivalent of
40 array = [(objc_get_class ("NSArray")) new];
42 objc_get_class returns the class pointer corresponding to the string
43 `NSArray'; and because of the lookup, the operation is more
44 complicated and slow than a simple instance method invocation.
46 Most high performance Objective-C code (using the GNU Objc runtime)
47 I had the opportunity to read (or write) work around this problem by
48 caching the class pointer:
50 Class arrayClass = [NSArray class];
54 array = [arrayClass new];
55 array = [arrayClass new];
56 array = [arrayClass new];
58 In this case, you always perform a class lookup (the first one), but
59 then all the [arrayClass new] methods run exactly as fast as an
60 instance method invocation. It helps if you have many class method
61 invocations to the same class.
63 The long-term solution to this problem would be to modify the
64 compiler to output tables of class pointers corresponding to all the
65 class method invocations, and to add code to the runtime to update
66 these tables - that should in the end allow class method invocations
67 to perform precisely as fast as instance method invocations, because
68 no class lookup would be involved. I think the Apple Objective-C
69 runtime uses this technique. Doing this involves synchronized
70 modifications in the runtime and in the compiler.
72 As a first medicine to the problem, I [NP] have redesigned and
73 rewritten the way the runtime is performing class lookup. This
74 doesn't give as much speed as the other (definitive) approach, but
75 at least a class method invocation now takes approximately 4.5 times
76 an instance method invocation on my machine (it would take approx 12
77 times before the rewriting), which is a lot better.
79 One of the main reason the new class lookup is so faster is because
80 I implemented it in a way that can safely run multithreaded without
81 using locks - a so-called `lock-free' data structure. The atomic
82 operation is pointer assignment. The reason why in this problem
83 lock-free data structures work so well is that you never remove
84 classes from the table - and the difficult thing with lock-free data
85 structures is freeing data when is removed from the structures. */
87 #include "objc-private/common.h"
88 #include "objc-private/error.h"
89 #include "objc/runtime.h"
91 #include "objc-private/module-abi-8.h" /* For CLS_ISCLASS and similar. */
92 #include "objc-private/runtime.h" /* the kitchen sink */
93 #include "objc-private/sarray.h" /* For sarray_put_at_safe. */
94 #include "objc-private/selector.h" /* For sarray_put_at_safe. */
95 #include <string.h> /* For memset */
97 /* We use a table which maps a class name to the corresponding class
98 pointer. The first part of this file defines this table, and
99 functions to do basic operations on the table. The second part of
100 the file implements some higher level Objective-C functionality for
101 classes by using the functions provided in the first part to manage
105 ** Class Table Internals
108 /* A node holding a class */
109 typedef struct class_node
111 struct class_node
*next
; /* Pointer to next entry on the list.
112 NULL indicates end of list. */
114 const char *name
; /* The class name string */
115 int length
; /* The class name string length */
116 Class pointer
; /* The Class pointer */
120 /* A table containing classes is a class_node_ptr (pointing to the
121 first entry in the table - if it is NULL, then the table is
124 /* We have 1024 tables. Each table contains all class names which
125 have the same hash (which is a number between 0 and 1023). To look
126 up a class_name, we compute its hash, and get the corresponding
127 table. Once we have the table, we simply compare strings directly
128 till we find the one which we want (using the length first). The
129 number of tables is quite big on purpose (a normal big application
130 has less than 1000 classes), so that you shouldn't normally get any
131 collisions, and get away with a single comparison (which we can't
132 avoid since we need to know that you have got the right thing). */
133 #define CLASS_TABLE_SIZE 1024
134 #define CLASS_TABLE_MASK 1023
136 static class_node_ptr class_table_array
[CLASS_TABLE_SIZE
];
138 /* The table writing mutex - we lock on writing to avoid conflicts
139 between different writers, but we read without locks. That is
140 possible because we assume pointer assignment to be an atomic
141 operation. TODO: This is only true under certain circumstances,
142 which should be clarified. */
143 static objc_mutex_t __class_table_lock
= NULL
;
145 /* CLASS_TABLE_HASH is how we compute the hash of a class name. It is
146 a macro - *not* a function - arguments *are* modified directly.
148 INDEX should be a variable holding an int;
149 HASH should be a variable holding an int;
150 CLASS_NAME should be a variable holding a (char *) to the class_name.
152 After the macro is executed, INDEX contains the length of the
153 string, and HASH the computed hash of the string; CLASS_NAME is
156 #define CLASS_TABLE_HASH(INDEX, HASH, CLASS_NAME) \
158 for (INDEX = 0; CLASS_NAME[INDEX] != '\0'; INDEX++) \
160 HASH = (HASH << 4) ^ (HASH >> 28) ^ CLASS_NAME[INDEX]; \
163 HASH = (HASH ^ (HASH >> 10) ^ (HASH >> 20)) & CLASS_TABLE_MASK;
165 /* Setup the table. */
167 class_table_setup (void)
169 /* Start - nothing in the table. */
170 memset (class_table_array
, 0, sizeof (class_node_ptr
) * CLASS_TABLE_SIZE
);
172 /* The table writing mutex. */
173 __class_table_lock
= objc_mutex_allocate ();
177 /* Insert a class in the table (used when a new class is
180 class_table_insert (const char *class_name
, Class class_pointer
)
183 class_node_ptr new_node
;
185 /* Find out the class name's hash and length. */
186 CLASS_TABLE_HASH (length
, hash
, class_name
);
188 /* Prepare the new node holding the class. */
189 new_node
= objc_malloc (sizeof (struct class_node
));
190 new_node
->name
= class_name
;
191 new_node
->length
= length
;
192 new_node
->pointer
= class_pointer
;
194 /* Lock the table for modifications. */
195 objc_mutex_lock (__class_table_lock
);
197 /* Insert the new node in the table at the beginning of the table at
198 class_table_array[hash]. */
199 new_node
->next
= class_table_array
[hash
];
200 class_table_array
[hash
] = new_node
;
202 objc_mutex_unlock (__class_table_lock
);
205 /* Get a class from the table. This does not need mutex protection.
206 Currently, this function is called each time you call a static
207 method, this is why it must be very fast. */
209 class_table_get_safe (const char *class_name
)
214 /* Compute length and hash. */
215 CLASS_TABLE_HASH (length
, hash
, class_name
);
217 node
= class_table_array
[hash
];
223 if (node
->length
== length
)
225 /* Compare the class names. */
228 for (i
= 0; i
< length
; i
++)
230 if ((node
->name
)[i
] != class_name
[i
])
236 /* They are equal! */
237 return node
->pointer
;
241 while ((node
= node
->next
) != NULL
);
247 /* Enumerate over the class table. */
248 struct class_table_enumerator
256 class_table_next (struct class_table_enumerator
**e
)
258 struct class_table_enumerator
*enumerator
= *e
;
261 if (enumerator
== NULL
)
263 *e
= objc_malloc (sizeof (struct class_table_enumerator
));
265 enumerator
->hash
= 0;
266 enumerator
->node
= NULL
;
268 next
= class_table_array
[enumerator
->hash
];
271 next
= enumerator
->node
->next
;
275 enumerator
->node
= next
;
276 return enumerator
->node
->pointer
;
282 while (enumerator
->hash
< CLASS_TABLE_SIZE
)
284 next
= class_table_array
[enumerator
->hash
];
287 enumerator
->node
= next
;
288 return enumerator
->node
->pointer
;
293 /* Ok - table finished - done. */
294 objc_free (enumerator
);
299 #if 0 /* DEBUGGING FUNCTIONS */
300 /* Debugging function - print the class table. */
302 class_table_print (void)
306 for (i
= 0; i
< CLASS_TABLE_SIZE
; i
++)
311 node
= class_table_array
[i
];
315 printf ("\t%s\n", node
->name
);
321 /* Debugging function - print an histogram of number of classes in
322 function of hash key values. Useful to evaluate the hash function
325 class_table_print_histogram (void)
330 for (i
= 0; i
< CLASS_TABLE_SIZE
; i
++)
334 node
= class_table_array
[i
];
341 if (((i
+ 1) % 50) == 0)
343 printf ("%4d:", i
+ 1);
344 for (j
= 0; j
< counter
; j
++)
351 printf ("%4d:", i
+ 1);
352 for (j
= 0; j
< counter
; j
++)
357 #endif /* DEBUGGING FUNCTIONS */
360 ** Objective-C runtime functions
363 /* From now on, the only access to the class table data structure
364 should be via the class_table_* functions. */
366 /* This is a hook which is called by objc_get_class and
367 objc_lookup_class if the runtime is not able to find the class.
368 This may e.g. try to load in the class using dynamic loading.
370 This hook was a public, global variable in the Traditional GNU
371 Objective-C Runtime API (objc/objc-api.h). The modern GNU
372 Objective-C Runtime API (objc/runtime.h) provides the
373 objc_setGetUnknownClassHandler() function instead.
375 Class (*_objc_lookup_class
) (const char *name
) = 0; /* !T:SAFE */
377 /* The handler currently in use. PS: if both
378 __obj_get_unknown_class_handler and _objc_lookup_class are defined,
379 __objc_get_unknown_class_handler is called first. */
380 static objc_get_unknown_class_handler
381 __objc_get_unknown_class_handler
= NULL
;
383 objc_get_unknown_class_handler
384 objc_setGetUnknownClassHandler (objc_get_unknown_class_handler
387 objc_get_unknown_class_handler old_handler
388 = __objc_get_unknown_class_handler
;
389 __objc_get_unknown_class_handler
= new_handler
;
394 /* True when class links has been resolved. */
395 BOOL __objc_class_links_resolved
= NO
; /* !T:UNUSED */
399 __objc_init_class_tables (void)
401 /* Allocate the class hash table. */
403 if (__class_table_lock
)
406 objc_mutex_lock (__objc_runtime_mutex
);
408 class_table_setup ();
410 objc_mutex_unlock (__objc_runtime_mutex
);
413 /* This function adds a class to the class hash table, and assigns the
414 class a number, unless it's already known. Return 'YES' if the
415 class was added. Return 'NO' if the class was already known. */
417 __objc_add_class_to_hash (Class
class)
419 Class existing_class
;
421 objc_mutex_lock (__objc_runtime_mutex
);
423 /* Make sure the table is there. */
424 assert (__class_table_lock
);
426 /* Make sure it's not a meta class. */
427 assert (CLS_ISCLASS (class));
429 /* Check to see if the class is already in the hash table. */
430 existing_class
= class_table_get_safe (class->name
);
434 objc_mutex_unlock (__objc_runtime_mutex
);
439 /* The class isn't in the hash table. Add the class and assign
441 static unsigned int class_number
= 1;
443 CLS_SETNUMBER (class, class_number
);
444 CLS_SETNUMBER (class->class_pointer
, class_number
);
447 class_table_insert (class->name
, class);
449 objc_mutex_unlock (__objc_runtime_mutex
);
455 objc_getClass (const char *name
)
462 class = class_table_get_safe (name
);
467 if (__objc_get_unknown_class_handler
)
468 return (*__objc_get_unknown_class_handler
) (name
);
470 if (_objc_lookup_class
)
471 return (*_objc_lookup_class
) (name
);
477 objc_lookUpClass (const char *name
)
482 return class_table_get_safe (name
);
486 objc_getMetaClass (const char *name
)
488 Class
class = objc_getClass (name
);
491 return class->class_pointer
;
497 objc_getRequiredClass (const char *name
)
499 Class
class = objc_getClass (name
);
504 _objc_abort ("objc_getRequiredClass ('%s') failed: class not found\n", name
);
508 objc_getClassList (Class
*returnValue
, int maxNumberOfClassesToReturn
)
510 /* Iterate over all entries in the table. */
513 for (hash
= 0; hash
< CLASS_TABLE_SIZE
; hash
++)
515 class_node_ptr node
= class_table_array
[hash
];
521 if (count
< maxNumberOfClassesToReturn
)
522 returnValue
[count
] = node
->pointer
;
535 objc_allocateClassPair (Class super_class
, const char *class_name
, size_t extraBytes
)
538 Class new_meta_class
;
540 if (class_name
== NULL
)
543 if (objc_getClass (class_name
))
548 /* If you want to build a hierarchy of classes, you need to
549 build and register them one at a time. The risk is that you
550 are able to cause confusion by registering a subclass before
551 the superclass or similar. */
552 if (CLS_IS_IN_CONSTRUCTION (super_class
))
556 /* Technically, we should create the metaclass first, then use
557 class_createInstance() to create the class. That complication
558 would be relevant if we had class variables, but we don't, so we
559 just ignore it and create everything directly and assume all
560 classes have the same size. */
561 new_class
= objc_calloc (1, sizeof (struct objc_class
) + extraBytes
);
562 new_meta_class
= objc_calloc (1, sizeof (struct objc_class
) + extraBytes
);
564 /* We create an unresolved class, similar to one generated by the
565 compiler. It will be resolved later when we register it.
567 Note how the metaclass details are not that important; when the
568 class is resolved, the ones that matter will be fixed up. */
569 new_class
->class_pointer
= new_meta_class
;
570 new_meta_class
->class_pointer
= 0;
574 /* Force the name of the superclass in place of the link to the
575 actual superclass, which will be put there when the class is
577 const char *super_class_name
= class_getName (super_class
);
578 new_class
->super_class
= (void *)super_class_name
;
579 new_meta_class
->super_class
= (void *)super_class_name
;
583 new_class
->super_class
= (void *)0;
584 new_meta_class
->super_class
= (void *)0;
587 new_class
->name
= objc_malloc (strlen (class_name
) + 1);
588 strcpy ((char*)new_class
->name
, class_name
);
589 new_meta_class
->name
= new_class
->name
;
591 new_class
->version
= 0;
592 new_meta_class
->version
= 0;
594 new_class
->info
= _CLS_CLASS
| _CLS_IN_CONSTRUCTION
;
595 new_meta_class
->info
= _CLS_META
| _CLS_IN_CONSTRUCTION
;
598 new_class
->instance_size
= super_class
->instance_size
;
600 new_class
->instance_size
= 0;
601 new_meta_class
->instance_size
= sizeof (struct objc_class
);
607 objc_registerClassPair (Class class_
)
612 if ((! CLS_ISCLASS (class_
)) || (! CLS_IS_IN_CONSTRUCTION (class_
)))
615 if ((! CLS_ISMETA (class_
->class_pointer
)) || (! CLS_IS_IN_CONSTRUCTION (class_
->class_pointer
)))
618 objc_mutex_lock (__objc_runtime_mutex
);
620 if (objc_getClass (class_
->name
))
622 objc_mutex_unlock (__objc_runtime_mutex
);
626 CLS_SET_NOT_IN_CONSTRUCTION (class_
);
627 CLS_SET_NOT_IN_CONSTRUCTION (class_
->class_pointer
);
629 __objc_init_class (class_
);
631 /* Resolve class links immediately. No point in waiting. */
632 __objc_resolve_class_links ();
634 objc_mutex_unlock (__objc_runtime_mutex
);
638 objc_disposeClassPair (Class class_
)
643 if ((! CLS_ISCLASS (class_
)) || (! CLS_IS_IN_CONSTRUCTION (class_
)))
646 if ((! CLS_ISMETA (class_
->class_pointer
)) || (! CLS_IS_IN_CONSTRUCTION (class_
->class_pointer
)))
649 /* Undo any class_addIvar(). */
653 for (i
= 0; i
< class_
->ivars
->ivar_count
; i
++)
655 struct objc_ivar
*ivar
= &(class_
->ivars
->ivar_list
[i
]);
657 objc_free ((char *)ivar
->ivar_name
);
658 objc_free ((char *)ivar
->ivar_type
);
661 objc_free (class_
->ivars
);
664 /* Undo any class_addMethod(). */
667 struct objc_method_list
*list
= class_
->methods
;
671 struct objc_method_list
*next
= list
->method_next
;
673 for (i
= 0; i
< list
->method_count
; i
++)
675 struct objc_method
*method
= &(list
->method_list
[i
]);
677 objc_free ((char *)method
->method_name
);
678 objc_free ((char *)method
->method_types
);
686 /* Undo any class_addProtocol(). */
687 if (class_
->protocols
)
689 struct objc_protocol_list
*list
= class_
->protocols
;
692 struct objc_protocol_list
*next
= list
->next
;
699 /* Undo any class_addMethod() on the meta-class. */
700 if (class_
->class_pointer
->methods
)
702 struct objc_method_list
*list
= class_
->class_pointer
->methods
;
706 struct objc_method_list
*next
= list
->method_next
;
708 for (i
= 0; i
< list
->method_count
; i
++)
710 struct objc_method
*method
= &(list
->method_list
[i
]);
712 objc_free ((char *)method
->method_name
);
713 objc_free ((char *)method
->method_types
);
721 /* Undo objc_allocateClassPair(). */
722 objc_free ((char *)(class_
->name
));
723 objc_free (class_
->class_pointer
);
727 /* Traditional GNU Objective-C Runtime API. Important: this method is
728 called automatically by the compiler while messaging (if using the
729 traditional ABI), so it is worth keeping it fast; don't make it
730 just a wrapper around objc_getClass(). */
731 /* Note that this is roughly equivalent to objc_getRequiredClass(). */
732 /* Get the class object for the class named NAME. If NAME does not
733 identify a known class, the hook _objc_lookup_class is called. If
734 this fails, an error message is issued and the system aborts. */
736 objc_get_class (const char *name
)
740 class = class_table_get_safe (name
);
745 if (__objc_get_unknown_class_handler
)
746 class = (*__objc_get_unknown_class_handler
) (name
);
748 if ((!class) && _objc_lookup_class
)
749 class = (*_objc_lookup_class
) (name
);
754 _objc_abort ("objc runtime: cannot find class %s\n", name
);
759 /* This is used by the compiler too. */
761 objc_get_meta_class (const char *name
)
763 return objc_get_class (name
)->class_pointer
;
766 /* This is not used by GCC, but the clang compiler seems to use it
767 when targeting the GNU runtime. That's wrong, but we have it to
770 objc_lookup_class (const char *name
)
772 return objc_getClass (name
);
775 /* This is used when the implementation of a method changes. It goes
776 through all classes, looking for the ones that have these methods
777 (either method_a or method_b; method_b can be NULL), and reloads
778 the implementation for these. You should call this with the
779 runtime mutex already locked. */
781 __objc_update_classes_with_methods (struct objc_method
*method_a
, struct objc_method
*method_b
)
785 /* Iterate over all classes. */
786 for (hash
= 0; hash
< CLASS_TABLE_SIZE
; hash
++)
788 class_node_ptr node
= class_table_array
[hash
];
792 /* We execute this loop twice: the first time, we iterate
793 over all methods in the class (instance methods), while
794 the second time we iterate over all methods in the meta
795 class (class methods). */
801 struct objc_method_list
* method_list
;
805 /* The first time, we work on the class. */
806 class = node
->pointer
;
810 /* The second time, we work on the meta class. */
811 class = class->class_pointer
;
815 method_list
= class->methods
;
821 for (i
= 0; i
< method_list
->method_count
; ++i
)
823 struct objc_method
*method
= &method_list
->method_list
[i
];
825 /* If the method is one of the ones we are
826 looking for, update the implementation. */
827 if (method
== method_a
)
828 sarray_at_put_safe (class->dtable
,
829 (sidx
) method_a
->method_name
->sel_id
,
830 method_a
->method_imp
);
832 if (method
== method_b
)
834 if (method_b
!= NULL
)
835 sarray_at_put_safe (class->dtable
,
836 (sidx
) method_b
->method_name
->sel_id
,
837 method_b
->method_imp
);
841 method_list
= method_list
->method_next
;
849 /* Resolve super/subclass links for all classes. The only thing we
850 can be sure of is that the class_pointer for class objects point to
851 the right meta class objects. */
853 __objc_resolve_class_links (void)
855 struct class_table_enumerator
*es
= NULL
;
856 Class object_class
= objc_get_class ("Object");
859 assert (object_class
);
861 objc_mutex_lock (__objc_runtime_mutex
);
863 /* Assign subclass links. */
864 while ((class1
= class_table_next (&es
)))
866 /* Make sure we have what we think we have. */
867 assert (CLS_ISCLASS (class1
));
868 assert (CLS_ISMETA (class1
->class_pointer
));
870 /* The class_pointer of all meta classes point to Object's meta
872 class1
->class_pointer
->class_pointer
= object_class
->class_pointer
;
874 if (! CLS_ISRESOLV (class1
))
876 CLS_SETRESOLV (class1
);
877 CLS_SETRESOLV (class1
->class_pointer
);
879 if (class1
->super_class
)
882 = objc_get_class ((char *) class1
->super_class
);
884 assert (a_super_class
);
886 DEBUG_PRINTF ("making class connections for: %s\n",
889 /* Assign subclass links for superclass. */
890 class1
->sibling_class
= a_super_class
->subclass_list
;
891 a_super_class
->subclass_list
= class1
;
893 /* Assign subclass links for meta class of superclass. */
894 if (a_super_class
->class_pointer
)
896 class1
->class_pointer
->sibling_class
897 = a_super_class
->class_pointer
->subclass_list
;
898 a_super_class
->class_pointer
->subclass_list
899 = class1
->class_pointer
;
902 else /* A root class, make its meta object be a subclass of
905 class1
->class_pointer
->sibling_class
906 = object_class
->subclass_list
;
907 object_class
->subclass_list
= class1
->class_pointer
;
912 /* Assign superclass links. */
914 while ((class1
= class_table_next (&es
)))
917 for (sub_class
= class1
->subclass_list
; sub_class
;
918 sub_class
= sub_class
->sibling_class
)
920 sub_class
->super_class
= class1
;
921 if (CLS_ISCLASS (sub_class
))
922 sub_class
->class_pointer
->super_class
= class1
->class_pointer
;
926 objc_mutex_unlock (__objc_runtime_mutex
);
930 class_getName (Class class_
)
939 class_isMetaClass (Class class_
)
941 /* CLS_ISMETA includes the check for Nil class_. */
942 return CLS_ISMETA (class_
);
945 /* Even inside libobjc it may be worth using class_getSuperclass
946 instead of accessing class_->super_class directly because it
947 resolves the class links if needed. If you access
948 class_->super_class directly, make sure to deal with the situation
949 where the class is not resolved yet! */
951 class_getSuperclass (Class class_
)
956 /* Classes that are in construction are not resolved, and still have
957 the class name (instead of a class pointer) in the
958 class_->super_class field. In that case we need to lookup the
959 superclass name to return the superclass. We can not resolve the
960 class until it is registered. */
961 if (CLS_IS_IN_CONSTRUCTION (class_
))
963 if (CLS_ISMETA (class_
))
964 return object_getClass ((id
)objc_lookUpClass ((const char *)(class_
->super_class
)));
966 return objc_lookUpClass ((const char *)(class_
->super_class
));
969 /* If the class is not resolved yet, super_class would point to a
970 string (the name of the super class) as opposed to the actual
971 super class. In that case, we need to resolve the class links
972 before we can return super_class. */
973 if (! CLS_ISRESOLV (class_
))
974 __objc_resolve_class_links ();
976 return class_
->super_class
;
980 class_getVersion (Class class_
)
985 return (int)(class_
->version
);
989 class_setVersion (Class class_
, int version
)
994 class_
->version
= version
;
998 class_getInstanceSize (Class class_
)
1003 return class_
->instance_size
;