sendmsg.c 37.5 KB
Newer Older
1
/* GNU Objective C Runtime message lookup 
Jakub Jelinek committed
2
   Copyright (C) 1993-2015 Free Software Foundation, Inc.
3 4
   Contributed by Kresten Krab Thorup

5
This file is part of GCC.
6

7
GCC is free software; you can redistribute it and/or modify it under the
8
terms of the GNU General Public License as published by the Free Software
9
Foundation; either version 3, or (at your option) any later version.
10

11
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 13 14 15
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
details.

16 17 18 19 20 21 22 23
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.

You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
<http://www.gnu.org/licenses/>.  */
24

25 26 27
/* Uncommented the following line to enable debug logging.  Use this
   only while debugging the runtime.  */
/* #define DEBUG 1 */
28

Andrew Pinski committed
29 30
/* FIXME: This should be using libffi instead of __builtin_apply
   and friends.  */
31

Nicola Pero committed
32
#include "objc-private/common.h"
Nicola Pero committed
33
#include "objc-private/error.h"
Ben Elliston committed
34
#include "tconfig.h"
35
#include "coretypes.h"
36
#include "objc/runtime.h"
37
#include "objc/message.h"          /* For objc_msg_lookup(), objc_msg_lookup_super().  */
Nicola Pero committed
38
#include "objc/thr.h"
39
#include "objc-private/module-abi-8.h"
Nicola Pero committed
40
#include "objc-private/runtime.h"
41
#include "objc-private/hash.h"
Nicola Pero committed
42
#include "objc-private/sarray.h"
43
#include "objc-private/selector.h" /* For sel_is_mapped() */
44
#include "runtime-info.h"
Nicola Pero committed
45
#include <assert.h> /* For assert */
Nicola Pero committed
46
#include <string.h> /* For strlen */
47 48 49

#define INVISIBLE_STRUCT_RETURN 1

50 51 52
/* The uninstalled dispatch table.  If a class' dispatch table points
   to __objc_uninstalled_dtable then that means it needs its dispatch
   table to be installed.  */
53
struct sarray *__objc_uninstalled_dtable = 0;   /* !T:MUTEX */
54

55 56 57 58 59
/* Two hooks for method forwarding. If either is set, it is invoked to
 * return a function that performs the real forwarding.  If both are
 * set, the result of __objc_msg_forward2 will be preferred over that
 * of __objc_msg_forward.  If both return NULL or are unset, the
 * libgcc based functions (__builtin_apply and friends) are used.  */
60
IMP (*__objc_msg_forward) (SEL) = NULL;
61
IMP (*__objc_msg_forward2) (id, SEL) = NULL;
62

63
/* Send +initialize to class.  */
64
static void __objc_send_initialize (Class);
65

66 67 68 69
/* Forward declare some functions */
static void __objc_install_dtable_for_class (Class cls);
static void __objc_prepare_dtable_for_class (Class cls);
static void __objc_install_prepared_dtable_for_class (Class cls);
70

71 72 73
static struct sarray *__objc_prepared_dtable_for_class (Class cls);
static IMP __objc_get_prepared_imp (Class cls,SEL sel);
  
74 75 76 77 78

/* Various forwarding functions that are used based upon the
   return type for the selector.
   __objc_block_forward for structures.
   __objc_double_forward for floats/doubles.
79
   __objc_word_forward for pointers or types that fit in registers.  */
80 81
static double __objc_double_forward (id, SEL, ...);
static id __objc_word_forward (id, SEL, ...);
82 83 84 85 86 87
typedef struct { id many[8]; } __big;
#if INVISIBLE_STRUCT_RETURN 
static __big 
#else
static id
#endif
88
__objc_block_forward (id, SEL, ...);
89 90
static struct objc_method * search_for_method_in_hierarchy (Class class, SEL sel);
struct objc_method * search_for_method_in_list (struct objc_method_list * list, SEL op);
91
id nil_method (id, SEL);
92

93 94 95 96
/* Make sure this inline function is exported regardless of GNU89 or C99
   inlining semantics as it is part of the libobjc ABI.  */
extern IMP __objc_get_forward_imp (id, SEL);

97
/* Given a selector, return the proper forwarding implementation.  */
Andrew Pinski committed
98
inline
99
IMP
100
__objc_get_forward_imp (id rcv, SEL sel)
101
{
102 103 104 105
  /* If a custom forwarding hook was registered, try getting a
     forwarding function from it. There are two forward routine hooks,
     one that takes the receiver as an argument and one that does
     not.  */
106 107 108 109 110 111
  if (__objc_msg_forward2)
    {
      IMP result;
      if ((result = __objc_msg_forward2 (rcv, sel)) != NULL)
       return result;
    }
112 113 114
  if (__objc_msg_forward)
    {
      IMP result;
115
      if ((result = __objc_msg_forward (sel)) != NULL) 
116
	return result;
117
    }
118

119 120
  /* In all other cases, use the default forwarding functions built
     using __builtin_apply and friends.  */
121 122
    {
      const char *t = sel->sel_types;
123
      
124 125 126 127 128 129 130 131 132 133 134 135
      if (t && (*t == '[' || *t == '(' || *t == '{')
#ifdef OBJC_MAX_STRUCT_BY_VALUE
          && objc_sizeof_type (t) > OBJC_MAX_STRUCT_BY_VALUE
#endif
          )
        return (IMP)__objc_block_forward;
      else if (t && (*t == 'f' || *t == 'd'))
        return (IMP)__objc_double_forward;
      else
        return (IMP)__objc_word_forward;
    }
}
136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
/* Selectors for +resolveClassMethod: and +resolveInstanceMethod:.
   These are set up at startup.  */
