summaryrefslogtreecommitdiff
path: root/Objective-C/libobjcl.m
blob: b380b6e7e065d420a647a9bbbf331f0f5d5fd28a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
/* -*- mode: objc; coding: utf-8 -*- */
/* Objective-CL, an Objective-C bridge for Common Lisp.
 * Copyright (C) 2007  Matthias Andreas Benkard.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#import "libobjcl.h"
#import "NSObject-ObjectiveCLWrapperLink.h"
#import "PyObjC/libffi_support.h"
#import "JIGS/ObjcRuntimeUtilities.h"

#import <Foundation/Foundation.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <objc/objc-api.h>

#ifdef __NEXT_RUNTIME__
#include <objc/objc-class.h>
#endif

#if 0
#define TRACE NSLog
#else
#define TRACE objcl_null_log
#endif

static void
objcl_null_log (NSString *s, ...)
{
}


static NSAutoreleasePool *objcl_autorelease_pool = NULL;

/* Preallocate an exception to throw when memory is all used up. */
NSException *objcl_oom_exception = NULL;

id objcl_current_exception = NULL;
void *objcl_current_exception_lock = NULL;

static NSMutableDictionary *method_lists = NULL;
static NSMutableDictionary *method_list_lengths = NULL;

static int init_count = 0;


void
objcl_initialise_runtime (void)
{
  if (init_count <= 0)
    {
      objcl_autorelease_pool = [[NSAutoreleasePool alloc] init];
      objcl_oom_exception = [NSException exceptionWithName: @"MLKOutOfMemoryException"
                                         reason: @"Out of memory"
                                         userInfo: nil];
      [objcl_oom_exception retain];

#ifdef __NEXT_RUNTIME__
      PyObjC_SetupRuntimeCompat ();
#endif

      objcl_initialise_lock (&objcl_current_exception_lock);
      method_lists = [[NSMutableDictionary alloc] init];
      method_list_lengths = [[NSMutableDictionary alloc] init];
      objcl_initialise_instance_wrappers ();
      init_count = 1;
    }
  else
    init_count++;
}


static void
release_unless_null (id *object)
{
  if (*object)
    {
      [*object release];
      *object = NULL;
    }
}


void
objcl_shutdown_runtime (void)
{
  init_count--;
  if (init_count == 0)
    {
      release_unless_null (&objcl_autorelease_pool);
      release_unless_null (&objcl_oom_exception);
      release_unless_null (&method_lists);
      release_unless_null (&method_list_lengths);
      objcl_shutdown_instance_wrappers ();
    }
  else if (init_count < 0)
    init_count = 0;
}


#ifdef USE_LIBFFI
id
objcl_invoke_with_types (int argc,
                         char *return_typespec,
                         char *arg_typespecs[],
                         void *return_value,
                         void **argv)
{
  IMP method;
  int i;
  ffi_cif cif;
  ffi_type *return_type;
  ffi_type *arg_types[argc + 2];
  ffi_status status;

  id receiver = *((id*)argv[0]);
  SEL method_selector = *((SEL*)argv[1]);

  static ffi_type *id_type = NULL;
  static ffi_type *sel_type = NULL;

  if (!id_type)
    id_type = objcl_pyobjc_arg_signature_to_ffi_type ("@");
  if (!sel_type)
    sel_type = objcl_pyobjc_arg_signature_to_ffi_type (":");

  NS_DURING
    {
      TRACE (@"get-method");
      method = objcl_get_method_implementation (receiver, method_selector);
      TRACE (@"method == NULL");
      if (method == NULL)
        [[NSException exceptionWithName: @"MLKNoApplicableMethod"
                      reason: @"Tried to call a non-existent method."
                      userInfo: nil] raise];

      TRACE (@"return type");
      return_type = objcl_pyobjc_signature_to_ffi_return_type (return_typespec);
      arg_types[0] = id_type;
      arg_types[1] = sel_type;

      TRACE (@"args");
      for (i = 0; i < argc; i++)
        arg_types[i + 2] = objcl_pyobjc_arg_signature_to_ffi_type (arg_typespecs[i]);

      TRACE (@"prep");
      status = ffi_prep_cif (&cif, FFI_DEFAULT_ABI, argc + 2, return_type, arg_types);
      if (status != FFI_OK)
        {
          [[NSException exceptionWithName: @"MLKInvalidFFITypeException"
                        reason: @"FFI type is invalid (this is probably a bug)."
                        userInfo: nil] raise];
        }

      TRACE (@"call");
      ffi_call (&cif, FFI_FN (method), return_value, argv);
      TRACE (@"...");
    }
  NS_HANDLER
    {
      NS_VALUERETURN (localException, id);
    }
  NS_ENDHANDLER

  return NULL;
}
#endif


