summaryrefslogtreecommitdiff
path: root/Objective-C/libobjcl.m
blob: 25fc11f33ea8ab991b7b138daf22ca835525cb0e (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
/* -*- mode: objc; coding: utf-8 -*- */

#import "libobjcl.h"
#import "libffi_support.h"
#import "objc_support.h"

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

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


static NSAutoreleasePool *objcl_autorelease_pool = NULL;

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


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


void
objcl_shutdown_runtime (void)
{
  [objcl_autorelease_pool release];
}


#ifdef __NEXT_RUNTIME__
size_t
objc_sizeof_type (const char *typespec)
{
  switch (typespec[0])
    {
    case '@': return sizeof (id);
    case '#': return sizeof (Class);
    case ':': return sizeof (SEL);
    case 'c': return sizeof (char);
    case 'C': return sizeof (unsigned char);
    case 's': return sizeof (short);
    case 'S': return sizeof (unsigned short);
    case 'i': return sizeof (int);
    case 'I': return sizeof (unsigned int);
    case 'l': return sizeof (long);
    case 'L': return sizeof (unsigned long);
    case 'q': return sizeof (long long);
    case 'Q': return sizeof (unsigned long long);
    case 'f': return sizeof (float);
    case 'd': return sizeof (double);
    case 'B': return sizeof (BOOL);
    case '?':
    case '^': return sizeof (void *);
    case '*': return sizeof (char *);
    default:
      NSLog (@"Dammit.  What the heck is `%s' supposed to mean?",
             typespec);
      return 0;  /* FIXME: Should signal an error. */
    }
}
#endif


static void
_objcl_get_arg_pointer (void *buffer, OBJCL_OBJ_DATA argdata)
{
  void *source = NULL;

  switch (argdata->type[0])
    {
    case '@': source = &argdata->data.id_val; break;
    case '#': source = &argdata->data.id_val; break;
    case ':': source = &argdata->data.sel_val; break;
    case 'c': source = &argdata->data.char_val; break;
    case 'C': source = &argdata->data.char_val; break;
    case 's': source = &argdata->data.short_val; break;
    case 'S': source = &argdata->data.short_val; break;
    case 'i': source = &argdata->data.int_val; break;
    case 'I': source = &argdata->data.int_val; break;
    case 'l': source = &argdata->data.long_val; break;
    case 'L': source = &argdata->data.long_val; break;
    case 'q': source = &argdata->data.long_long_val; break;
    case 'Q': source = &argdata->data.long_long_val; break;
    case 'f': source = &argdata->data.float_val; break;
    case 'd': source = &argdata->data.double_val; break;
    case 'B': source = &argdata->data.bool_val; break;
/*    _OBJCL_ARG_CASE(_C_PTR, ptr); */
    case '^': source = &argdata->data.ptr_val; break;
    case '?': source = &argdata->data.ptr_val; break;
    case '*': source = &argdata->data.charptr_val; break;
/*
  case 'v': source = &argdata->data.oid_val; break;
  case 'b': source = &argdata->data.bitfield_val; break;
      _OBJCL_ARG_CASE(_C_ATOM, atom);
      _OBJCL_ARG_CASE(_C_ARY_B, );
      _OBJCL_ARG_CASE(_C_UNION_B, );
      _OBJCL_ARG_CASE(_C_STRUCT_B, );
      _OBJCL_ARG_CASE(_C_VECTOR, );
      _OBJCL_ARG_CASE(_C_COMPLEX, );
*/
/*  case '?': */
    default:
      NSLog (@"Dammit.  What the heck is `%s' supposed to mean?",
             argdata->type);
      return;  /* FIXME: Should signal an error. */
    }

  memmove (buffer, source, objc_sizeof_type (argdata->type));
}


static void
_objcl_invoke_method (id self_,
                      OBJCL_OBJ_DATA result,
                      NSMethodSignature *signature,
                      SEL selector,
                      int argc,
                      va_list arglist)
{
  int i;
  NSInvocation *invocation;
  void *result_ptr = NULL;
  const char *type = [signature methodReturnType];

  result->type = malloc (strlen (type) + 1);
  strcpy (result->type, type);

  if (signature == NULL)
    {
      [[NSException exceptionWithName: @"MLKNoSignatureFoundException"
                    reason: @"No signature found"
                    userInfo: NULL] raise];
    }

  
  switch (type[0])
    {
    case '@': result_ptr = &(result->data.id_val); break;
    case '#': result_ptr = &result->data.id_val; break;
    case ':': result_ptr = &result->data.sel_val; break;
    case 'c': result_ptr = &result->data.char_val; break;
    case 'C': result_ptr = &result->data.char_val; break;
    case 's': result_ptr = &result->data.short_val; break;
    case 'S': result_ptr = &result->data.short_val; break;
    case 'i': result_ptr = &result->data.int_val; break;
    case 'I': result_ptr = &result->data.int_val; break;
    case 'l': result_ptr = &result->data.long_val; break;
    case 'L': result_ptr = &result->data.long_val; break;
    case 'q': result_ptr = &result->data.long_long_val; break;
    case 'Q': result_ptr = &result->data.long_long_val; break;
    case 'f': result_ptr = &result->data.float_val; break;
    case 'd': result_ptr = &result->data.double_val; break;
    case 'B': result_ptr = &result->data.bool_val; break;
    case '?':
    case '^': result_ptr = &result->data.ptr_val; break;
    case '*': result_ptr = &result->data.charptr_val; break;
      /*
    case _C_BFLD: result_ptr = &result->data._val; break;
    case _C_VOID: result_ptr = &result->data._val; break;
    case _C_UNDEF: result_ptr = &result->data._val; break;
    case _C_ATOM: result_ptr = &result->data._val; break;
    case _C_ARY_B: result_ptr = &result->data._val; break;
    case _C_ARY_E: result_ptr = &result->data._val; break;
    case _C_UNION_B: result_ptr = &result->data._val; break;
    case _C_UNION_E: result_ptr = &result->data._val; break;
    case _C_STRUCT_B: result_ptr = &result->data._val; break;
    case _C_STRUCT_E: result_ptr = &result->data._val; break;
    case _C_VECTOR: result_ptr = &result->data._val; break;
    case _C_COMPLEX: result_ptr = &result->data._val; break;
      */
    }

  invocation = [NSInvocation invocationWithMethodSignature: signature];
  [invocation setTarget: self_];
  [invocation setSelector: selector];

  for (i = 0; i < argc; i++)
    {
      const char* type = [signature getArgumentTypeAtIndex: (i + 2)];
      void *buffer = malloc (objc_sizeof_type (type));
      OBJCL_OBJ_DATA arg = va_arg (arglist, OBJCL_OBJ_DATA);
      _objcl_get_arg_pointer (buffer, arg);

      if (type[0] == '#')
        NSLog (@"Argument %d: %@ (type %s)", i, buffer, type);
      else
        NSLog (@"Argument %d: type %s.", i, type);

      [invocation setArgument: buffer
                  atIndex: (i + 2)];

      free (buffer);
    }

  [invocation retainArguments];
  NSLog (@"Invoking %@ on %@.", invocation, self_);
  [invocation invoke];
  NSLog (@"Fetching return value.");
  [invocation getReturnValue: result_ptr];
  if (result->type[0] == '#')
    NSLog (@"Returning: %@", result->data.id_val);
  else
    NSLog (@"Returning.");
}


OBJCL_OBJ_DATA
objcl_invoke_method (OBJCL_OBJ_DATA receiver,
                     SEL method_selector,
                     int argc,
                     ...)
{
  va_list arglist;
  id self_ = NULL;
  NSMethodSignature *signature;
  OBJCL_OBJ_DATA result = malloc (sizeof (struct objcl_object));

  NS_DURING
    {
      switch (receiver->type[0])
        {
        case '#':
          self_ = receiver->data.class_val;
          break;
        case '@':
          self_ = receiver->data.id_val;
          break;
        case 'E':
          self_ = receiver->data.exc_val;
          break;
        default:
          return NULL;
        }


      signature = [self_ methodSignatureForSelector: method_selector];

      va_start (arglist, argc);
      _objcl_invoke_method (self_,
                            result,
                            signature,
                            method_selector,
                            argc,
                            arglist);
      va_end (arglist);
    }
  NS_HANDLER
    {
      result->type = malloc (strlen (EXCEPTION_TYPESPEC) + 1);
      strcpy (result->type, EXCEPTION_TYPESPEC);
      result->data.exc_val = localException;
      NS_VALUERETURN (result, void *);
    }
  NS_ENDHANDLER

    return result;
}


#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
    {
#ifdef __NEXT_RUNTIME__
      method = class_getInstanceMethod ([receiver class], method_selector)->method_imp;
#else
      method = objc_msg_lookup (receiver, method_selector);
      /* Alternatively:
         method = [receiver methodForSelector: method_selector];
      */
#endif

      if (method == NULL)
        [[NSException exceptionWithName: @"MLKNoApplicableMethod"
                      reason: @"Tried to call a non-existent method."
                      userInfo: nil] raise];

      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];
        }

      ffi_call (&cif, FFI_FN (method), return_value, argv);
    }
  NS_HANDLER
    {
      NS_VALUERETURN (localException, id);
    }
  NS_ENDHANDLER

  return NULL;
}
#endif