static SEL selector_resolveClassMethod = NULL;
static SEL selector_resolveInstanceMethod = NULL;

/* Internal routines use to resolve a class method using
   +resolveClassMethod:.  'class' is always a non-Nil class (*not* a
   meta-class), and 'sel' is the selector that we are trying to
   resolve.  This must be called when class is not Nil, and the
   dispatch table for class methods has already been installed.

   This routine tries to call +resolveClassMethod: to give an
   opportunity to resolve the method.  If +resolveClassMethod: returns
   YES, it tries looking up the method again, and if found, it returns
   it.  Else, it returns NULL.  */
static inline
IMP
__objc_resolve_class_method (Class class, SEL sel)
{
  /* We need to lookup +resolveClassMethod:.  */
  BOOL (*resolveMethodIMP) (id, SEL, SEL);

  /* The dispatch table for class methods is already installed and we
     don't want any forwarding to happen when looking up this method,
     so we just look it up directly.  Note that if 'sel' is precisely
     +resolveClassMethod:, this would look it up yet again and find
     nothing.  That's no problem and there's no recursion.  */
  resolveMethodIMP = (BOOL (*) (id, SEL, SEL))sarray_get_safe
    (class->class_pointer->dtable, (size_t) selector_resolveClassMethod->sel_id);

  if (resolveMethodIMP && resolveMethodIMP ((id)class, selector_resolveClassMethod, sel))
    {
      /* +resolveClassMethod: returned YES.  Look the method up again.
	 We already know the dtable is installed.  */
      
      /* TODO: There is the case where +resolveClassMethod: is buggy
	 and returned YES without actually adding the method.  We
	 could maybe print an error message.  */
      return sarray_get_safe (class->class_pointer->dtable, (size_t) sel->sel_id);
    }

  return NULL;
}

/* Internal routines use to resolve a instance method using
   +resolveInstanceMethod:.  'class' is always a non-Nil class, and
   'sel' is the selector that we are trying to resolve.  This must be
   called when class is not Nil, and the dispatch table for instance
   methods has already been installed.

   This routine tries to call +resolveInstanceMethod: to give an
   opportunity to resolve the method.  If +resolveInstanceMethod:
   returns YES, it tries looking up the method again, and if found, it
   returns it.  Else, it returns NULL.  */
static inline
IMP
__objc_resolve_instance_method (Class class, SEL sel)
{
  /* We need to lookup +resolveInstanceMethod:.  */
  BOOL (*resolveMethodIMP) (id, SEL, SEL);

  /* The dispatch table for class methods may not be already installed
     so we have to install it if needed.  */
  resolveMethodIMP = sarray_get_safe (class->class_pointer->dtable,
				      (size_t) selector_resolveInstanceMethod->sel_id);
  if (resolveMethodIMP == 0)
    {
      /* Try again after installing the dtable.  */
      if (class->class_pointer->dtable == __objc_uninstalled_dtable)
	{
	  objc_mutex_lock (__objc_runtime_mutex);
	  if (class->class_pointer->dtable == __objc_uninstalled_dtable)
209
	    __objc_install_dtable_for_class (class->class_pointer);
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	  objc_mutex_unlock (__objc_runtime_mutex);
	}
      resolveMethodIMP = sarray_get_safe (class->class_pointer->dtable,
					  (size_t) selector_resolveInstanceMethod->sel_id);	      
    }

  if (resolveMethodIMP && resolveMethodIMP ((id)class, selector_resolveInstanceMethod, sel))
    {
      /* +resolveInstanceMethod: returned YES.  Look the method up
	 again.  We already know the dtable is installed.  */
      
      /* TODO: There is the case where +resolveInstanceMethod: is
	 buggy and returned YES without actually adding the method.
	 We could maybe print an error message.  */
      return sarray_get_safe (class->dtable, (size_t) sel->sel_id);	
    }

  return NULL;
}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
/* Given a CLASS and selector, return the implementation corresponding
   to the method of the selector.

   If CLASS is a class, the instance method is returned.
   If CLASS is a meta class, the class method is returned.

   Since this requires the dispatch table to be installed, this function
   will implicitly invoke +initialize for CLASS if it hasn't been
   invoked yet.  This also insures that +initialize has been invoked
   when the returned implementation is called directly.

   The forwarding hooks require the receiver as an argument (if they are to
   perform dynamic lookup in proxy objects etc), so this function has a
   receiver argument to be used with those hooks.  */