Class
objcl_find_class (const char *class_name)
{
  TRACE (@"find-class %s", class_name);
#ifdef __NEXT_RUNTIME__
  return objc_getClass (class_name);
#else
  return objc_lookup_class (class_name);
#endif
}


Class
objcl_find_meta_class (const char *class_name)
{
  TRACE (@"find-meta-class %s", class_name);
#ifdef __NEXT_RUNTIME__
  return objc_getMetaClass (class_name);
#else
  /* FIXME: Is this correct? */
  Class class = objcl_find_class (class_name);
  if (class == NULL || class == nil)
    return NULL;
  else
    return class_get_meta_class (class);
#endif
}


SEL
objcl_find_selector (const char *selector_name)
{
#ifdef __NEXT_RUNTIME__
  if (!(sel_isMapped ((SEL) selector_name)))  /* XXX Does this work? */
    return NULL;
  else
    return sel_getUid (selector_name);
#else
  return sel_get_any_uid (selector_name);
#endif
}


SEL
objcl_intern_selector (const char *selector_name)
{
  /* sel_registerName and sel_register_name seem not to be necessary here. */
#ifdef __NEXT_RUNTIME__
  return sel_getUid (selector_name);
#else
  return sel_get_uid (selector_name);
#endif
}


const char *
objcl_class_name (Class class)
{
  const char *ns_name;
  char *name;

  TRACE (@"class-name");
  ns_name = [(NSStringFromClass (class)) UTF8String];
  name = malloc (strlen (ns_name) + 1);
  strcpy (name, ns_name);

  return name;
}


Class
objcl_class_superclass (Class class)
{
  TRACE (@"super-class");

  /* Not strictly needed on the GNU runtime, but not going to hurt
     anyone either. */
  if (class == [NSObject class])
    return nil;

#ifdef __NEXT_RUNTIME__
  return class_getSuperclass (class);
#else
  return class_get_super_class (class);
#endif
}


const char *
objcl_selector_name (SEL selector)
{
  const char *ns_name;
  char *name;

  ns_name = [(NSStringFromSelector (selector)) UTF8String];
  name = malloc (strlen (ns_name) + 1);
  strcpy (name, ns_name);

  return name;
}


IMP
objcl_get_method_implementation (id object,
                                 SEL selector)
{
  TRACE (@"method-impl %p %p", object, selector);
#ifdef __NEXT_RUNTIME__
  if (objcl_object_is_class (object))
    return method_getImplementation (class_getClassMethod (object, selector));
  else
    {
#ifdef __OBJC2__
      return class_getMethodImplementation ([object class], selector);
#else
      return method_getImplementation (class_getInstanceMethod ([object class], selector));
#endif
    }
#else
  return objc_msg_lookup (object, selector);
#endif
}


BOOL
objcl_object_is_class (id obj)
{
  TRACE (@"is-class %p", obj);
#ifdef __NEXT_RUNTIME__
  return [obj class] == obj;
#else
  /* return CLS_ISCLASS (obj); */
  return object_is_class (obj);
#endif
}


BOOL
objcl_object_is_meta_class (id obj)
{
  TRACE (@"is-meta-class %p", obj);
#ifdef __NEXT_RUNTIME__
  return objcl_object_is_class (obj) && class_isMetaClass (obj);
#else
  /* return CLS_ISMETA (ptr); */
  if (objcl_object_is_class (obj))
    return class_is_meta_class (obj);
  else
    return object_is_meta_class (obj);
#endif
}


Class
objcl_object_get_class (id obj)
{
  TRACE (@"get-class %p", obj);
#ifdef __NEXT_RUNTIME__
  return object_getClass (obj);
#else
  return object_get_class (obj);
#endif
}


