OSDN Git Service

In libobjc/:
[pf3gnuchains/gcc-fork.git] / libobjc / class.c
1 /* GNU Objective C Runtime class related functions
2    Copyright (C) 1993, 1995, 1996, 1997, 2001, 2002, 2009, 2010
3      Free Software Foundation, Inc.
4    Contributed by Kresten Krab Thorup and Dennis Glatting.
5
6    Lock-free class table code designed and written from scratch by
7    Nicola Pero, 2001.
8
9 This file is part of GCC.
10
11 GCC is free software; you can redistribute it and/or modify it under the
12 terms of the GNU General Public License as published by the Free Software
13 Foundation; either version 3, or (at your option) any later version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18 details.
19
20 Under Section 7 of GPL version 3, you are granted additional
21 permissions described in the GCC Runtime Library Exception, version
22 3.1, as published by the Free Software Foundation.
23
24 You should have received a copy of the GNU General Public License and
25 a copy of the GCC Runtime Library Exception along with this program;
26 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
27 <http://www.gnu.org/licenses/>.  */
28
29 /* The code in this file critically affects class method invocation
30   speed.  This long preamble comment explains why, and the issues
31   involved.
32
33   One of the traditional weaknesses of the GNU Objective-C runtime is
34   that class method invocations are slow.  The reason is that when you
35   write
36   
37   array = [NSArray new];
38   
39   this gets basically compiled into the equivalent of 
40   
41   array = [(objc_get_class ("NSArray")) new];
42   
43   objc_get_class returns the class pointer corresponding to the string
44   `NSArray'; and because of the lookup, the operation is more
45   complicated and slow than a simple instance method invocation.
46   
47   Most high performance Objective-C code (using the GNU Objc runtime)
48   I had the opportunity to read (or write) work around this problem by
49   caching the class pointer:
50   
51   Class arrayClass = [NSArray class];
52   
53   ... later on ...
54   
55   array = [arrayClass new];
56   array = [arrayClass new];
57   array = [arrayClass new];
58   
59   In this case, you always perform a class lookup (the first one), but
60   then all the [arrayClass new] methods run exactly as fast as an
61   instance method invocation.  It helps if you have many class method
62   invocations to the same class.
63   
64   The long-term solution to this problem would be to modify the
65   compiler to output tables of class pointers corresponding to all the
66   class method invocations, and to add code to the runtime to update
67   these tables - that should in the end allow class method invocations
68   to perform precisely as fast as instance method invocations, because
69   no class lookup would be involved.  I think the Apple Objective-C
70   runtime uses this technique.  Doing this involves synchronized
71   modifications in the runtime and in the compiler.
72   
73   As a first medicine to the problem, I [NP] have redesigned and
74   rewritten the way the runtime is performing class lookup.  This
75   doesn't give as much speed as the other (definitive) approach, but
76   at least a class method invocation now takes approximately 4.5 times
77   an instance method invocation on my machine (it would take approx 12
78   times before the rewriting), which is a lot better.
79
80   One of the main reason the new class lookup is so faster is because
81   I implemented it in a way that can safely run multithreaded without
82   using locks - a so-called `lock-free' data structure.  The atomic
83   operation is pointer assignment.  The reason why in this problem
84   lock-free data structures work so well is that you never remove
85   classes from the table - and the difficult thing with lock-free data
86   structures is freeing data when is removed from the structures.  */
87
88 #include "objc-private/common.h"
89 #include "objc-private/error.h"
90 #include "objc/runtime.h"
91 #include "objc/thr.h"
92 #include "objc-private/module-abi-8.h"  /* For CLS_ISCLASS and similar.  */
93 #include "objc-private/runtime.h"       /* the kitchen sink */
94 #include "objc-private/sarray.h"        /* For sarray_put_at_safe.  */
95 #include "objc-private/selector.h"      /* For sarray_put_at_safe.  */
96 #include <string.h>                     /* For memset */
97
98 /* We use a table which maps a class name to the corresponding class
99    pointer.  The first part of this file defines this table, and
100    functions to do basic operations on the table.  The second part of
101    the file implements some higher level Objective-C functionality for
102    classes by using the functions provided in the first part to manage
103    the table. */
104
105 /**
106  ** Class Table Internals
107  **/
108
109 /* A node holding a class */
110 typedef struct class_node
111 {
112   struct class_node *next;      /* Pointer to next entry on the list.
113                                    NULL indicates end of list. */
114   
115   const char *name;             /* The class name string */
116   int length;                   /* The class name string length */
117   Class pointer;                /* The Class pointer */
118   
119 } *class_node_ptr;
120
121 /* A table containing classes is a class_node_ptr (pointing to the
122    first entry in the table - if it is NULL, then the table is
123    empty). */
124
125 /* We have 1024 tables.  Each table contains all class names which
126    have the same hash (which is a number between 0 and 1023).  To look
127    up a class_name, we compute its hash, and get the corresponding
128    table.  Once we have the table, we simply compare strings directly
129    till we find the one which we want (using the length first).  The
130    number of tables is quite big on purpose (a normal big application
131    has less than 1000 classes), so that you shouldn't normally get any
132    collisions, and get away with a single comparison (which we can't
133    avoid since we need to know that you have got the right thing).  */
134 #define CLASS_TABLE_SIZE 1024
135 #define CLASS_TABLE_MASK 1023
136
137 static class_node_ptr class_table_array[CLASS_TABLE_SIZE];
138
139 /* The table writing mutex - we lock on writing to avoid conflicts
140    between different writers, but we read without locks.  That is
141    possible because we assume pointer assignment to be an atomic
142    operation.  TODO: This is only true under certain circumstances,
143    which should be clarified.  */
144 static objc_mutex_t __class_table_lock = NULL;
145
146 /* CLASS_TABLE_HASH is how we compute the hash of a class name.  It is
147    a macro - *not* a function - arguments *are* modified directly.
148
149    INDEX should be a variable holding an int;
150    HASH should be a variable holding an int;
151    CLASS_NAME should be a variable holding a (char *) to the class_name.  
152
153    After the macro is executed, INDEX contains the length of the
154    string, and HASH the computed hash of the string; CLASS_NAME is
155    untouched.  */
156
157 #define CLASS_TABLE_HASH(INDEX, HASH, CLASS_NAME)          \
158   HASH = 0;                                                  \
159   for (INDEX = 0; CLASS_NAME[INDEX] != '\0'; INDEX++)        \
160     {                                                        \
161       HASH = (HASH << 4) ^ (HASH >> 28) ^ CLASS_NAME[INDEX]; \
162     }                                                        \
163                                                              \
164   HASH = (HASH ^ (HASH >> 10) ^ (HASH >> 20)) & CLASS_TABLE_MASK;
165
166 /* Setup the table.  */
167 static void
168 class_table_setup (void)
169 {
170   /* Start - nothing in the table.  */
171   memset (class_table_array, 0, sizeof (class_node_ptr) * CLASS_TABLE_SIZE);
172
173   /* The table writing mutex.  */
174   __class_table_lock = objc_mutex_allocate ();
175 }
176
177
178 /* Insert a class in the table (used when a new class is
179    registered).  */
180 static void 
181 class_table_insert (const char *class_name, Class class_pointer)
182 {
183   int hash, length;
184   class_node_ptr new_node;
185
186   /* Find out the class name's hash and length.  */
187   CLASS_TABLE_HASH (length, hash, class_name);
188   
189   /* Prepare the new node holding the class.  */
190   new_node = objc_malloc (sizeof (struct class_node));
191   new_node->name = class_name;
192   new_node->length = length;
193   new_node->pointer = class_pointer;
194
195   /* Lock the table for modifications.  */
196   objc_mutex_lock (__class_table_lock);
197   
198   /* Insert the new node in the table at the beginning of the table at
199      class_table_array[hash].  */
200   new_node->next = class_table_array[hash];
201   class_table_array[hash] = new_node;
202   
203   objc_mutex_unlock (__class_table_lock);
204 }
205
206 /* Replace a class in the table (used only by poseAs:).  */
207 static void 
208 class_table_replace (Class old_class_pointer, Class new_class_pointer)
209 {
210   int hash;
211   class_node_ptr node;
212
213   objc_mutex_lock (__class_table_lock);
214   
215   hash = 0;
216   node = class_table_array[hash];
217   
218   while (hash < CLASS_TABLE_SIZE)
219     {
220       if (node == NULL)
221         {
222           hash++;
223           if (hash < CLASS_TABLE_SIZE)
224             node = class_table_array[hash];
225         }
226       else
227         {
228           Class class1 = node->pointer;
229
230           if (class1 == old_class_pointer)
231             node->pointer = new_class_pointer;
232
233           node = node->next;
234         }
235     }
236
237   objc_mutex_unlock (__class_table_lock);
238 }
239
240
241 /* Get a class from the table.  This does not need mutex protection.
242    Currently, this function is called each time you call a static
243    method, this is why it must be very fast.  */
244 static inline Class 
245 class_table_get_safe (const char *class_name)
246 {
247   class_node_ptr node;  
248   int length, hash;
249
250   /* Compute length and hash.  */
251   CLASS_TABLE_HASH (length, hash, class_name);
252   
253   node = class_table_array[hash];
254   
255   if (node != NULL)
256     {
257       do
258         {
259           if (node->length == length)
260             {
261               /* Compare the class names.  */
262               int i;
263
264               for (i = 0; i < length; i++)
265                 {
266                   if ((node->name)[i] != class_name[i]) 
267                     break;
268                 }
269               
270               if (i == length)
271                 {
272                   /* They are equal!  */
273                   return node->pointer;
274                 }
275             }
276         }
277       while ((node = node->next) != NULL);
278     }
279
280   return Nil;
281 }
282
283 /* Enumerate over the class table.  */
284 struct class_table_enumerator
285 {
286   int hash;
287   class_node_ptr node;
288 };
289
290
291 static Class
292 class_table_next (struct class_table_enumerator **e)
293 {
294   struct class_table_enumerator *enumerator = *e;
295   class_node_ptr next;
296   
297   if (enumerator == NULL)
298     {
299        *e = objc_malloc (sizeof (struct class_table_enumerator));
300       enumerator = *e;
301       enumerator->hash = 0;
302       enumerator->node = NULL;
303
304       next = class_table_array[enumerator->hash];
305     }
306   else
307     next = enumerator->node->next;
308   
309   if (next != NULL)
310     {
311       enumerator->node = next;
312       return enumerator->node->pointer;
313     }
314   else 
315     {
316       enumerator->hash++;
317      
318       while (enumerator->hash < CLASS_TABLE_SIZE)
319         {
320           next = class_table_array[enumerator->hash];
321           if (next != NULL)
322             {
323               enumerator->node = next;
324               return enumerator->node->pointer;
325             }
326           enumerator->hash++;
327         }
328       
329       /* Ok - table finished - done.  */
330       objc_free (enumerator);
331       return Nil;
332     }
333 }
334
335 #if 0 /* DEBUGGING FUNCTIONS */
336 /* Debugging function - print the class table.  */
337 void
338 class_table_print (void)
339 {
340   int i;
341   
342   for (i = 0; i < CLASS_TABLE_SIZE; i++)
343     {
344       class_node_ptr node;
345       
346       printf ("%d:\n", i);
347       node = class_table_array[i];
348       
349       while (node != NULL)
350         {
351           printf ("\t%s\n", node->name);
352           node = node->next;
353         }
354     }
355 }
356
357 /* Debugging function - print an histogram of number of classes in
358    function of hash key values.  Useful to evaluate the hash function
359    in real cases.  */
360 void
361 class_table_print_histogram (void)
362 {
363   int i, j;
364   int counter = 0;
365   
366   for (i = 0; i < CLASS_TABLE_SIZE; i++)
367     {
368       class_node_ptr node;
369       
370       node = class_table_array[i];
371       
372       while (node != NULL)
373         {
374           counter++;
375           node = node->next;
376         }
377       if (((i + 1) % 50) == 0)
378         {
379           printf ("%4d:", i + 1);
380           for (j = 0; j < counter; j++)
381             printf ("X");
382
383           printf ("\n");
384           counter = 0;
385         }
386     }
387   printf ("%4d:", i + 1);
388   for (j = 0; j < counter; j++)
389     printf ("X");
390
391   printf ("\n");
392 }
393 #endif /* DEBUGGING FUNCTIONS */
394
395 /**
396  ** Objective-C runtime functions
397  **/
398
399 /* From now on, the only access to the class table data structure
400    should be via the class_table_* functions.  */
401
402 /* This is a hook which is called by objc_get_class and
403    objc_lookup_class if the runtime is not able to find the class.
404    This may e.g. try to load in the class using dynamic loading.
405
406    This hook was a public, global variable in the Traditional GNU
407    Objective-C Runtime API (objc/objc-api.h).  The modern GNU
408    Objective-C Runtime API (objc/runtime.h) provides the
409    objc_setGetUnknownClassHandler() function instead.
410 */
411 Class (*_objc_lookup_class) (const char *name) = 0;      /* !T:SAFE */
412
413 /* The handler currently in use.  PS: if both
414    __obj_get_unknown_class_handler and _objc_lookup_class are defined,
415    __objc_get_unknown_class_handler is called first.  */
416 static objc_get_unknown_class_handler
417 __objc_get_unknown_class_handler = NULL;
418
419 objc_get_unknown_class_handler
420 objc_setGetUnknownClassHandler (objc_get_unknown_class_handler 
421                                 new_handler)
422 {
423   objc_get_unknown_class_handler old_handler 
424     = __objc_get_unknown_class_handler;
425   __objc_get_unknown_class_handler = new_handler;
426   return old_handler;
427 }
428
429
430 /* True when class links has been resolved.  */     
431 BOOL __objc_class_links_resolved = NO;                  /* !T:UNUSED */
432
433
434 void
435 __objc_init_class_tables (void)
436 {
437   /* Allocate the class hash table.  */
438   
439   if (__class_table_lock)
440     return;
441   
442   objc_mutex_lock (__objc_runtime_mutex);
443   
444   class_table_setup ();
445
446   objc_mutex_unlock (__objc_runtime_mutex);
447 }  
448
449 /* This function adds a class to the class hash table, and assigns the
450    class a number, unless it's already known.  Return 'YES' if the
451    class was added.  Return 'NO' if the class was already known.  */
452 BOOL
453 __objc_add_class_to_hash (Class class)
454 {
455   Class existing_class;
456
457   objc_mutex_lock (__objc_runtime_mutex);
458
459   /* Make sure the table is there.  */
460   assert (__class_table_lock);
461
462   /* Make sure it's not a meta class.  */
463   assert (CLS_ISCLASS (class));
464
465   /* Check to see if the class is already in the hash table.  */
466   existing_class = class_table_get_safe (class->name);
467
468   if (existing_class)
469     {
470       objc_mutex_unlock (__objc_runtime_mutex);
471       return NO;      
472     }
473   else
474     {
475       /* The class isn't in the hash table.  Add the class and assign
476          a class number.  */
477       static unsigned int class_number = 1;
478       
479       CLS_SETNUMBER (class, class_number);
480       CLS_SETNUMBER (class->class_pointer, class_number);
481
482       ++class_number;
483       class_table_insert (class->name, class);
484
485       objc_mutex_unlock (__objc_runtime_mutex);
486       return YES;
487     }
488 }
489
490 Class
491 objc_getClass (const char *name)
492 {
493   Class class;
494
495   if (name == NULL)
496     return Nil;
497
498   class = class_table_get_safe (name);
499   
500   if (class)
501     return class;
502
503   if (__objc_get_unknown_class_handler)
504     return (*__objc_get_unknown_class_handler) (name);
505
506   if (_objc_lookup_class)
507     return (*_objc_lookup_class) (name);
508
509   return Nil;
510 }
511
512 Class
513 objc_lookUpClass (const char *name)
514 {
515   if (name == NULL)
516     return Nil;
517   else
518     return class_table_get_safe (name);
519 }
520
521 Class
522 objc_getMetaClass (const char *name)
523 {
524   Class class = objc_getClass (name);
525
526   if (class)
527     return class->class_pointer;
528   else
529     return Nil;
530 }
531
532 Class
533 objc_getRequiredClass (const char *name)
534 {
535   Class class = objc_getClass (name);
536
537   if (class)
538     return class;
539   else
540     _objc_abort ("objc_getRequiredClass ('%s') failed: class not found\n", name);
541 }
542
543 int
544 objc_getClassList (Class *returnValue, int maxNumberOfClassesToReturn)
545 {
546   /* Iterate over all entries in the table.  */
547   int hash, count = 0;
548
549   for (hash = 0; hash < CLASS_TABLE_SIZE; hash++)
550     {
551       class_node_ptr node = class_table_array[hash];
552       
553       while (node != NULL)
554         {
555           if (returnValue)
556             {
557               if (count < maxNumberOfClassesToReturn)
558                 returnValue[count] = node->pointer;
559               else
560                 return count;
561             }
562           count++;
563           node = node->next;
564         }
565     }
566   
567   return count;
568 }
569
570 Class
571 objc_allocateClassPair (Class super_class, const char *class_name, size_t extraBytes)
572 {
573   Class new_class;
574   Class new_meta_class;
575
576   if (class_name == NULL)
577     return Nil;
578
579   if (objc_getClass (class_name))
580     return Nil;
581
582   if (super_class)
583     {
584       /* If you want to build a hierarchy of classes, you need to
585          build and register them one at a time.  The risk is that you
586          are able to cause confusion by registering a subclass before
587          the superclass or similar.  */
588       if (CLS_IS_IN_CONSTRUCTION (super_class))
589         return Nil;
590     }
591
592   /* Technically, we should create the metaclass first, then use
593      class_createInstance() to create the class.  That complication
594      would be relevant if we had class variables, but we don't, so we
595      just ignore it and create everything directly and assume all
596      classes have the same size.  */
597   new_class = objc_calloc (1, sizeof (struct objc_class) + extraBytes);
598   new_meta_class = objc_calloc (1, sizeof (struct objc_class) + extraBytes);
599
600   /* We create an unresolved class, similar to one generated by the
601      compiler.  It will be resolved later when we register it.
602
603      Note how the metaclass details are not that important; when the
604      class is resolved, the ones that matter will be fixed up.  */
605   new_class->class_pointer = new_meta_class;
606   new_meta_class->class_pointer = 0;
607
608   if (super_class)
609     {
610       /* Force the name of the superclass in place of the link to the
611          actual superclass, which will be put there when the class is
612          resolved.  */
613       const char *super_class_name = class_getName (super_class);
614       new_class->super_class = (void *)super_class_name;
615       new_meta_class->super_class = (void *)super_class_name;
616     }
617   else
618     {
619       new_class->super_class = (void *)0;
620       new_meta_class->super_class = (void *)0;
621     }
622
623   new_class->name = objc_malloc (strlen (class_name) + 1);
624   strcpy ((char*)new_class->name, class_name);
625   new_meta_class->name = new_class->name;
626
627   new_class->version = 0;
628   new_meta_class->version = 0;
629
630   new_class->info = _CLS_CLASS | _CLS_IN_CONSTRUCTION;
631   new_meta_class->info = _CLS_META | _CLS_IN_CONSTRUCTION;
632
633   if (super_class)
634     new_class->instance_size = super_class->instance_size;
635   else
636     new_class->instance_size = 0;
637   new_meta_class->instance_size = sizeof (struct objc_class);
638
639   return new_class;
640 }
641
642 void
643 objc_registerClassPair (Class class_)
644 {
645   if (class_ == Nil)
646     return;
647
648   if ((! CLS_ISCLASS (class_)) || (! CLS_IS_IN_CONSTRUCTION (class_)))
649     return;
650
651   if ((! CLS_ISMETA (class_->class_pointer)) || (! CLS_IS_IN_CONSTRUCTION (class_->class_pointer)))
652     return;
653
654   objc_mutex_lock (__objc_runtime_mutex);
655
656   if (objc_getClass (class_->name))
657     {
658       objc_mutex_unlock (__objc_runtime_mutex);
659       return;
660     }
661
662   CLS_SET_NOT_IN_CONSTRUCTION (class_);
663   CLS_SET_NOT_IN_CONSTRUCTION (class_->class_pointer);
664
665   __objc_init_class (class_);
666
667   /* Resolve class links immediately.  No point in waiting.  */
668   __objc_resolve_class_links ();
669
670   objc_mutex_unlock (__objc_runtime_mutex);
671 }
672
673 void
674 objc_disposeClassPair (Class class_)
675 {
676   if (class_ == Nil)
677     return;
678
679   if ((! CLS_ISCLASS (class_)) || (! CLS_IS_IN_CONSTRUCTION (class_)))
680     return;
681
682   if ((! CLS_ISMETA (class_->class_pointer)) || (! CLS_IS_IN_CONSTRUCTION (class_->class_pointer)))
683     return;
684
685   /* Undo any class_addIvar().  */
686   if (class_->ivars)
687     {
688       int i;
689       for (i = 0; i < class_->ivars->ivar_count; i++)
690         {
691           struct objc_ivar *ivar = &(class_->ivars->ivar_list[i]);
692
693           objc_free ((char *)ivar->ivar_name);
694           objc_free ((char *)ivar->ivar_type);
695         }
696       
697       objc_free (class_->ivars);
698     }
699
700   /* Undo any class_addMethod().  */
701   if (class_->methods)
702     {
703       struct objc_method_list *list = class_->methods;
704       while (list)
705         {
706           int i;
707           struct objc_method_list *next = list->method_next;
708
709           for (i = 0; i < list->method_count; i++)
710             {
711               struct objc_method *method = &(list->method_list[i]);
712
713               objc_free ((char *)method->method_name);
714               objc_free ((char *)method->method_types);
715             }
716
717           objc_free (list);
718           list = next;
719         }
720     }
721
722   /* Undo any class_addProtocol().  */
723   if (class_->protocols)
724     {
725       struct objc_protocol_list *list = class_->protocols;
726       while (list)
727         {
728           struct objc_protocol_list *next = list->next;
729
730           objc_free (list);
731           list = next;
732         }
733     }
734   
735   /* Undo any class_addMethod() on the meta-class.  */
736   if (class_->class_pointer->methods)
737     {
738       struct objc_method_list *list = class_->class_pointer->methods;
739       while (list)
740         {
741           int i;
742           struct objc_method_list *next = list->method_next;
743
744           for (i = 0; i < list->method_count; i++)
745             {
746               struct objc_method *method = &(list->method_list[i]);
747
748               objc_free ((char *)method->method_name);
749               objc_free ((char *)method->method_types);
750             }
751
752           objc_free (list);
753           list = next;
754         }
755     }
756
757   /* Undo objc_allocateClassPair().  */
758   objc_free ((char *)(class_->name));
759   objc_free (class_->class_pointer);
760   objc_free (class_);
761 }
762
763 /* Traditional GNU Objective-C Runtime API.  */
764 /* Get the class object for the class named NAME.  If NAME does not
765    identify a known class, the hook _objc_lookup_class is called.  If
766    this fails, nil is returned.  */
767 Class
768 objc_lookup_class (const char *name)
769 {
770   return objc_getClass (name);
771 }
772
773 /* Traditional GNU Objective-C Runtime API.  Important: this method is
774    called automatically by the compiler while messaging (if using the
775    traditional ABI), so it is worth keeping it fast; don't make it
776    just a wrapper around objc_getClass().  */
777 /* Note that this is roughly equivalent to objc_getRequiredClass().  */
778 /* Get the class object for the class named NAME.  If NAME does not
779    identify a known class, the hook _objc_lookup_class is called.  If
780    this fails, an error message is issued and the system aborts.  */
781 Class
782 objc_get_class (const char *name)
783 {
784   Class class;
785
786   class = class_table_get_safe (name);
787
788   if (class)
789     return class;
790
791   if (__objc_get_unknown_class_handler)
792     class = (*__objc_get_unknown_class_handler) (name);
793
794   if ((!class)  &&  _objc_lookup_class)
795     class = (*_objc_lookup_class) (name);
796
797   if (class)
798     return class;
799   
800   _objc_abort ("objc runtime: cannot find class %s\n", name);
801
802   return 0;
803 }
804
805 Class
806 objc_get_meta_class (const char *name)
807 {
808   return objc_get_class (name)->class_pointer;
809 }
810
811 /* This function provides a way to enumerate all the classes in the
812    executable.  Pass *ENUM_STATE == NULL to start the enumeration.  The
813    function will return 0 when there are no more classes.  
814    For example: 
815        id class; 
816        void *es = NULL;
817        while ((class = objc_next_class (&es)))
818          ... do something with class; 
819 */
820 Class
821 objc_next_class (void **enum_state)
822 {
823   Class class;
824
825   objc_mutex_lock (__objc_runtime_mutex);
826   
827   /* Make sure the table is there.  */
828   assert (__class_table_lock);
829
830   class = class_table_next ((struct class_table_enumerator **) enum_state);
831
832   objc_mutex_unlock (__objc_runtime_mutex);
833   
834   return class;
835 }
836
837 /* This is used when the implementation of a method changes.  It goes
838    through all classes, looking for the ones that have these methods
839    (either method_a or method_b; method_b can be NULL), and reloads
840    the implementation for these.  You should call this with the
841    runtime mutex already locked.  */
842 void
843 __objc_update_classes_with_methods (struct objc_method *method_a, struct objc_method *method_b)
844 {
845   int hash;
846
847   /* Iterate over all classes.  */
848   for (hash = 0; hash < CLASS_TABLE_SIZE; hash++)
849     {
850       class_node_ptr node = class_table_array[hash];
851       
852       while (node != NULL)
853         {
854           /* Iterate over all methods in the class.  */
855           Class class = node->pointer;
856           struct objc_method_list * method_list = class->methods;
857
858           while (method_list)
859             {
860               int i;
861
862               for (i = 0; i < method_list->method_count; ++i)
863                 {
864                   struct objc_method *method = &method_list->method_list[i];
865
866                   /* If the method is one of the ones we are looking
867                      for, update the implementation.  */
868                   if (method == method_a)
869                     sarray_at_put_safe (class->dtable,
870                                         (sidx) method_a->method_name->sel_id,
871                                         method_a->method_imp);
872
873                   if (method == method_b)
874                     {
875                       if (method_b != NULL)
876                         sarray_at_put_safe (class->dtable,
877                                             (sidx) method_b->method_name->sel_id,
878                                             method_b->method_imp);
879                     }
880                 }
881           
882               method_list = method_list->method_next;
883             }
884           node = node->next;
885         }
886     }
887 }
888
889 /* Resolve super/subclass links for all classes.  The only thing we
890    can be sure of is that the class_pointer for class objects point to
891    the right meta class objects.  */
892 void
893 __objc_resolve_class_links (void)
894 {
895   struct class_table_enumerator *es = NULL;
896   Class object_class = objc_get_class ("Object");
897   Class class1;
898
899   assert (object_class);
900
901   objc_mutex_lock (__objc_runtime_mutex);
902
903   /* Assign subclass links.  */
904   while ((class1 = class_table_next (&es)))
905     {
906       /* Make sure we have what we think we have.  */
907       assert (CLS_ISCLASS (class1));
908       assert (CLS_ISMETA (class1->class_pointer));
909
910       /* The class_pointer of all meta classes point to Object's meta
911          class.  */
912       class1->class_pointer->class_pointer = object_class->class_pointer;
913
914       if (! CLS_ISRESOLV (class1))
915         {
916           CLS_SETRESOLV (class1);
917           CLS_SETRESOLV (class1->class_pointer);
918               
919           if (class1->super_class)
920             {   
921               Class a_super_class 
922                 = objc_get_class ((char *) class1->super_class);
923               
924               assert (a_super_class);
925               
926               DEBUG_PRINTF ("making class connections for: %s\n",
927                             class1->name);
928               
929               /* Assign subclass links for superclass.  */
930               class1->sibling_class = a_super_class->subclass_list;
931               a_super_class->subclass_list = class1;
932               
933               /* Assign subclass links for meta class of superclass.  */
934               if (a_super_class->class_pointer)
935                 {
936                   class1->class_pointer->sibling_class
937                     = a_super_class->class_pointer->subclass_list;
938                   a_super_class->class_pointer->subclass_list 
939                     = class1->class_pointer;
940                 }
941             }
942           else /* A root class, make its meta object be a subclass of
943                   Object.  */
944             {
945               class1->class_pointer->sibling_class 
946                 = object_class->subclass_list;
947               object_class->subclass_list = class1->class_pointer;
948             }
949         }
950     }
951
952   /* Assign superclass links.  */
953    es = NULL;
954    while ((class1 = class_table_next (&es)))
955     {
956       Class sub_class;
957       for (sub_class = class1->subclass_list; sub_class;
958            sub_class = sub_class->sibling_class)
959         {
960           sub_class->super_class = class1;
961           if (CLS_ISCLASS (sub_class))
962             sub_class->class_pointer->super_class = class1->class_pointer;
963         }
964     }
965
966   objc_mutex_unlock (__objc_runtime_mutex);
967 }
968
969 const char *
970 class_getName (Class class_)
971 {
972   if (class_ == Nil)
973     return "nil";
974
975   return class_->name;
976 }
977
978 BOOL
979 class_isMetaClass (Class class_)
980 {
981   /* CLS_ISMETA includes the check for Nil class_.  */
982   return CLS_ISMETA (class_);
983 }
984
985 /* Even inside libobjc it may be worth using class_getSuperclass
986    instead of accessing class_->super_class directly because it
987    resolves the class links if needed.  If you access
988    class_->super_class directly, make sure to deal with the situation
989    where the class is not resolved yet!  */
990 Class
991 class_getSuperclass (Class class_)
992 {
993   if (class_ == Nil)
994     return Nil;
995
996   /* Classes that are in construction are not resolved and can not be
997      resolved!  */
998   if (CLS_IS_IN_CONSTRUCTION (class_))
999     return Nil;
1000
1001   /* If the class is not resolved yet, super_class would point to a
1002      string (the name of the super class) as opposed to the actual
1003      super class.  In that case, we need to resolve the class links
1004      before we can return super_class.  */
1005   if (! CLS_ISRESOLV (class_))
1006     __objc_resolve_class_links ();
1007   
1008   return class_->super_class;
1009 }
1010
1011 int
1012 class_getVersion (Class class_)
1013 {
1014   if (class_ == Nil)
1015     return 0;
1016
1017   return (int)(class_->version);
1018 }
1019
1020 void
1021 class_setVersion (Class class_, int version)
1022 {
1023   if (class_ == Nil)
1024     return;
1025
1026   class_->version = version;
1027 }
1028
1029 size_t
1030 class_getInstanceSize (Class class_)
1031 {
1032   if (class_ == Nil)
1033     return 0;
1034
1035   return class_->instance_size;
1036 }
1037
1038 #define CLASSOF(c) ((c)->class_pointer)
1039
1040 Class
1041 class_pose_as (Class impostor, Class super_class)
1042 {
1043   if (! CLS_ISRESOLV (impostor))
1044     __objc_resolve_class_links ();
1045
1046   /* Preconditions */
1047   assert (impostor);
1048   assert (super_class);
1049   assert (impostor->super_class == super_class);
1050   assert (CLS_ISCLASS (impostor));
1051   assert (CLS_ISCLASS (super_class));
1052   assert (impostor->instance_size == super_class->instance_size);
1053
1054   {
1055     Class *subclass = &(super_class->subclass_list);
1056
1057     /* Move subclasses of super_class to impostor.  */
1058     while (*subclass)
1059       {
1060         Class nextSub = (*subclass)->sibling_class;
1061
1062         if (*subclass != impostor)
1063           {
1064             Class sub = *subclass;
1065
1066             /* Classes */
1067             sub->sibling_class = impostor->subclass_list;
1068             sub->super_class = impostor;
1069             impostor->subclass_list = sub;
1070
1071             /* It will happen that SUB is not a class object if it is
1072                the top of the meta class hierarchy chain (root
1073                meta-class objects inherit their class object).  If
1074                that is the case... don't mess with the meta-meta
1075                class.  */
1076             if (CLS_ISCLASS (sub))
1077               {
1078                 /* Meta classes */
1079                 CLASSOF (sub)->sibling_class = 
1080                   CLASSOF (impostor)->subclass_list;
1081                 CLASSOF (sub)->super_class = CLASSOF (impostor);
1082                 CLASSOF (impostor)->subclass_list = CLASSOF (sub);
1083               }
1084           }
1085
1086         *subclass = nextSub;
1087       }
1088
1089     /* Set subclasses of superclass to be impostor only.  */
1090     super_class->subclass_list = impostor;
1091     CLASSOF (super_class)->subclass_list = CLASSOF (impostor);
1092     
1093     /* Set impostor to have no sibling classes.  */
1094     impostor->sibling_class = 0;
1095     CLASSOF (impostor)->sibling_class = 0;
1096   }
1097   
1098   /* Check relationship of impostor and super_class is kept.  */
1099   assert (impostor->super_class == super_class);
1100   assert (CLASSOF (impostor)->super_class == CLASSOF (super_class));
1101
1102   /* This is how to update the lookup table.  Regardless of what the
1103      keys of the hashtable is, change all values that are superclass
1104      into impostor.  */
1105
1106   objc_mutex_lock (__objc_runtime_mutex);
1107
1108   class_table_replace (super_class, impostor);
1109
1110   objc_mutex_unlock (__objc_runtime_mutex);
1111
1112   /* Next, we update the dispatch tables...  */
1113   __objc_update_dispatch_table_for_class (CLASSOF (impostor));
1114   __objc_update_dispatch_table_for_class (impostor);
1115
1116   return impostor;
1117 }