static inline
IMP
get_implementation (id receiver, Class class, SEL sel)
{
  void *res;

  if (class->dtable == __objc_uninstalled_dtable)
    {
      /* The dispatch table needs to be installed.  */
      objc_mutex_lock (__objc_runtime_mutex);

      /* Double-checked locking pattern: Check
	 __objc_uninstalled_dtable again in case another thread
257 258
	 installed the dtable while we were waiting for the lock to be
	 released.  */
259
      if (class->dtable == __objc_uninstalled_dtable)
260
	__objc_install_dtable_for_class (class);
261

262 263 264 265
      /* If the dispatch table is not yet installed, we are still in
	 the process of executing +initialize.  But the implementation
	 pointer should be available in the prepared ispatch table if
	 it exists at all.  */
266 267 268 269 270 271
      if (class->dtable == __objc_uninstalled_dtable)
	{
	  assert (__objc_prepared_dtable_for_class (class) != 0);
	  res = __objc_get_prepared_imp (class, sel);
	}
      else
272 273
	res = 0;

274
      objc_mutex_unlock (__objc_runtime_mutex);
275 276
      /* Call ourselves with the installed dispatch table and get the
	 real method.  */
277 278 279 280 281 282 283 284 285
      if (!res)
	res = get_implementation (receiver, class, sel);
    }
  else
    {
      /* The dispatch table has been installed.  */
      res = sarray_get_safe (class->dtable, (size_t) sel->sel_id);
      if (res == 0)
	{
286 287 288
	  /* The dispatch table has been installed, and the method is
	     not in the dispatch table.  So the method just doesn't
	     exist for the class.  */
289 290 291 292 293 294 295

	  /* Try going through the +resolveClassMethod: or
	     +resolveInstanceMethod: process.  */
	  if (CLS_ISMETA (class))
	    {
	      /* We have the meta class, but we need to invoke the
		 +resolveClassMethod: method on the class.  So, we
296 297 298
		 need to obtain the class from the meta class, which
		 we do using the fact that both the class and the
		 meta-class have the same name.  */
299 300 301 302 303 304 305 306
	      Class realClass = objc_lookUpClass (class->name);
	      if (realClass)
		res = __objc_resolve_class_method (realClass, sel);
	    }
	  else
	    res = __objc_resolve_instance_method (class, sel);

	  if (res == 0)
307
	    res = __objc_get_forward_imp (receiver, sel);
308 309 310 311 312
	}
    }
  return res;
}

313 314 315 316
/* Make sure this inline function is exported regardless of GNU89 or C99
   inlining semantics as it is part of the libobjc ABI.  */
extern IMP get_imp (Class, SEL);

317
inline
318 319 320
IMP
get_imp (Class class, SEL sel)
{
321 322 323 324 325 326 327 328
  /* In a vanilla implementation we would first check if the dispatch
     table is installed.  Here instead, to get more speed in the
     standard case (that the dispatch table is installed) we first try
     to get the imp using brute force.  Only if that fails, we do what
     we should have been doing from the very beginning, that is, check
     if the dispatch table needs to be installed, install it if it's
     not installed, and retrieve the imp from the table if it's
     installed.  */
329
  void *res = sarray_get_safe (class->dtable, (size_t) sel->sel_id);
330 331
  if (res == 0)
    {
332
      res = get_implementation(nil, class, sel);
333 334 335 336
    }
  return res;
}

337 338 339 340 341 342 343 344 345 346 347
/* The new name of get_imp().  */
IMP
class_getMethodImplementation (Class class_, SEL selector)
{
  if (class_ == Nil  ||  selector == NULL)
    return NULL;

  /* get_imp is inlined, so we're good.  */
  return get_imp (class_, selector);
}

348 349
/* Given a method, return its implementation.  This has been replaced
   by method_getImplementation() in the modern API.  */
350
IMP
351
method_get_imp (struct objc_method * method)
352
{
353
  return (method != (struct objc_method *)0) ? method->method_imp : (IMP)0;
354 355
}

356
/* Query if an object can respond to a selector, returns YES if the
357
   object implements the selector otherwise NO.  Does not check if the
358 359 360
   method can be forwarded.  Since this requires the dispatch table to
   installed, this function will implicitly invoke +initialize for the
   class of OBJECT if it hasn't been invoked yet.  */
Andrew Pinski committed
361
inline
362 363 364
BOOL
__objc_responds_to (id object, SEL sel)
{
365
  void *res;
366
  struct sarray *dtable;
367

368 369 370
  /* Install dispatch table if need be */
  dtable = object->class_pointer->dtable;
  if (dtable == __objc_uninstalled_dtable)
371
    {
372
      objc_mutex_lock (__objc_runtime_mutex);
373
      if (object->class_pointer->dtable == __objc_uninstalled_dtable)
374 375
        __objc_install_dtable_for_class (object->class_pointer);

376 377 378
      /* If the dispatch table is not yet installed, we are still in
         the process of executing +initialize.  Yet the dispatch table
         should be available.  */
379 380 381 382 383 384 385 386
      if (object->class_pointer->dtable == __objc_uninstalled_dtable)
        {
          dtable = __objc_prepared_dtable_for_class (object->class_pointer);
          assert (dtable);
        }
      else
        dtable = object->class_pointer->dtable;

387
      objc_mutex_unlock (__objc_runtime_mutex);
388 389
    }

390
  /* Get the method from the dispatch table.  */
391 392
  res = sarray_get_safe (dtable, (size_t) sel->sel_id);
  return (res != 0) ? YES : NO;
393 394
}