Class
objcl_object_get_meta_class (id obj)
{
  TRACE (@"get-meta-class %p", obj);
#ifdef __NEXT_RUNTIME__
  /* FIXME: What to do here? */
  return objc_getMetaClass ([(NSStringFromClass ([obj class])) UTF8String]);
#else
  if (objcl_object_is_class (obj))
    return class_get_meta_class (obj);
  else
    return object_get_meta_class (obj);
#endif
}


id
objcl_get_nil (void)
{
  return nil;
}


long
objcl_get_yes (void)
{
  if (sizeof (YES) > sizeof (long))
    fprintf (stderr, "WARNING: objcl_get_yes: YES might not fit into a long.\n");
  return YES;
}


long
objcl_get_no (void)
{
  if (sizeof (NO) > sizeof (long))
    fprintf (stderr, "WARNING: objcl_get_no: NO might not fit into a long.\n");
  return NO;
}


const char *
objcl_get_runtime_type (void)
{
#ifdef __NEXT_RUNTIME__
  return "NeXT";
#else
  return "GNU";
#endif
}


int
objcl_objc2_p (void)
{
#ifdef __OBJC2__
  return 1;
#else
  return 0;
#endif
}


long
objcl_sizeof_type (const char *typespec)
{
  if (sizeof (ssize_t) > sizeof (long))
    fprintf (stderr, "WARNING: objcl_sizeof_typespec: Size might not fit into a long.\n");
  return PyObjCRT_SizeOfType (typespec);
}


long
objcl_sizeof_return_type (const char *typespec)
{
  if (sizeof (ssize_t) > sizeof (long))
    fprintf (stderr, "WARNING: objcl_sizeof_return_typespec: Size might not fit into a long.\n");
  return PyObjCRT_SizeOfReturnType (typespec);
}


long
objcl_alignof_type (const char *typespec)
{
  if (sizeof (ssize_t) > sizeof (long))
    fprintf (stderr, "WARNING: objcl_align_typespec: Alignment might not fit into a long.\n");
  return PyObjCRT_AlignOfType (typespec);
}


void
objcl_set_slot_value (id obj, const char *ivar_name, void *value)
{
  /* For the GNU runtime, this function is defined in objc-runtime-gnu.m. */
  object_setInstanceVariable (obj, ivar_name, value);
}


void *
objcl_slot_value (id obj, const char *ivar_name)
{
  void *value;
  /* Caching Ivars may be useful here.  Using those instead of strings
     is claimed to be faster. */
  /* For the GNU runtime, this function is defined in objc-runtime-gnu.m. */
  object_getInstanceVariable (obj, ivar_name, &value);
  return value;
}


IVAR_T *
objcl_class_direct_slots (Class class, unsigned int *count, unsigned int *element_size)
{
  IVAR_T *ivars;

#ifdef __NEXT_RUNTIME__
  TRACE (@"slots");
#else
  int i;
#endif

  *element_size = sizeof (IVAR_T);

#ifdef __NEXT_RUNTIME__
  ivars = class_copyIvarList (class, count);
#else
  *count = (class->ivars ? class->ivars->ivar_count : 0);
  if (!*count)
    ivars = NULL;
  else
    {
      ivars = malloc ((*count) * (*element_size));
      for (i = 0; i < *count; i++)
        ivars[i] = &class->ivars->ivar_list[i];
    }
#endif

  return ivars;
}


const char *
objcl_slot_name (IVAR_T ivar)
{
  TRACE (@"slot-name");
#ifdef __NEXT_RUNTIME__
  return ivar_getName (ivar);
#else
  return ivar->ivar_name;
#endif
}


const char *
objcl_slot_type (IVAR_T ivar)
{
#ifdef __NEXT_RUNTIME__
  return ivar_getTypeEncoding (ivar);
#else
  return ivar->ivar_type;
#endif
}


/* In order to be able to do exception propagation from Lisp code, we
   have the Lisp layer save exceptions to objcl_current_exception.  Our
   wrapper function is then able to raise the exception from where it
   ought to be raised from: the Objective-C layer.

   Note that it is the Lisp layer's duty to wrap Objective-C exceptions
   around Lisp SERIOUS-CONDITIONs in order to propagate those. */