OBJCL_OBJ_DATA
objcl_find_class (const char *class_name)
{
  Class class =
    NSClassFromString ([NSString stringWithUTF8String: class_name]);
  OBJCL_OBJ_DATA result = malloc (sizeof (struct objcl_object));
  const char *const typespec = @encode (Class);

  result->type = malloc (strlen (typespec) + 1);
  strcpy (result->type, typespec);
  result->data.class_val = class;

  return result;
}


OBJCL_OBJ_DATA
objcl_find_selector (const char *class_name)
{
  SEL selector =
    NSSelectorFromString ([NSString stringWithUTF8String: class_name]);
  OBJCL_OBJ_DATA result = malloc (sizeof (struct objcl_object));
  const char *const typespec = @encode (SEL);

  result->type = malloc (strlen (typespec) + 1);
  strcpy (result->type, typespec);
  result->data.sel_val = selector;

  return result;
}


const char *
objcl_class_name (OBJCL_OBJ_DATA class)
{
  const char *ns_name;
  char *name;
  Class cls = NULL;

  switch (class->type[0])
    {
    case '#':
      cls = class->data.class_val;
      break;
    case '@':
      cls = class->data.id_val;
      break;
    case 'E':
      cls = (id) class->data.exc_val;
      break;
    default:
      return NULL;
    }

  ns_name = [(NSStringFromClass (cls)) UTF8String];
  name = malloc (strlen (ns_name) + 1);
  strcpy (name, ns_name);

  return name;
}


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

  if (strcmp (selector->type, @encode (SEL)) != 0)
    return NULL;

  ns_name = [(NSStringFromSelector (selector->data.sel_val))
              UTF8String];
  name = malloc (strlen (ns_name) + 1);
  strcpy (name, ns_name);

  return name;
}


IMP
objcl_get_method_implementation (OBJCL_OBJ_DATA object,
                                 OBJCL_OBJ_DATA selector)
{
  id obj;

  if (strcmp (selector->type, @encode (SEL)) != 0)
    return NULL;

  switch (object->type[0])
    {
    case '#':
      obj = object->data.class_val;
      break;
    case '@':
      obj = object->data.id_val;
      break;
    case 'E':
      obj = (id) object->data.exc_val;
      break;
    default:
      return NULL;
    }

#ifdef __NEXT_RUNTIME__
  return class_getInstanceMethod ([obj class],
                                  selector->data.sel_val)->method_imp;
#else
  return objc_msg_lookup (obj, selector->data.sel_val);
#endif
}