395 396 397
BOOL
class_respondsToSelector (Class class_, SEL selector)
{
398
  struct sarray *dtable;
399 400 401 402 403
  void *res;

  if (class_ == Nil  ||  selector == NULL)
    return NO;

404
  /* Install dispatch table if need be.  */
405 406
  dtable = class_->dtable;
  if (dtable == __objc_uninstalled_dtable)
407 408 409
    {
      objc_mutex_lock (__objc_runtime_mutex);
      if (class_->dtable == __objc_uninstalled_dtable)
410 411
	__objc_install_dtable_for_class (class_);

412 413 414 415 416 417 418 419 420 421
      /* If the dispatch table is not yet installed,
         we are still in the process of executing +initialize.
         Yet the dispatch table should be available.  */
      if (class_->dtable == __objc_uninstalled_dtable)
        {
          dtable = __objc_prepared_dtable_for_class (class_);
          assert (dtable);
        }
      else
        dtable = class_->dtable;
422

423 424 425
      objc_mutex_unlock (__objc_runtime_mutex);
    }

426
  /* Get the method from the dispatch table.  */
427 428
  res = sarray_get_safe (dtable, (size_t) selector->sel_id);
  return (res != 0) ? YES : NO;
429 430
}

431
/* This is the lookup function.  All entries in the table are either a
432
   valid method *or* zero.  If zero then either the dispatch table
433 434
   needs to be installed or it doesn't exist and forwarding is
   attempted.  */
435
IMP
436
objc_msg_lookup (id receiver, SEL op)
437 438
{
  IMP result;
439
  if (receiver)
440
    {
441
      /* First try a quick lookup assuming the dispatch table exists.  */
442 443 444 445
      result = sarray_get_safe (receiver->class_pointer->dtable, 
				(sidx)op->sel_id);
      if (result == 0)
	{
446 447 448 449
	  /* Not found ... call get_implementation () to install the
             dispatch table and call +initialize as required,
             providing the method implementation or a forwarding
             function.  */
450
	  result = get_implementation (receiver, receiver->class_pointer, op);
451 452 453 454
	}
      return result;
    }
  else
455
    return (IMP)nil_method;
456 457 458
}

IMP
459
objc_msg_lookup_super (struct objc_super *super, SEL sel)
460 461
{
  if (super->self)
462
    return get_imp (super->super_class, sel);
463
  else
464
    return (IMP)nil_method;
465 466 467
}

void
468
__objc_init_dispatch_tables ()
469
{
470
  __objc_uninstalled_dtable = sarray_new (200, 0);
471 472

  /* TODO: It would be cool to register typed selectors here.  */
473
  selector_resolveClassMethod = sel_registerName ("resolveClassMethod:");
474
  selector_resolveInstanceMethod = sel_registerName ("resolveInstanceMethod:");
475 476 477 478
}


/* Install dummy table for class which causes the first message to
479
   that class (or instances hereof) to be initialized properly.  */
480
void
481
__objc_install_premature_dtable (Class class)
482
{
483
  assert (__objc_uninstalled_dtable);
484 485 486
  class->dtable = __objc_uninstalled_dtable;
}   

487
/* Send +initialize to class if not already done.  */
488
static void
489
__objc_send_initialize (Class class)
490
{
491
  /* This *must* be a class object.  */
492 493
  assert (CLS_ISCLASS (class));
  assert (! CLS_ISMETA (class));
494

495 496 497
  /* class_add_method_list/__objc_update_dispatch_table_for_class may
     have reset the dispatch table.  The canonical way to insure that
     we send +initialize just once, is this flag.  */
498
  if (! CLS_ISINITIALIZED (class))
499
    {
500
      DEBUG_PRINTF ("+initialize: need to initialize class '%s'\n", class->name);
501 502
      CLS_SETINITIALIZED (class);
      CLS_SETINITIALIZED (class->class_pointer);
503

504
      /* Create the garbage collector type memory description.  */
505 506
      __objc_generate_gc_type_description (class);

507 508
      if (class->super_class)
	__objc_send_initialize (class->super_class);
509 510

      {
511
	SEL op = sel_registerName ("initialize");
512 513 514 515
        struct objc_method *method = search_for_method_in_hierarchy (class->class_pointer, 
								     op);

	if (method)
516 517
	  {
	    DEBUG_PRINTF (" begin of [%s +initialize]\n", class->name);
518
	    (*method->method_imp) ((id)class, op);
519 520 521 522 523 524 525 526
	    DEBUG_PRINTF (" end of [%s +initialize]\n", class->name);
	  }
#ifdef DEBUG
	else
	  {
	    DEBUG_PRINTF (" class '%s' has no +initialize method\n", class->name);	    
	  }
#endif
527 528 529 530
      }
    }
}

531 532 533 534 535 536 537
/* Walk on the methods list of class and install the methods in the
   reverse order of the lists.  Since methods added by categories are
   before the methods of class in the methods list, this allows
   categories to substitute methods declared in class.  However if
   more than one category replaces the same method nothing is
   guaranteed about what method will be used.  Assumes that
   __objc_runtime_mutex is locked down.  */
538
static void
539
__objc_install_methods_in_dtable (struct sarray *dtable, struct objc_method_list * method_list)
540 541
{
  int i;
542
  
543
  if (! method_list)
544
    return;
545
  
546
  if (method_list->method_next)
547
    __objc_install_methods_in_dtable (dtable, method_list->method_next);
548
  
549 550
  for (i = 0; i < method_list->method_count; i++)
    {
551
      struct objc_method * method = &(method_list->method_list[i]);
552
      sarray_at_put_safe (dtable,
553 554 555 556 557 558 559 560 561 562 563
			  (sidx) method->method_name->sel_id,
			  method->method_imp);
    }
}