static void
imp_closure (ffi_cif *cif, void *result, void **args, void *user_data)
{
  id exception;

  ffi_call (cif, user_data, result, args);

  exception = objcl_current_exception;
  objcl_current_exception = NULL;
  objcl_release_lock (objcl_current_exception_lock);

  if (exception)
    [exception raise];
}


IMP
objcl_create_imp (IMP callback,
                  int argc,
                  const char *return_typespec,
                  const char *arg_typespecs[])
{
  ffi_type *return_type;
  ffi_type *arg_types[argc + 2];
  ffi_status status;
  ffi_cif cif;
  ffi_closure *closure;

  int i;

  static ffi_type *id_type = NULL;
  static ffi_type *sel_type = NULL;

  if (!id_type)
    id_type = objcl_pyobjc_arg_signature_to_ffi_type ("@");

  if (!sel_type)
    sel_type = objcl_pyobjc_arg_signature_to_ffi_type (":");

  return_type = objcl_pyobjc_signature_to_ffi_return_type (return_typespec);

  arg_types[0] = id_type;
  arg_types[1] = sel_type;

  for (i = 0; i < argc; i++)
    arg_types[i + 2] = objcl_pyobjc_arg_signature_to_ffi_type (arg_typespecs[i]);

  status = ffi_prep_cif (&cif, FFI_DEFAULT_ABI, argc + 2, return_type, arg_types);
  if (status != FFI_OK)
    {
      [[NSException exceptionWithName: @"MLKInvalidFFITypeException"
                    reason: @"FFI type is invalid (this is probably a bug)."
                    userInfo: nil] raise];
    }

  status = ffi_prep_closure (closure, &cif, imp_closure, (void *)callback);
  if (status != FFI_OK)
    {
      [[NSException exceptionWithName: @"MLKClosureCreationFailure"
                    reason: @"Creating an IMP closure failed (this is probably a bug)."
                    userInfo: nil] raise];
    }

  if (mprotect (closure, sizeof (closure), PROT_READ | PROT_EXEC) == -1)
    {
      [[NSException exceptionWithName: @"MLKClosureCreationFailure"
                    reason: @"Creating an IMP closure failed (this is probably a bug)."
                    userInfo: nil] raise];
    }

  return (IMP) closure;
}


void
objcl_initialise_lock (void **lock)
{
#ifdef HAVE_SYS_SEM_H
  int sem;
  union semun initop;

  sem = semget (IPC_PRIVATE, 1, IPC_CREAT | 0600);
  *lock = malloc (sizeof (int));
  *((int *) *lock) = sem;

  initop.val = 1;
  semctl (sem, 0, SETVAL, initop);
#else
#warning "I do not know how to do locking on this platform."
#endif
}


void
objcl_acquire_lock (void *lock)
{
#ifdef HAVE_SYS_SEM_H
  struct sembuf op;
  op.sem_num = 0; op.sem_op = +1; op.sem_flg = 0;

  if ((semop (*((int *) lock), &op, 1)) < 0)
    {
      [[NSException exceptionWithName: @"MLKLockLossage"
                    reason: @"Acquiring the exception lock failed (don't ask me why)."
                    userInfo: nil] raise];
    }

  TRACE (@"Exception buffer locked.");
#else
#warning "I do not know how to do locking on this platform."
#endif
}


void
objcl_release_lock (void *lock)
{
#ifdef HAVE_SYS_SEM_H
  struct sembuf op;
  op.sem_num = 0; op.sem_op = +1; op.sem_flg = 0;

  if ((semop (*((int *) lock), &op, 1)) < 0)
    {
      [[NSException exceptionWithName: @"MLKLockLossage"
                    reason: @"Acquiring the exception lock failed (don't ask me why)."
                    userInfo: nil] raise];
    }

  TRACE (@"Exception buffer unlocked.");
#else
#warning "I do not know how to do locking on this platform."
#endif
}


