OSDN Git Service

In libobjc/:
[pf3gnuchains/gcc-fork.git] / libobjc / init.c
1 /* GNU Objective C Runtime initialization 
2    Copyright (C) 1993, 1995, 1996, 1997, 2002, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Kresten Krab Thorup
5    +load support contributed by Ovidiu Predescu <ovidiu@net-community.com>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under the
10 terms of the GNU General Public License as published by the Free Software
11 Foundation; either version 3, or (at your option) any later version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
16 details.
17
18 Under Section 7 of GPL version 3, you are granted additional
19 permissions described in the GCC Runtime Library Exception, version
20 3.1, as published by the Free Software Foundation.
21
22 You should have received a copy of the GNU General Public License and
23 a copy of the GCC Runtime Library Exception along with this program;
24 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
25 <http://www.gnu.org/licenses/>.  */
26
27 /* Uncommented the following line to enable debug logging.  Use this
28    only while debugging the runtime.  */
29 /* #define DEBUG 1 */
30
31 #include "objc-private/common.h"
32 #include "objc-private/error.h"
33 #include "objc/runtime.h"
34 #include "objc/thr.h"
35 #include "objc-private/hash.h"
36 #include "objc-private/objc-list.h" 
37 #include "objc-private/module-abi-8.h" 
38 #include "objc-private/runtime.h"   /* For __objc_resolve_class_links().  */
39 #include "objc-private/selector.h"  /* For __sel_register_typed_name().  */
40 #include "objc-private/objc-sync.h" /* For __objc_sync_init() */
41 #include "objc-private/protocols.h" /* For __objc_protocols_init(),
42                                        __objc_protocols_add_protocol()
43                                        __objc_protocols_register_selectors() */
44 #include "objc-private/accessors.h" /* For __objc_accessors_init() */
45
46 /* The version number of this runtime.  This must match the number
47    defined in gcc (objc-act.c).  */
48 #define OBJC_VERSION 8
49 #define PROTOCOL_VERSION 2
50
51 /* This list contains modules currently loaded into the runtime and
52    for which the +load method (and the load callback, if any) has not
53    been called yet.  */
54 static struct objc_list *__objc_module_list = 0;        /* !T:MUTEX */
55
56 /* This list contains all proto_list's not yet assigned class
57    links.  */
58 static struct objc_list *unclaimed_proto_list = 0;      /* !T:MUTEX */
59
60 /* List of unresolved static instances.  */
61 static struct objc_list *uninitialized_statics = 0;     /* !T:MUTEX */
62
63 /* List of duplicated classes found while loading modules.  If we find
64    a class twice, we ignore it the second time.  On some platforms,
65    where the order in which modules are loaded is well defined, this
66    allows you to replace a class in a shared library by linking in a
67    new implementation which is loaded in in the right order, and which
68    overrides the existing one.
69
70    Protected by __objc_runtime_mutex.  */
71 static cache_ptr duplicate_classes = NULL;
72
73 /* Global runtime "write" mutex.  Having a single mutex prevents
74    deadlocks, but reduces concurrency.  To improve concurrency, some
75    groups of functions in the runtime have their own separate mutex
76    (eg, __class_table_lock in class.c); to avoid deadlocks, these
77    routines must make sure that they never acquire any other lock
78    while holding their own local lock.  Ie, they should lock, execute
79    some C code that does not perform any calls to other runtime
80    functions which may potentially lock different locks, then unlock.
81    If they need to perform any calls to other runtime functions that
82    may potentially lock other locks, then they should use the global
83    __objc_runtime_mutex.  */
84 objc_mutex_t __objc_runtime_mutex = 0;
85
86 /* Number of threads that are alive.  */
87 int __objc_runtime_threads_alive = 1;                   /* !T:MUTEX */
88
89 /* Check compiler vs runtime version.  */
90 static void init_check_module_version (struct objc_module *);
91
92 /* Assign isa links to protos.  */
93 static void __objc_init_protocols (struct objc_protocol_list *protos);
94
95 /* Assign isa link to a protocol, and register it.  */
96 static void __objc_init_protocol (struct objc_protocol *protocol);
97
98 /* Add protocol to class.  */
99 static void __objc_class_add_protocols (Class, struct objc_protocol_list *);
100
101 /* Load callback hook.  */
102 void (*_objc_load_callback) (Class class, struct objc_category *category) = 0; /* !T:SAFE */
103
104 /* Are all categories/classes resolved ?  */
105 BOOL __objc_dangling_categories = NO;           /* !T:UNUSED */
106
107 /* Sends +load to all classes and categories in certain
108    situations.  */
109 static void objc_send_load (void);
110
111 /* Inserts all the classes defined in module in a tree of classes that
112    resembles the class hierarchy. This tree is traversed in preorder
113    and the classes in its nodes receive the +load message if these
114    methods were not executed before. The algorithm ensures that when
115    the +load method of a class is executed all the superclasses have
116    been already received the +load message.  */
117 static void __objc_create_classes_tree (struct objc_module *module);
118
119 /* Calls the _objc_load_callback for each class and category in the
120    module (if _objc_load_callback is not NULL).  */
121 static void __objc_call_load_callback (struct objc_module *module);
122
123 /* A special version that works only before the classes are completely
124    installed in the runtime.  */
125 static BOOL class_is_subclass_of_class (Class class, Class superclass);
126
127 typedef struct objc_class_tree
128 {
129   Class class;
130   struct objc_list *subclasses; /* `head' is a pointer to an
131                                    objc_class_tree.  */
132 } objc_class_tree;
133
134 /* This is a linked list of objc_class_tree trees. The head of these
135    trees are root classes (their super class is Nil). These different
136    trees represent different class hierarchies.  */
137 static struct objc_list *__objc_class_tree_list = NULL;
138
139 /* Keeps the +load methods who have been already executed. This hash
140    should not be destroyed during the execution of the program.  */
141 static cache_ptr __objc_load_methods = NULL;
142
143 /* This function is used when building the class tree used to send
144    ordinately the +load message to all classes needing it.  The tree
145    is really needed so that superclasses will get the message before
146    subclasses.
147
148    This tree will contain classes which are being loaded (or have just
149    being loaded), and whose super_class pointers have not yet been
150    resolved.  This implies that their super_class pointers point to a
151    string with the name of the superclass; when the first message is
152    sent to the class (/an object of that class) the class links will
153    be resolved, which will replace the super_class pointers with
154    pointers to the actual superclasses.
155
156    Unfortunately, the tree might also contain classes which had been
157    loaded previously, and whose class links have already been
158    resolved.
159
160    This function returns the superclass of a class in both cases, and
161    can be used to build the determine the class relationships while
162    building the tree.  */
163 static Class  class_superclass_of_class (Class class)
164 {
165   char *super_class_name;
166
167   /* If the class links have been resolved, use the resolved
168      links.  */
169   if (CLS_ISRESOLV (class))
170     return class->super_class;
171   
172   /* Else, 'class' has not yet been resolved.  This means that its
173      super_class pointer is really the name of the super class (rather
174      than a pointer to the actual superclass).  */
175   super_class_name = (char *)class->super_class;
176
177   /* Return Nil for a root class.  */
178   if (super_class_name == NULL)
179     return Nil;
180
181   /* Lookup the superclass of non-root classes.  */
182   return objc_getClass (super_class_name);
183 }
184
185
186 /* Creates a tree of classes whose topmost class is directly inherited
187    from `upper' and the bottom class in this tree is
188    `bottom_class'. The classes in this tree are super classes of
189    `bottom_class'. `subclasses' member of each tree node point to the
190    next subclass tree node.  */
191 static objc_class_tree *
192 create_tree_of_subclasses_inherited_from (Class bottom_class, Class upper)
193 {
194   Class superclass;
195   objc_class_tree *tree, *prev;
196
197   if (bottom_class->super_class)
198     superclass = objc_getClass ((char *) bottom_class->super_class);
199   else
200     superclass = Nil;
201
202   DEBUG_PRINTF ("create_tree_of_subclasses_inherited_from:");
203   DEBUG_PRINTF (" bottom_class = %s, upper = %s\n",
204                 (bottom_class ? bottom_class->name : NULL),
205                 (upper ? upper->name : NULL));
206
207   tree = prev = objc_calloc (1, sizeof (objc_class_tree));
208   prev->class = bottom_class;
209
210   while (superclass != upper)
211     {
212       tree = objc_calloc (1, sizeof (objc_class_tree));
213       tree->class = superclass;
214       tree->subclasses = list_cons (prev, tree->subclasses);
215       superclass = class_superclass_of_class (superclass);
216       prev = tree;
217     }
218
219   return tree;
220 }
221
222 /* Insert the `class' into the proper place in the `tree' class
223    hierarchy. This function returns a new tree if the class has been
224    successfully inserted into the tree or NULL if the class is not
225    part of the classes hierarchy described by `tree'. This function is
226    private to objc_tree_insert_class (), you should not call it
227    directly.  */
228 static objc_class_tree *
229 __objc_tree_insert_class (objc_class_tree *tree, Class class)
230 {
231   DEBUG_PRINTF ("__objc_tree_insert_class: tree = %p, class = %s\n",
232                 tree, class->name);
233
234   if (tree == NULL)
235     return create_tree_of_subclasses_inherited_from (class, NULL);
236   else if (class == tree->class)
237     {
238       /* `class' has been already inserted.  */
239       DEBUG_PRINTF (" 1. class %s was previously inserted\n", class->name);
240       return tree;
241     }
242   else if (class_superclass_of_class (class) == tree->class)
243     {
244       /* If class is a direct subclass of tree->class then add class
245          to the list of subclasses. First check to see if it wasn't
246          already inserted.  */
247       struct objc_list *list = tree->subclasses;
248       objc_class_tree *node;
249
250       while (list)
251         {
252           /* Class has been already inserted; do nothing just return
253              the tree.  */
254           if (((objc_class_tree *) list->head)->class == class)
255             {
256               DEBUG_PRINTF (" 2. class %s was previously inserted\n",
257                             class->name);
258               return tree;
259             }
260           list = list->tail;
261         }
262
263       /* Create a new node class and insert it into the list of
264          subclasses.  */
265       node = objc_calloc (1, sizeof (objc_class_tree));
266       node->class = class;
267       tree->subclasses = list_cons (node, tree->subclasses);
268       DEBUG_PRINTF (" 3. class %s inserted\n", class->name);
269       return tree;
270     }
271   else
272     {
273       /* The class is not a direct subclass of tree->class.  Search
274          for class's superclasses in the list of subclasses.  */
275       struct objc_list *subclasses = tree->subclasses;
276
277       /* Precondition: the class must be a subclass of tree->class;
278          otherwise return NULL to indicate our caller that it must
279          take the next tree.  */
280       if (! class_is_subclass_of_class (class, tree->class))
281         return NULL;
282
283       for (; subclasses != NULL; subclasses = subclasses->tail)
284         {
285           Class aClass = ((objc_class_tree *) (subclasses->head))->class;
286
287           if (class_is_subclass_of_class (class, aClass))
288             {
289               /* If we found one of class's superclasses we insert the
290                  class into its subtree and return the original tree
291                  since nothing has been changed.  */
292               subclasses->head
293                   = __objc_tree_insert_class (subclasses->head, class);
294               DEBUG_PRINTF (" 4. class %s inserted\n", class->name);
295               return tree;
296             }
297         }
298
299       /* We haven't found a subclass of `class' in the `subclasses'
300          list.  Create a new tree of classes whose topmost class is a
301          direct subclass of tree->class.  */
302       {
303         objc_class_tree *new_tree
304           = create_tree_of_subclasses_inherited_from (class, tree->class);
305         tree->subclasses = list_cons (new_tree, tree->subclasses);
306         DEBUG_PRINTF (" 5. class %s inserted\n", class->name);
307         return tree;
308       }
309     }
310 }
311
312 /* This function inserts `class' in the right tree hierarchy classes.  */
313 static void
314 objc_tree_insert_class (Class class)
315 {
316   struct objc_list *list_node;
317   objc_class_tree *tree;
318
319   list_node = __objc_class_tree_list;
320   while (list_node)
321     {
322       tree = __objc_tree_insert_class (list_node->head, class);
323       if (tree)
324         {
325           list_node->head = tree;
326           break;
327         }
328       else
329         list_node = list_node->tail;
330     }
331
332   /* If the list was finished but the class hasn't been inserted,
333      insert it here.  */
334   if (! list_node)
335     {
336       __objc_class_tree_list = list_cons (NULL, __objc_class_tree_list);
337       __objc_class_tree_list->head = __objc_tree_insert_class (NULL, class);
338     }
339 }
340
341 /* Traverse tree in preorder. Used to send +load.  */
342 static void
343 objc_preorder_traverse (objc_class_tree *tree,
344                         int level,
345                         void (*function) (objc_class_tree *, int))
346 {
347   struct objc_list *node;
348
349   (*function) (tree, level);
350   for (node = tree->subclasses; node; node = node->tail)
351     objc_preorder_traverse (node->head, level + 1, function);
352 }
353
354 /* Traverse tree in postorder. Used to destroy a tree.  */
355 static void
356 objc_postorder_traverse (objc_class_tree *tree,
357                          int level,
358                          void (*function) (objc_class_tree *, int))
359 {
360   struct objc_list *node;
361
362   for (node = tree->subclasses; node; node = node->tail)
363     objc_postorder_traverse (node->head, level + 1, function);
364   (*function) (tree, level);
365 }
366
367 /* Used to print a tree class hierarchy.  */
368 #ifdef DEBUG
369 static void
370 __objc_tree_print (objc_class_tree *tree, int level)
371 {
372   int i;
373
374   for (i = 0; i < level; i++)
375     printf ("  ");
376   printf ("%s\n", tree->class->name);
377 }
378 #endif
379
380 /* Walks on a linked list of methods in the reverse order and executes
381    all the methods corresponding to the `+load' selector.  Walking in
382    the reverse order assures the +load of class is executed first and
383    then +load of categories because of the way in which categories are
384    added to the class methods.  This function needs to be called with
385    the objc_runtime_mutex locked.  */
386 static void
387 __objc_send_load_using_method_list (struct objc_method_list *method_list, Class class)
388 {
389   static SEL load_selector = 0;
390   int i;
391
392   if (!method_list)
393     return;
394
395   /* This needs no lock protection because we are called with the
396      objc_runtime_mutex locked.  */
397   if (!load_selector)
398     load_selector = sel_registerName ("load");
399
400   /* method_list is a linked list of method lists; since we're
401      executing in reverse order, we need to do the next list before we
402      do this one.  */
403   __objc_send_load_using_method_list (method_list->method_next, class);
404
405   /* Search the method list.  */
406   for (i = 0; i < method_list->method_count; i++)
407     {
408       struct objc_method *mth = &method_list->method_list[i];
409
410       /* We are searching for +load methods that we haven't executed
411          yet.  */
412       if (mth->method_name && sel_eq (mth->method_name, load_selector)
413           && ! objc_hash_is_key_in_hash (__objc_load_methods, mth->method_imp))
414         {
415           /* Add this method into the +load hash table, so we won't
416              execute it again next time.  */
417           objc_hash_add (&__objc_load_methods,
418                          mth->method_imp,
419                          mth->method_imp);
420           
421           /* Call +load.  */
422           DEBUG_PRINTF (" begin of [%s +load]\n", class->name);
423           (*mth->method_imp) ((id)class, mth->method_name);
424           DEBUG_PRINTF (" end of [%s +load]\n", class->name);
425
426           break;
427         }
428     }
429 }
430
431 /* This function needs to be called with the objc_runtime_mutex
432    locked.  */
433 static void
434 __objc_send_load (objc_class_tree *tree,
435                   int level __attribute__ ((__unused__)))
436 {
437   Class class = tree->class;
438   struct objc_method_list *method_list = class->class_pointer->methods;
439
440   DEBUG_PRINTF ("+load: need to send load to class '%s'\n", class->name);
441   __objc_send_load_using_method_list (method_list, class);
442 }
443
444 static void
445 __objc_destroy_class_tree_node (objc_class_tree *tree,
446                                 int level __attribute__ ((__unused__)))
447 {
448   objc_free (tree);
449 }
450
451 /* This is used to check if the relationship between two classes
452    before the runtime completely installs the classes.  */
453 static BOOL
454 class_is_subclass_of_class (Class class, Class superclass)
455 {
456   for (; class != Nil;)
457     {
458       if (class == superclass)
459         return YES;
460       class = class_superclass_of_class (class);
461     }
462
463   return NO;
464 }
465
466 /* This list contains all the classes in the runtime system for whom
467    their superclasses are not yet known to the runtime.  */
468 static struct objc_list *unresolved_classes = 0;
469
470 /* Extern function used to reference the Object class.  */
471 extern void __objc_force_linking (void);
472
473 void
474 __objc_force_linking (void)
475 {
476   extern void __objc_linking (void);
477   __objc_linking ();
478 }
479
480 /* Run through the statics list, removing modules as soon as all its
481    statics have been initialized.  */
482 static void
483 objc_init_statics (void)
484 {
485   struct objc_list **cell = &uninitialized_statics;
486   struct objc_static_instances **statics_in_module;
487
488   objc_mutex_lock (__objc_runtime_mutex);
489
490   while (*cell)
491     {
492       int module_initialized = 1;
493
494       for (statics_in_module = (*cell)->head;
495            *statics_in_module; statics_in_module++)
496         {
497           struct objc_static_instances *statics = *statics_in_module;
498           Class class = objc_getClass (statics->class_name);
499
500           if (! class)
501             {
502               /* It is unfortunate that this will cause all the
503                  statics initialization to be done again (eg, if we
504                  already initialized constant strings, and are now
505                  initializing protocols, setting module_initialized to
506                  0 would cause constant strings to be initialized
507                  again).  It would be good to be able to track if we
508                  have already initialized some of them.  */
509               module_initialized = 0;
510             }
511           else
512             {
513               /* Note that if this is a list of Protocol objects, some
514                  of them may have been initialized already (because
515                  they were attached to classes or categories, and the
516                  class/category loading code automatically fixes them
517                  up), and some of them may not.  We really need to go
518                  through the whole list to be sure!  Protocols are
519                  also special because we want to register them and
520                  register all their selectors.  */
521               id *inst;
522
523               if (strcmp (statics->class_name, "Protocol") == 0)
524                 {
525                   /* Protocols are special, because not only we want
526                      to fix up their class pointers, but we also want
527                      to register them and their selectors with the
528                      runtime.  */
529                   for (inst = &statics->instances[0]; *inst; inst++)
530                     __objc_init_protocol ((struct objc_protocol *)*inst);
531                 }
532               else
533                 {
534                   /* Other static instances (typically constant
535                      strings) are easier as we just fix up their class
536                      pointers.  */
537                   for (inst = &statics->instances[0]; *inst; inst++)              
538                     (*inst)->class_pointer = class;
539                 }
540             }
541         }
542       if (module_initialized)
543         {
544           /* Remove this module from the uninitialized list.  */
545           struct objc_list *this = *cell;
546           *cell = this->tail;
547           objc_free (this);
548         }
549       else
550         cell = &(*cell)->tail;
551     }
552
553   objc_mutex_unlock (__objc_runtime_mutex);
554 }
555
556 /* This function is called by constructor functions generated for each
557    module compiled.  (_GLOBAL_$I$...) The purpose of this function is
558    to gather the module pointers so that they may be processed by the
559    initialization routines as soon as possible.  */
560 void
561 __objc_exec_class (struct objc_module *module)
562 {
563   /* Have we processed any constructors previously?  This flag is used
564      to indicate that some global data structures need to be
565      built.  */
566   static BOOL previous_constructors = 0;
567
568   static struct objc_list *unclaimed_categories = 0;
569
570   /* The symbol table (defined in objc-private/module-abi-8.h)
571      generated by gcc.  */
572   struct objc_symtab *symtab = module->symtab;
573
574   /* The statics in this module.  */
575   struct objc_static_instances **statics
576     = symtab->defs[symtab->cls_def_cnt + symtab->cat_def_cnt];
577
578   /* Entry used to traverse hash lists.  */
579   struct objc_list **cell;
580
581   /* The table of selector references for this module.  */
582   struct objc_selector *selectors = symtab->refs;
583
584   int i;
585
586   DEBUG_PRINTF ("\n__objc_exec_class (%p) - start processing module...\n", module);
587
588   /* Check gcc version.  */
589   init_check_module_version (module);
590
591   /* On the first call of this routine, initialize some data
592      structures.  */
593   if (! previous_constructors)
594     {
595         /* Initialize thread-safe system.  */
596       __objc_init_thread_system ();
597       __objc_runtime_threads_alive = 1;
598       __objc_runtime_mutex = objc_mutex_allocate ();
599
600       __objc_init_selector_tables ();
601       __objc_init_class_tables ();
602       __objc_init_dispatch_tables ();
603       duplicate_classes = objc_hash_new (8,
604                                          (hash_func_type)objc_hash_ptr,
605                                          objc_compare_ptrs);
606       __objc_class_tree_list = list_cons (NULL, __objc_class_tree_list);
607       __objc_load_methods = objc_hash_new (128, 
608                                            (hash_func_type)objc_hash_ptr,
609                                            objc_compare_ptrs);
610       __objc_protocols_init ();
611       __objc_accessors_init ();
612       __objc_sync_init ();
613       previous_constructors = 1;
614     }
615
616   /* Save the module pointer so that later we remember to call +load
617      on all classes and categories on it.  */
618   objc_mutex_lock (__objc_runtime_mutex);
619   __objc_module_list = list_cons (module, __objc_module_list);
620
621   /* Replace referenced selectors from names to SELs.  */
622   if (selectors)
623     {
624       DEBUG_PRINTF (" registering selectors\n");
625       __objc_register_selectors_from_module (selectors);
626     }
627
628   /* Parse the classes in the load module and gather selector
629      information.  */
630   for (i = 0; i < symtab->cls_def_cnt; ++i)
631     {
632       Class class = (Class) symtab->defs[i];
633       const char *superclass = (char *) class->super_class;
634
635       /* Make sure we have what we think.  */
636       assert (CLS_ISCLASS (class));
637       assert (CLS_ISMETA (class->class_pointer));
638       DEBUG_PRINTF (" installing class '%s'\n", class->name);
639
640       /* Initialize the subclass list to be NULL.  In some cases it
641          isn't and this crashes the program.  */
642       class->subclass_list = NULL;
643
644       if (__objc_init_class (class))
645         {
646           /* Check to see if the superclass is known in this point. If
647              it's not add the class to the unresolved_classes list.  */
648           if (superclass && ! objc_getClass (superclass))
649             unresolved_classes = list_cons (class, unresolved_classes);
650         }
651     }
652
653   /* Process category information from the module.  */
654   for (i = 0; i < symtab->cat_def_cnt; ++i)
655     {
656       struct objc_category *category = symtab->defs[i + symtab->cls_def_cnt];
657       Class class = objc_getClass (category->class_name);
658       
659       /* If the class for the category exists then append its
660          methods.  */
661       if (class)
662         {
663           DEBUG_PRINTF (" installing category '%s (%s)'\n", category->class_name, category->category_name);
664           /* Do instance methods.  */
665           if (category->instance_methods)
666             class_add_method_list (class, category->instance_methods);
667
668           /* Do class methods.  */
669           if (category->class_methods)
670             class_add_method_list ((Class) class->class_pointer, 
671                                    category->class_methods);
672
673           if (category->protocols)
674             {
675               __objc_init_protocols (category->protocols);
676               __objc_class_add_protocols (class, category->protocols);
677             }
678
679           /* Register the instance methods as class methods, this is
680              only done for root classes.  */
681           __objc_register_instance_methods_to_class (class);
682         }
683       else
684         {
685           DEBUG_PRINTF (" delaying installation of category '%s (%s)'\n", category->class_name, category->category_name);
686           /* The object to which the category methods belong can't be
687              found.  Save the information.  */
688           unclaimed_categories = list_cons (category, unclaimed_categories);
689         }
690     }
691
692   if (statics)
693     uninitialized_statics = list_cons (statics, uninitialized_statics);
694   if (uninitialized_statics)
695     objc_init_statics ();
696
697   /* Scan the unclaimed category hash.  Attempt to attach any
698      unclaimed categories to objects.  */
699   for (cell = &unclaimed_categories; *cell; )
700     {
701       struct objc_category *category = (*cell)->head;
702       Class class = objc_getClass (category->class_name);
703       
704       if (class)
705         {
706           DEBUG_PRINTF (" installing (delayed) category '%s (%s)'\n", category->class_name, category->category_name);
707           list_remove_head (cell);
708           
709           if (category->instance_methods)
710             class_add_method_list (class, category->instance_methods);
711           
712           if (category->class_methods)
713             class_add_method_list ((Class) class->class_pointer,
714                                    category->class_methods);
715
716           if (category->protocols)
717             {
718               __objc_init_protocols (category->protocols);
719               __objc_class_add_protocols (class, category->protocols);
720             }
721
722           /* Register the instance methods as class methods, this is
723              only done for root classes.  */
724           __objc_register_instance_methods_to_class (class);
725         }
726       else
727         cell = &(*cell)->tail;
728     }
729   
730   if (unclaimed_proto_list && objc_getClass ("Protocol"))
731     {
732       list_mapcar (unclaimed_proto_list,
733                    (void (*) (void *))__objc_init_protocols);
734       list_free (unclaimed_proto_list);
735       unclaimed_proto_list = 0;
736     }
737
738   objc_send_load ();
739
740   /* Check if there are no unresolved classes (ie, classes whose
741      superclass has not been loaded yet) and that the 'Object' class,
742      used as the class of classes, exist.  If so, it is worth
743      "resolving the class links" at this point, which will setup all
744      the class/superclass pointers.  */
745   if (!unresolved_classes && objc_getClass ("Object"))
746     {
747       DEBUG_PRINTF (" resolving class links\n");
748       __objc_resolve_class_links ();
749     }
750
751   objc_mutex_unlock (__objc_runtime_mutex);
752
753   DEBUG_PRINTF ("__objc_exec_class (%p) - finished processing module...\n\n", module);
754 }
755
756 /* This function needs to be called with the objc_runtime_mutex
757    locked.  */
758 static void
759 objc_send_load (void)
760 {
761   if (!__objc_module_list)
762     return;
763  
764   /* Try to find out if all the classes loaded so far also have their
765      superclasses known to the runtime.  We suppose that the objects
766      that are allocated in the +load method are in general of a class
767      declared in the same module.  */
768   if (unresolved_classes)
769     {
770       Class class = unresolved_classes->head;
771
772       while (objc_getClass ((char *) class->super_class))
773         {
774           list_remove_head (&unresolved_classes);
775           if (unresolved_classes)
776             class = unresolved_classes->head;
777           else
778             break;
779         }
780
781       /* If we still have classes for whom we don't have yet their
782          super classes known to the runtime we don't send the +load
783          messages (and call the load callback) yet.  */
784       if (unresolved_classes)
785         return;
786     }
787
788   /* Special check.  If 'Object', which is used by meta-classes, has
789      not been loaded yet, delay sending of +load.  */
790   if (! objc_getClass ("Object"))
791     return;
792
793   /* Iterate over all modules in the __objc_module_list and call on
794      them the __objc_create_classes_tree function.  This function
795      creates a tree of classes that resembles the class hierarchy.  */
796   list_mapcar (__objc_module_list,
797                (void (*) (void *)) __objc_create_classes_tree);
798
799   while (__objc_class_tree_list)
800     {
801 #ifdef DEBUG
802       objc_preorder_traverse (__objc_class_tree_list->head,
803                               0, __objc_tree_print);
804 #endif
805       objc_preorder_traverse (__objc_class_tree_list->head,
806                               0, __objc_send_load);
807       objc_postorder_traverse (__objc_class_tree_list->head,
808                               0, __objc_destroy_class_tree_node);
809       list_remove_head (&__objc_class_tree_list);
810     }
811
812   /* For each module, call the _objc_load_callback if any is
813      defined.  */
814   list_mapcar (__objc_module_list, (void (*) (void *)) __objc_call_load_callback);
815
816   /* Empty the list of modules.  */
817   list_free (__objc_module_list);
818   __objc_module_list = NULL;
819 }
820
821 static void
822 __objc_create_classes_tree (struct objc_module *module)
823 {
824   /* The runtime mutex is locked at this point */
825   struct objc_symtab *symtab = module->symtab;
826   int i;
827
828   /* Iterate thru classes defined in this module and insert them in
829      the classes tree hierarchy.  */
830   for (i = 0; i < symtab->cls_def_cnt; i++)
831     {
832       Class class = (Class) symtab->defs[i];
833
834       if (!objc_hash_is_key_in_hash (duplicate_classes, class))
835         objc_tree_insert_class (class);
836     }
837
838   /* Now iterate over "claimed" categories too (ie, categories that
839      extend a class that has already been loaded by the runtime), and
840      insert them in the classes tree hiearchy too.  Otherwise, if you
841      add a category, its +load method would not be called if the class
842      is already loaded in the runtime.  It the category is
843      "unclaimed", ie, we haven't loaded the main class yet, postpone
844      sending +load as we want to execute +load from the class before
845      we execute the one from the category.  */
846   for (i = 0; i < symtab->cat_def_cnt; ++i)
847     {
848       struct objc_category *category = symtab->defs[i + symtab->cls_def_cnt];
849       Class class = objc_getClass (category->class_name);
850       
851       /* If the class for the category exists then append its
852          methods.  */
853       if (class)
854         objc_tree_insert_class (class);
855     }
856 }
857
858 static void
859 __objc_call_load_callback (struct objc_module *module)
860 {
861   if (_objc_load_callback)
862     {
863       /* The runtime mutex is locked at this point.  */
864       struct objc_symtab *symtab = module->symtab;
865       int i;
866       
867       /* Iterate thru classes defined in this module and call the callback
868          for each one.  */
869       for (i = 0; i < symtab->cls_def_cnt; i++)
870         {
871           Class class = (Class) symtab->defs[i];
872         
873           if (!objc_hash_is_key_in_hash (duplicate_classes, class))
874             {
875               /* Call the _objc_load_callback for this class.  */
876               DEBUG_PRINTF (" calling the load callback for class '%s'\n", class->name);
877               _objc_load_callback (class, 0);
878             }
879         }
880       
881       /* Call the _objc_load_callback for categories.  Don't register
882          the instance methods as class methods for categories to root
883          classes since they were already added in the class.  */
884       for (i = 0; i < symtab->cat_def_cnt; i++)
885         {
886           struct objc_category *category = symtab->defs[i + symtab->cls_def_cnt];
887           Class class = objc_getClass (category->class_name);
888           
889           DEBUG_PRINTF (" calling the load callback for category '%s (%s)'\n",
890                         category->class_name, category->category_name);
891           _objc_load_callback (class, category);
892         }
893     }
894 }
895
896 /* Sanity check the version of gcc used to compile `module'.  */
897 static void
898 init_check_module_version (struct objc_module *module)
899 {
900   if ((module->version != OBJC_VERSION) || (module->size != sizeof (struct objc_module)))
901     {
902       _objc_abort ("Module %s version %d doesn't match runtime %d\n",
903                    module->name, (int)module->version, OBJC_VERSION);
904     }
905 }
906
907 /* __objc_init_class must be called with __objc_runtime_mutex already
908    locked.  Return YES if the class could be setup; return NO if the
909    class could not be setup because a class with the same name already
910    exists.  */
911 BOOL
912 __objc_init_class (Class class)
913 {
914   /* Store the class in the class table and assign class numbers.  */
915   if (__objc_add_class_to_hash (class))
916     {
917       /* Register all of the selectors in the class and meta class.  */
918       __objc_register_selectors_from_class (class);
919       __objc_register_selectors_from_class ((Class) class->class_pointer);
920       
921       /* Install the fake dispatch tables.  */
922       __objc_install_premature_dtable (class);
923       __objc_install_premature_dtable (class->class_pointer);
924       
925       /* Register the instance methods as class methods, this is only
926          done for root classes.  */
927       __objc_register_instance_methods_to_class (class);
928       
929       if (class->protocols)
930         __objc_init_protocols (class->protocols);
931
932       return YES;
933     }
934   else
935     {
936       /* The module contains a duplicate class.  Remember it so that
937          we will ignore it later.  */
938       DEBUG_PRINTF (" duplicate class '%s' - will be ignored\n", class->name);
939       objc_hash_add (&duplicate_classes, class, class);
940       return NO;
941     }
942 }
943
944 /* __objc_init_protocol must be called with __objc_runtime_mutex
945    already locked, and the "Protocol" class already registered.  */
946 static void
947 __objc_init_protocol (struct objc_protocol *protocol)
948 {
949   static Class proto_class = 0;
950
951   if (! proto_class)
952     proto_class = objc_getClass ("Protocol");
953
954   if (((size_t)protocol->class_pointer) == PROTOCOL_VERSION)
955     {
956       /* Assign class pointer.  */
957       protocol->class_pointer = proto_class;
958       
959       /* Register all the selectors in the protocol with the runtime.
960          This both registers the selectors with the right types, and
961          it also fixes up the 'struct objc_method' structures inside
962          the protocol so that each method_name (a char * as compiled
963          by the compiler) is replaced with the appropriate runtime
964          SEL.  */
965       if (protocol->class_methods)
966         __objc_register_selectors_from_description_list (protocol->class_methods);
967
968       if (protocol->instance_methods)
969         __objc_register_selectors_from_description_list (protocol->instance_methods);
970
971       /* Register the protocol in the hashtable or protocols by
972          name.  */
973       __objc_protocols_add_protocol (protocol->protocol_name, protocol);
974       
975       /* Init super protocols.  */
976       __objc_init_protocols (protocol->protocol_list);
977     }
978   else if (protocol->class_pointer != proto_class)
979     {
980       _objc_abort ("Version %d doesn't match runtime protocol version %d\n",
981                    (int) ((char *) protocol->class_pointer
982                           - (char *) 0),
983                    PROTOCOL_VERSION);
984     }
985 }
986
987 static void
988 __objc_init_protocols (struct objc_protocol_list *protos)
989 {
990   size_t i;
991   static Class proto_class = 0;
992
993   if (! protos)
994     return;
995
996   objc_mutex_lock (__objc_runtime_mutex);
997
998   if (! proto_class)
999     proto_class = objc_getClass ("Protocol");
1000
1001   if (! proto_class)
1002     {
1003       unclaimed_proto_list = list_cons (protos, unclaimed_proto_list);
1004       objc_mutex_unlock (__objc_runtime_mutex);
1005       return;
1006     }
1007
1008 #if 0
1009   assert (protos->next == 0); /* Only single ones allowed.  */
1010 #endif
1011
1012   for (i = 0; i < protos->count; i++)
1013     {
1014       struct objc_protocol *aProto = protos->list[i];
1015       __objc_init_protocol (aProto);
1016     }
1017
1018   objc_mutex_unlock (__objc_runtime_mutex);
1019 }
1020
1021 static void
1022 __objc_class_add_protocols (Class class, struct objc_protocol_list *protos)
1023 {
1024   if (! protos)
1025     return;
1026
1027   protos->next = class->protocols;
1028   class->protocols = protos;
1029 }