void
__objc_update_dispatch_table_for_class (Class class)
{
  Class next;
  struct sarray *arr;

564
  DEBUG_PRINTF (" _objc_update_dtable_for_class (%s)\n", class->name);
565

566
  objc_mutex_lock (__objc_runtime_mutex);
567

568
  /* Not yet installed -- skip it unless in +initialize.  */
569 570 571 572 573
  if (class->dtable == __objc_uninstalled_dtable) 
    {
      if (__objc_prepared_dtable_for_class (class))
	{
	  /* There is a prepared table so we must be initialising this
574
	     class ... we must re-do the table preparation.  */
575 576 577 578 579 580
	  __objc_prepare_dtable_for_class (class);
	}
      objc_mutex_unlock (__objc_runtime_mutex);
      return;
    }

581 582 583
  arr = class->dtable;
  __objc_install_premature_dtable (class); /* someone might require it... */
  sarray_free (arr);			   /* release memory */
584 585
  
  /* Could have been lazy...  */
586
  __objc_install_dtable_for_class (class); 
587

588
  if (class->subclass_list)	/* Traverse subclasses.  */
589 590 591
    for (next = class->subclass_list; next; next = next->sibling_class)
      __objc_update_dispatch_table_for_class (next);

592
  objc_mutex_unlock (__objc_runtime_mutex);
593 594 595 596 597 598 599 600
}

/* This function adds a method list to a class.  This function is
   typically called by another function specific to the run-time.  As
   such this function does not worry about thread safe issues.

   This one is only called for categories. Class objects have their
   methods installed right away, and their selectors are made into
601
   SEL's by the function __objc_register_selectors_from_class.  */
602
void
603
class_add_method_list (Class class, struct objc_method_list * list)
604 605
{
  /* Passing of a linked list is not allowed.  Do multiple calls.  */
606
  assert (! list->method_next);
607

Andrew Pinski committed
608
  __objc_register_selectors_from_list(list);
609 610 611 612 613

  /* Add the methods to the class's method list.  */
  list->method_next = class->methods;
  class->methods = list;

614
  /* Update the dispatch table of class.  */
615 616 617
  __objc_update_dispatch_table_for_class (class);
}

618 619 620
struct objc_method *
class_getInstanceMethod (Class class_, SEL selector)
{
621 622
  struct objc_method *m;

623 624 625
  if (class_ == Nil  ||  selector == NULL)
    return NULL;

626 627 628 629
  m = search_for_method_in_hierarchy (class_, selector);
  if (m)
    return m;

630 631
  /* Try going through +resolveInstanceMethod:, and do the search
     again if successful.  */
632 633 634 635
  if (__objc_resolve_instance_method (class_, selector))
    return search_for_method_in_hierarchy (class_, selector);

  return NULL;
636 637 638 639 640
}

struct objc_method *
class_getClassMethod (Class class_, SEL selector)
{
641 642
  struct objc_method *m;

643 644 645
  if (class_ == Nil  ||  selector == NULL)
    return NULL;
  
646 647 648 649 650 651 652 653 654 655 656 657
  m = search_for_method_in_hierarchy (class_->class_pointer, 
				      selector);
  if (m)
    return m;

  /* Try going through +resolveClassMethod:, and do the search again
     if successful.  */
  if (__objc_resolve_class_method (class_, selector))
    return search_for_method_in_hierarchy (class_->class_pointer, 
					   selector);    

  return NULL;
658
}
659

660 661 662 663 664 665 666 667 668 669 670 671
BOOL
class_addMethod (Class class_, SEL selector, IMP implementation,
		 const char *method_types)
{
  struct objc_method_list *method_list;
  struct objc_method *method;
  const char *method_name;

  if (class_ == Nil  ||  selector == NULL  ||  implementation == NULL  
      || method_types == NULL  || (strcmp (method_types, "") == 0))
    return NO;

672
  method_name = sel_getName (selector);
673 674 675
  if (method_name == NULL)
    return NO;

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
  /* If the method already exists in the class, return NO.  It is fine
     if the method already exists in the superclass; in that case, we
     are overriding it.  */
  if (CLS_IS_IN_CONSTRUCTION (class_))
    {
      /* The class only contains a list of methods; they have not been
	 registered yet, ie, the method_name of each of them is still
	 a string, not a selector.  Iterate manually over them to
	 check if we have already added the method.  */
      struct objc_method_list * method_list = class_->methods;
      while (method_list)
	{
	  int i;
	  
	  /* Search the method list.  */
	  for (i = 0; i < method_list->method_count; ++i)
	    {
	      struct objc_method * method = &method_list->method_list[i];
	      
	      if (method->method_name
		  && strcmp ((char *)method->method_name, method_name) == 0)
		return NO;
	    }
	  
	  /* The method wasn't found.  Follow the link to the next list of
	     methods.  */
	  method_list = method_list->method_next;
	}
      /* The method wasn't found.  It's a new one.  Go ahead and add
	 it.  */
    }
  else
    {
      /* Do the standard lookup.  This assumes the selectors are
	 mapped.  */
      if (search_for_method_in_list (class_->methods, selector))
	return NO;
    }

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
  method_list = (struct objc_method_list *)objc_calloc (1, sizeof (struct objc_method_list));
  method_list->method_count = 1;

  method = &(method_list->method_list[0]);
  method->method_name = objc_malloc (strlen (method_name) + 1);
  strcpy ((char *)method->method_name, method_name);

  method->method_types = objc_malloc (strlen (method_types) + 1);
  strcpy ((char *)method->method_types, method_types);
  
  method->method_imp = implementation;
  
  if (CLS_IS_IN_CONSTRUCTION (class_))
    {
      /* We only need to add the method to the list.  It will be
	 registered with the runtime when the class pair is registered
	 (if ever).  */
      method_list->method_next = class_->methods;
      class_->methods = method_list;
    }
  else
    {
      /* Add the method to a live class.  */
      objc_mutex_lock (__objc_runtime_mutex);
      class_add_method_list (class_, method_list);
      objc_mutex_unlock (__objc_runtime_mutex);
    }

  return YES;
}