Class
objcl_create_class (const char *class_name,
                    Class superclass,
                    int protocol_number,
                    const char *protocol_names[],
                    int ivar_number,
                    const char *ivar_names[],
                    const char *ivar_typespecs[])
{
#ifdef __NEXT_RUNTIME__
  int i;
  Class class;

  objc_allocateClassPair (superclass, class_name, 0);
  class = objcl_find_class (class_name);

  for (i = 0; i < ivar_number; i++)
    preclass_addIvar (class,
                      ivar_names[i],
                      objcl_sizeof_type (ivar_typespecs[i]),
                      objcl_alignof_type (ivar_typespecs[i]),
                      ivar_typespecs[i]);

#ifdef __OBJC2__
  /* FIXME: What to do for the NeXT Objective-C 1.0 and GNU runtimes
     here? */
  for (i = 0; i < protocol_number; i++)
    preclass_addProtocol (class,
                          objc_getProtocol ((char *) protocol_names[i])
                          /* ??? !__OBJC2__ ???
                             objc_getClass (protocol_names[i]) */
                          );
#endif

  return class;
#else
  ffi_cif cif;
  ffi_status status;
  ffi_type *arg_types[3 + ivar_number*2];
  void *argv[3 + ivar_number*2];
  int i;
  BOOL return_value;
  const char *superclass_name;

  arg_types[0] = &ffi_type_pointer;
  arg_types[1] = &ffi_type_pointer;
  arg_types[2] = &ffi_type_sint;
  for (i = 0; i < ivar_number*2; i++)
    arg_types[3 + i] = &ffi_type_pointer;

  superclass_name = objcl_class_name (superclass);

  argv[0] = &class_name;
  argv[1] = &superclass_name;
  argv[2] = &ivar_number;
  for (i = 0; i < ivar_number; i++)
    {
      argv[3 + 2*i] = (void *) &ivar_names[2*i];
      argv[3 + 2*i + 1] = (void *) &ivar_names[2*i + 1];
    }

  status = ffi_prep_cif (&cif, FFI_DEFAULT_ABI, ivar_number + 3, &ffi_type_uchar, arg_types);
  if (status != FFI_OK)
    {
      [[NSException exceptionWithName: @"MLKInvalidFFITypeException"
                    reason: @"FFI type is invalid (this is probably a bug)."
                    userInfo: nil] raise];
    }

  ffi_call (&cif, FFI_FN (ObjcUtilities_new_class), &return_value, argv);

  NSString *ns_class_name = [NSString stringWithUTF8String: class_name];
  [method_lists setObject:
                  [NSValue valueWithPointer: ObjcUtilities_alloc_method_list]
                forKey: ns_class_name];
  [method_list_lengths setObject: [NSNumber numberWithInt: 0]
                       forKey: ns_class_name];

  return objcl_find_class (class_name);
#endif
}


void
objcl_add_method (Class class,
                  SEL method_name,
                  IMP callback,
                  int argc,
                  const char *return_typespec,
                  const char *arg_typespecs[],
                  const char *signature)
{
  IMP imp;

  imp = objcl_create_imp (callback, argc, return_typespec, arg_typespecs);

#ifdef __NEXT_RUNTIME__
  preclass_addMethod (class, method_name, imp, signature);
#else
  NSString *class_name = [NSString stringWithUTF8String: objcl_class_name (class)];
  MethodList *method_list = [[method_lists objectForKey: class_name] pointerValue];
  int index = [[method_list_lengths objectForKey: class_name] intValue];

  ObjcUtilities_insert_method_in_list
    (method_list,
     index,
     objcl_selector_name (method_name),
     ObjcUtilities_build_runtime_Objc_signature (signature),
     imp);

  [method_list_lengths setObject: [NSNumber numberWithInt: index]
                       forKey: class_name];
#endif
}


void
objcl_finalise_class (Class class)
{
#ifdef __NEXT_RUNTIME__
  /* FIXME: Should we do this if class is a metaclass? */
  objc_registerClassPair (class);
#else
  NSString *class_name = [NSString stringWithUTF8String:
                                     objcl_class_name (class)];
  ObjcUtilities_register_method_list
    (class, [[method_lists objectForKey: class_name]
              pointerValue]);

  [method_lists removeObjectForKey: class_name];
  [method_list_lengths removeObjectForKey: class_name];
#endif
}