IMP
class_replaceMethod (Class class_, SEL selector, IMP implementation,
		     const char *method_types)
{
  struct objc_method * method;

  if (class_ == Nil  ||  selector == NULL  ||  implementation == NULL
      || method_types == NULL)
    return NULL;

  method = search_for_method_in_hierarchy (class_, selector);

  if (method)
    {
      return method_setImplementation (method, implementation);
    }
  else
    {
      class_addMethod (class_, selector, implementation, method_types);
      return NULL;
    }
}

769 770 771
/* Search for a method starting from the current class up its
   hierarchy.  Return a pointer to the method's method structure if
   found.  NULL otherwise.  */
772
static struct objc_method *
773 774
search_for_method_in_hierarchy (Class cls, SEL sel)
{
775
  struct objc_method * method = NULL;
776 777 778 779 780
  Class class;

  if (! sel_is_mapped (sel))
    return NULL;

781 782
  /* Scan the method list of the class.  If the method isn't found in
     the list then step to its super class.  */
783 784 785 786 787 788 789 790
  for (class = cls; ((! method) && class); class = class->super_class)
    method = search_for_method_in_list (class->methods, sel);

  return method;
}



791 792 793
/* Given a linked list of method and a method's name.  Search for the
   named method's method structure.  Return a pointer to the method's
   method structure if found.  NULL otherwise.  */  
794 795
struct objc_method *
search_for_method_in_list (struct objc_method_list * list, SEL op)
796
{
797
  struct objc_method_list * method_list = list;
798 799 800 801 802 803 804 805 806 807 808 809

  if (! sel_is_mapped (op))
    return NULL;

  /* If not found then we'll search the list.  */
  while (method_list)
    {
      int i;

      /* Search the method list.  */
      for (i = 0; i < method_list->method_count; ++i)
        {
810
          struct objc_method * method = &method_list->method_list[i];
811 812 813 814 815 816 817 818 819 820 821 822 823 824

          if (method->method_name)
            if (method->method_name->sel_id == op->sel_id)
              return method;
        }

      /* The method wasn't found.  Follow the link to the next list of
         methods.  */
      method_list = method_list->method_next;
    }

  return NULL;
}

825 826 827
typedef void * retval_t;
typedef void * arglist_t;

828 829
static retval_t __objc_forward (id object, SEL sel, arglist_t args);

830
/* Forwarding pointers/integers through the normal registers.  */
831 832 833 834 835 836 837 838 839 840 841 842 843 844
static id
__objc_word_forward (id rcv, SEL op, ...)
{
  void *args, *res;

  args = __builtin_apply_args ();
  res = __objc_forward (rcv, op, args);
  if (res)
    __builtin_return (res);
  else
    return res;
}

/* Specific routine for forwarding floats/double because of
845 846 847 848
   architectural differences on some processors.  i386s for example
   which uses a floating point stack versus general registers for
   floating point numbers.  This forward routine makes sure that GCC
   restores the proper return values.  */
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
static double
__objc_double_forward (id rcv, SEL op, ...)
{
  void *args, *res;

  args = __builtin_apply_args ();
  res = __objc_forward (rcv, op, args);
  __builtin_return (res);
}

#if INVISIBLE_STRUCT_RETURN
static __big
#else
static id
#endif
__objc_block_forward (id rcv, SEL op, ...)
{
  void *args, *res;

  args = __builtin_apply_args ();
  res = __objc_forward (rcv, op, args);
  if (res)
    __builtin_return (res);
  else
#if INVISIBLE_STRUCT_RETURN
    return (__big) {{0, 0, 0, 0, 0, 0, 0, 0}};
#else
    return nil;
#endif
}


881 882 883 884 885 886
/* This function is called for methods which are not implemented,
   unless a custom forwarding routine has been installed.  Please note
   that most serious users of libobjc (eg, GNUstep base) do install
   their own forwarding routines, and hence this is never actually
   used.  But, if no custom forwarding routine is installed, this is
   called when a selector is not recognized.  */
887 888 889 890 891 892 893
static retval_t
__objc_forward (id object, SEL sel, arglist_t args)
{
  IMP imp;
  static SEL frwd_sel = 0;                      /* !T:SAFE2 */
  SEL err_sel;

894
  /* First try if the object understands forward::.  */
895 896
  if (! frwd_sel)
    frwd_sel = sel_get_any_uid ("forward::");
897 898 899

  if (__objc_responds_to (object, frwd_sel))
    {
900
      imp = get_implementation (object, object->class_pointer, frwd_sel);
901
      return (*imp) (object, frwd_sel, sel, args);
902 903
    }

904 905
  /* If the object recognizes the doesNotRecognize: method then we're
     going to send it.  */
906 907 908
  err_sel = sel_get_any_uid ("doesNotRecognize:");
  if (__objc_responds_to (object, err_sel))
    {
909
      imp = get_implementation (object, object->class_pointer, err_sel);
910 911 912 913
      return (*imp) (object, err_sel, sel);
    }
  
  /* The object doesn't recognize the method.  Check for responding to
914
     error:.  If it does then sent it.  */
915
  {
916
    char msg[256 + strlen ((const char *) sel_getName (sel))
917
             + strlen ((const char *) object->class_pointer->name)];
918 919

    sprintf (msg, "(%s) %s does not recognize %s",
920
	     (CLS_ISMETA (object->class_pointer)
921 922
	      ? "class"
	      : "instance" ),
923
             object->class_pointer->name, sel_getName (sel));
924

925 926
    /* The object doesn't respond to doesNotRecognize:.  Therefore, a
       default action is taken.  */
Nicola Pero committed
927
    _objc_abort ("%s\n", msg);
928 929 930 931 932 933

    return 0;
  }
}

void
934
__objc_print_dtable_stats (void)
935 936 937
{
  int total = 0;

938
  objc_mutex_lock (__objc_runtime_mutex);
939 940

#ifdef OBJC_SPARSE2
941
  printf ("memory usage: (%s)\n", "2-level sparse arrays");
942
#else
943
  printf ("memory usage: (%s)\n", "3-level sparse arrays");
944 945
#endif

946
  printf ("arrays: %d = %ld bytes\n", narrays, 
947
	  (long) ((size_t) narrays * sizeof (struct sarray)));
948 949
  total += narrays * sizeof (struct sarray);
  printf ("buckets: %d = %ld bytes\n", nbuckets, 
950
	  (long) ((size_t) nbuckets * sizeof (struct sbucket)));
951 952 953
  total += nbuckets * sizeof (struct sbucket);

  printf ("idxtables: %d = %ld bytes\n",
954
	  idxsize, (long) ((size_t) idxsize * sizeof (void *)));
955 956 957 958 959 960
  total += idxsize * sizeof (void *);
  printf ("-----------------------------------\n");
  printf ("total: %d bytes\n", total);
  printf ("===================================\n");

  objc_mutex_unlock (__objc_runtime_mutex);
961 962
}

963 964
static cache_ptr prepared_dtable_table = 0;

965 966 967
/* This function is called by: objc_msg_lookup, get_imp and
   __objc_responds_to (and the dispatch table installation functions
   themselves) to install a dispatch table for a class.
968 969 970 971 972 973 974 975

   If CLS is a class, it installs instance methods.
   If CLS is a meta class, it installs class methods.

   In either case +initialize is invoked for the corresponding class.

   The implementation must insure that the dispatch table is not
   installed until +initialize completes.  Otherwise it opens a
976 977 978 979
   potential race since the installation of the dispatch table is used
   as gate in regular method dispatch and we need to guarantee that
   +initialize is the first method invoked an that no other thread my
   dispatch messages to the class before +initialize completes.  */
980 981 982
static void
__objc_install_dtable_for_class (Class cls)
{
983 984
  /* If the class has not yet had its class links resolved, we must
     re-compute all class links.  */
985 986 987
  if (! CLS_ISRESOLV (cls))
    __objc_resolve_class_links ();

988 989 990
  /* Make sure the super class has its dispatch table installed or is
     at least preparing.  We do not need to send initialize for the
     super class since __objc_send_initialize will insure that.  */
991
  if (cls->super_class
992 993
      && cls->super_class->dtable == __objc_uninstalled_dtable
      && !__objc_prepared_dtable_for_class (cls->super_class))
994 995 996
    {
      __objc_install_dtable_for_class (cls->super_class);
      /* The superclass initialisation may have also initialised the
997
         current class, in which case there is no more to do.  */
998
      if (cls->dtable != __objc_uninstalled_dtable)
999
	return;
1000 1001 1002
    }

  /* We have already been prepared but +initialize hasn't completed.
1003 1004 1005
     The +initialize implementation is probably sending 'self'
     messages.  We rely on _objc_get_prepared_imp to retrieve the
     implementation pointers.  */
1006
  if (__objc_prepared_dtable_for_class (cls))
1007
    return;
1008

1009 1010 1011
  /* We have this function cache the implementation pointers for
     _objc_get_prepared_imp but the dispatch table won't be initilized
     until __objc_send_initialize completes.  */
1012 1013
  __objc_prepare_dtable_for_class (cls);

1014 1015
  /* We may have already invoked +initialize but
     __objc_update_dispatch_table_for_class invoked by
1016 1017
     class_add_method_list may have reset dispatch table.  */

1018 1019 1020 1021
  /* Call +initialize.  If we are a real class, we are installing
     instance methods.  If we are a meta class, we are installing
     class methods.  The __objc_send_initialize itself will insure
     that the message is called only once per class.  */
1022 1023 1024 1025
  if (CLS_ISCLASS (cls))
    __objc_send_initialize (cls);
  else
    {
1026
      /* Retrieve the class from the meta class.  */
1027
      Class c = objc_getClass (cls->name);
1028 1029 1030 1031 1032 1033 1034 1035 1036
      assert (CLS_ISMETA (cls));
      assert (c);
      __objc_send_initialize (c);
    }

  /* We install the dispatch table correctly when +initialize completed.  */
  __objc_install_prepared_dtable_for_class (cls);
}

1037 1038 1039 1040 1041
/* Builds the dispatch table for the class CLS and stores it in a
   place where it can be retrieved by __objc_get_prepared_imp until
   __objc_install_prepared_dtable_for_class installs it into the
   class.  The dispatch table should not be installed into the class
   until +initialize has completed.  */
1042 1043 1044 1045 1046 1047
static void
__objc_prepare_dtable_for_class (Class cls)
{
  struct sarray *dtable;
  struct sarray *super_dtable;

1048 1049 1050 1051
  /* This table could be initialized in init.c.  We can not use the
     class name since the class maintains the instance methods and the
     meta class maintains the the class methods yet both share the
     same name.  Classes should be unique in any program.  */
1052 1053
  if (! prepared_dtable_table)
    prepared_dtable_table 
1054 1055 1056 1057 1058 1059
      = objc_hash_new (32,
		       (hash_func_type) objc_hash_ptr,
		       (compare_func_type) objc_compare_ptrs);
  
  /* If the class has not yet had its class links resolved, we must
     re-compute all class links.  */
1060 1061 1062 1063 1064 1065
  if (! CLS_ISRESOLV (cls))
    __objc_resolve_class_links ();

  assert (cls);
  assert (cls->dtable == __objc_uninstalled_dtable);

1066 1067 1068 1069
  /* If there is already a prepared dtable for this class, we must
     replace it with a new version (since there must have been methods
     added to or otherwise modified in the class while executing
     +initialize, and the table needs to be recomputed.  */
1070
  dtable = __objc_prepared_dtable_for_class (cls);
1071
  if (dtable != 0)
1072 1073 1074 1075 1076 1077 1078 1079 1080
    {
      objc_hash_remove (prepared_dtable_table, cls);
      sarray_free (dtable);
    }

  /* Now prepare the dtable for population.  */
  assert (cls != cls->super_class);
  if (cls->super_class)
    {
1081 1082 1083
      /* Inherit the method list from the super class.  Yet the super
         class may still be initializing in the case when a class
         cluster sub class initializes its super classes.  */
1084 1085 1086 1087
      if (cls->super_class->dtable == __objc_uninstalled_dtable)
	__objc_install_dtable_for_class (cls->super_class);

      super_dtable = cls->super_class->dtable;
1088 1089 1090
      /* If the dispatch table is not yet installed, we are still in
	 the process of executing +initialize.  Yet the dispatch table
	 should be available.  */
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
      if (super_dtable == __objc_uninstalled_dtable)
	super_dtable = __objc_prepared_dtable_for_class (cls->super_class);

      assert (super_dtable);
      dtable = sarray_lazy_copy (super_dtable);
    }
  else
    dtable = sarray_new (__objc_selector_max_index, 0);

  __objc_install_methods_in_dtable (dtable, cls->methods);

  objc_hash_add (&prepared_dtable_table,
		 cls,
		 dtable);
}

1107 1108 1109
/* This wrapper only exists to allow an easy replacement of the lookup
   implementation and it is expected that the compiler will optimize
   it away.  */
1110 1111 1112 1113 1114 1115 1116
static struct sarray *
__objc_prepared_dtable_for_class (Class cls)
{
  struct sarray *dtable = 0;
  assert (cls);
  if (prepared_dtable_table)
    dtable = objc_hash_value_for_key (prepared_dtable_table, cls);
1117 1118
  /* dtable my be nil, since we call this to check whether we are
     currently preparing before we start preparing.  */
1119 1120 1121 1122
  return dtable;
}

/* Helper function for messages sent to CLS or implementation pointers
1123 1124 1125 1126 1127 1128 1129
   retrieved from CLS during +initialize before the dtable is
   installed.  When a class implicitly initializes another class which
   in turn implicitly invokes methods in this class, before the
   implementation of +initialize of CLS completes, this returns the
   expected implementation.  Forwarding remains the responsibility of
   objc_msg_lookup.  This function should only be called under the
   global lock.  */
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
static IMP
__objc_get_prepared_imp (Class cls,SEL sel)
{
  struct sarray *dtable;
  IMP imp;

  assert (cls);
  assert (sel);
  assert (cls->dtable == __objc_uninstalled_dtable);
  dtable = __objc_prepared_dtable_for_class (cls);

  assert (dtable);
  assert (dtable != __objc_uninstalled_dtable);
  imp = sarray_get_safe (dtable, (size_t) sel->sel_id);

1145 1146
  /* imp may be Nil if the method does not exist and we may fallback
     to the forwarding implementation later.  */
1147 1148 1149
  return imp;  
}

1150 1151 1152 1153
/* When this function is called +initialize should be completed.  So
   now we are safe to install the dispatch table for the class so that
   they become available for other threads that may be waiting in the
   lock.  */
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
static void
__objc_install_prepared_dtable_for_class (Class cls)
{
  assert (cls);
  assert (cls->dtable == __objc_uninstalled_dtable);
  cls->dtable = __objc_prepared_dtable_for_class (cls);

  assert (cls->dtable);
  assert (cls->dtable != __objc_uninstalled_dtable);
  objc_hash_remove (prepared_dtable_table, cls);
}