]> git.saurik.com Git - cycript.git/blob - Library.mm
bc4a6c76af5fb7d31999edf4fd3639d1db623cf0
[cycript.git] / Library.mm
1 /* Cycript - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #define _GNU_SOURCE
41
42 #include <substrate.h>
43 #include "cycript.hpp"
44
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
47
48 #include "Pooling.hpp"
49 #include "Struct.hpp"
50
51 #include <unistd.h>
52
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
55
56 #include <WebKit/WebScriptObject.h>
57
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <sys/mman.h>
62
63 #include <iostream>
64 #include <ext/stdio_filebuf.h>
65 #include <set>
66 #include <map>
67
68 #include <cmath>
69
70 #include "Parser.hpp"
71 #include "Cycript.tab.hh"
72
73 #undef _assert
74 #undef _trace
75
76 #define _assert(test) do { \
77 if (!(test)) \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
79 } while (false)
80
81 #define _trace() do { \
82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
83 } while (false)
84
85 #define CYPoolTry { \
86 id _saved(nil); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 @try
89 #define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 @throw; \
93 return value; \
94 } @finally { \
95 [_pool release]; \
96 if (_saved != nil) \
97 [_saved autorelease]; \
98 } \
99 }
100
101 static JSGlobalContextRef Context_;
102 static JSObjectRef System_;
103
104 static JSClassRef Functor_;
105 static JSClassRef Instance_;
106 static JSClassRef Pointer_;
107 static JSClassRef Runtime_;
108 static JSClassRef Selector_;
109 static JSClassRef Struct_;
110
111 static JSObjectRef Array_;
112 static JSObjectRef Function_;
113
114 static JSStringRef length_;
115 static JSStringRef message_;
116 static JSStringRef name_;
117 static JSStringRef toCYON_;
118 static JSStringRef toJSON_;
119
120 static Class NSCFBoolean_;
121
122 static NSArray *Bridge_;
123
124 struct CYData {
125 apr_pool_t *pool_;
126
127 virtual ~CYData() {
128 }
129
130 void *operator new(size_t size) {
131 apr_pool_t *pool;
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
134 reinterpret_cast<CYData *>(data)->pool_ = pool;
135 return data;;
136 }
137
138 static void Finalize(JSObjectRef object) {
139 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
140 data->~CYData();
141 apr_pool_destroy(data->pool_);
142 }
143 };
144
145 struct Pointer_privateData :
146 CYData
147 {
148 void *value_;
149 sig::Type type_;
150
151 Pointer_privateData() {
152 }
153
154 Pointer_privateData(void *value) :
155 value_(value)
156 {
157 }
158 };
159
160 struct Functor_privateData :
161 Pointer_privateData
162 {
163 sig::Signature signature_;
164 ffi_cif cif_;
165
166 Functor_privateData(const char *type, void (*value)()) :
167 Pointer_privateData(reinterpret_cast<void *>(value))
168 {
169 sig::Parse(pool_, &signature_, type);
170 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
171 }
172 };
173
174 struct ffoData :
175 Functor_privateData
176 {
177 JSContextRef context_;
178 JSObjectRef function_;
179
180 ffoData(const char *type) :
181 Functor_privateData(type, NULL)
182 {
183 }
184 };
185
186 struct Selector_privateData : Pointer_privateData {
187 Selector_privateData(SEL value) :
188 Pointer_privateData(value)
189 {
190 }
191
192 SEL GetValue() const {
193 return reinterpret_cast<SEL>(value_);
194 }
195 };
196
197 struct Instance_privateData :
198 Pointer_privateData
199 {
200 bool transient_;
201
202 Instance_privateData(id value, bool transient) :
203 Pointer_privateData(value)
204 {
205 }
206
207 virtual ~Instance_privateData() {
208 if (!transient_)
209 [GetValue() release];
210 }
211
212 id GetValue() const {
213 return reinterpret_cast<id>(value_);
214 }
215 };
216
217 namespace sig {
218
219 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
220
221 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
222 lhs.name = apr_pstrdup(pool, rhs.name);
223 if (rhs.type == NULL)
224 lhs.type = NULL;
225 else {
226 lhs.type = new(pool) Type;
227 Copy(pool, *lhs.type, *rhs.type);
228 }
229 lhs.offset = rhs.offset;
230 }
231
232 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
233 size_t count(rhs.count);
234 lhs.count = count;
235 lhs.elements = new(pool) Element[count];
236 for (size_t index(0); index != count; ++index)
237 Copy(pool, lhs.elements[index], rhs.elements[index]);
238 }
239
240 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
241 lhs.primitive = rhs.primitive;
242 lhs.name = apr_pstrdup(pool, rhs.name);
243 lhs.flags = rhs.flags;
244
245 if (sig::IsAggregate(rhs.primitive))
246 Copy(pool, lhs.data.signature, rhs.data.signature);
247 else {
248 if (rhs.data.data.type != NULL) {
249 lhs.data.data.type = new(pool) Type;
250 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
251 }
252
253 lhs.data.data.size = rhs.data.data.size;
254 }
255 }
256
257 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
258 lhs.size = rhs.size;
259 lhs.alignment = rhs.alignment;
260 lhs.type = rhs.type;
261 if (rhs.elements == NULL)
262 lhs.elements = NULL;
263 else {
264 size_t count(0);
265 while (rhs.elements[count] != NULL)
266 ++count;
267
268 lhs.elements = new(pool) ffi_type *[count + 1];
269 lhs.elements[count] = NULL;
270
271 for (size_t index(0); index != count; ++index) {
272 // XXX: if these are libffi native then you can just take them
273 ffi_type *ffi(new(pool) ffi_type);
274 lhs.elements[index] = ffi;
275 sig::Copy(pool, *ffi, *rhs.elements[index]);
276 }
277 }
278 }
279
280 }
281
282 struct Type_privateData {
283 sig::Type type_;
284 ffi_type ffi_;
285
286 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
287 sig::Copy(pool, type_, *type);
288 sig::Copy(pool, ffi_, *ffi);
289 }
290 };
291
292 struct Struct_privateData :
293 Pointer_privateData
294 {
295 JSObjectRef owner_;
296 Type_privateData *type_;
297
298 Struct_privateData() {
299 }
300 };
301
302 struct CStringMapLess :
303 std::binary_function<const char *, const char *, bool>
304 {
305 _finline bool operator ()(const char *lhs, const char *rhs) const {
306 return strcmp(lhs, rhs) < 0;
307 }
308 };
309
310 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
311 static TypeMap Types_;
312
313 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
314 Struct_privateData *internal(new Struct_privateData());
315 apr_pool_t *pool(internal->pool_);
316 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
317 internal->type_ = typical;
318
319 if (owner != NULL) {
320 internal->owner_ = owner;
321 internal->value_ = data;
322 } else {
323 internal->owner_ = NULL;
324
325 size_t size(typical->ffi_.size);
326 void *copy(apr_palloc(internal->pool_, size));
327 memcpy(copy, data, size);
328 internal->value_ = copy;
329 }
330
331 return JSObjectMake(context, Struct_, internal);
332 }
333
334 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
335 if (!transient)
336 object = [object retain];
337 Instance_privateData *data(new Instance_privateData(object, transient));
338 return JSObjectMake(context, Instance_, data);
339 }
340
341 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
342 if (pool == NULL)
343 return [value UTF8String];
344 else {
345 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
346 char *string(new(pool) char[size]);
347 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
348 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
349 return string;
350 }
351 }
352
353 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
354 return JSValueMakeBoolean(context, value);
355 }
356
357 JSValueRef CYCastJSValue(JSContextRef context, double value) {
358 return JSValueMakeNumber(context, value);
359 }
360
361 #define CYCastJSValue_(Type_) \
362 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
363 return JSValueMakeNumber(context, static_cast<double>(value)); \
364 }
365
366 CYCastJSValue_(int)
367 CYCastJSValue_(unsigned int)
368 CYCastJSValue_(long int)
369 CYCastJSValue_(long unsigned int)
370 CYCastJSValue_(long long int)
371 CYCastJSValue_(long long unsigned int)
372
373 JSValueRef CYJSUndefined(JSContextRef context) {
374 return JSValueMakeUndefined(context);
375 }
376
377 @interface NSMethodSignature (Cycript)
378 - (NSString *) _typeString;
379 @end
380
381 @interface NSObject (Cycript)
382
383 - (JSType) cy$JSType;
384
385 - (NSObject *) cy$toJSON:(NSString *)key;
386 - (NSString *) cy$toCYON;
387
388 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
389
390 - (NSObject *) cy$getProperty:(NSString *)name;
391 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
392 - (bool) cy$deleteProperty:(NSString *)name;
393
394 @end
395
396 @interface NSString (Cycript)
397 - (void *) cy$symbol;
398 @end
399
400 @interface NSNumber (Cycript)
401 - (void *) cy$symbol;
402 @end
403
404 struct PropertyAttributes {
405 CYPool pool_;
406
407 const char *name;
408
409 const char *variable;
410
411 const char *getter_;
412 const char *setter_;
413
414 bool readonly;
415 bool copy;
416 bool retain;
417 bool nonatomic;
418 bool dynamic;
419 bool weak;
420 bool garbage;
421
422 PropertyAttributes(objc_property_t property) :
423 variable(NULL),
424 getter_(NULL),
425 setter_(NULL),
426 readonly(false),
427 copy(false),
428 retain(false),
429 nonatomic(false),
430 dynamic(false),
431 weak(false),
432 garbage(false)
433 {
434 name = property_getName(property);
435 const char *attributes(property_getAttributes(property));
436
437 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
438 switch (*token) {
439 case 'R': readonly = true; break;
440 case 'C': copy = true; break;
441 case '&': retain = true; break;
442 case 'N': nonatomic = true; break;
443 case 'G': getter_ = token + 1; break;
444 case 'S': setter_ = token + 1; break;
445 case 'V': variable = token + 1; break;
446 }
447 }
448
449 /*if (variable == NULL) {
450 variable = property_getName(property);
451 size_t size(strlen(variable));
452 char *name(new(pool_) char[size + 2]);
453 name[0] = '_';
454 memcpy(name + 1, variable, size);
455 name[size + 1] = '\0';
456 variable = name;
457 }*/
458 }
459
460 const char *Getter() {
461 if (getter_ == NULL)
462 getter_ = apr_pstrdup(pool_, name);
463 return getter_;
464 }
465
466 const char *Setter() {
467 if (setter_ == NULL && !readonly) {
468 size_t length(strlen(name));
469
470 char *temp(new(pool_) char[length + 5]);
471 temp[0] = 's';
472 temp[1] = 'e';
473 temp[2] = 't';
474
475 if (length != 0) {
476 temp[3] = toupper(name[0]);
477 memcpy(temp + 4, name + 1, length - 1);
478 }
479
480 temp[length + 3] = ':';
481 temp[length + 4] = '\0';
482 setter_ = temp;
483 }
484
485 return setter_;
486 }
487
488 };
489
490 @implementation NSObject (Cycript)
491
492 - (JSType) cy$JSType {
493 return kJSTypeObject;
494 }
495
496 - (NSObject *) cy$toJSON:(NSString *)key {
497 return [self description];
498 }
499
500 - (NSString *) cy$toCYON {
501 return [[self cy$toJSON:@""] cy$toCYON];
502 }
503
504 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
505 return CYMakeInstance(context, self, transient);
506 }
507
508 - (NSObject *) cy$getProperty:(NSString *)name {
509 /*if (![name isEqualToString:@"prototype"])
510 NSLog(@"get:%@", name);*/
511 return nil;
512 }
513
514 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
515 //NSLog(@"set:%@", name);
516 return false;
517 }
518
519 - (bool) cy$deleteProperty:(NSString *)name {
520 //NSLog(@"delete:%@", name);
521 return false;
522 }
523
524 @end
525
526 @implementation WebUndefined (Cycript)
527
528 - (JSType) cy$JSType {
529 return kJSTypeUndefined;
530 }
531
532 - (NSObject *) cy$toJSON:(NSString *)key {
533 return self;
534 }
535
536 - (NSString *) cy$toCYON {
537 return @"undefined";
538 }
539
540 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
541 return CYJSUndefined(context);
542 }
543
544 @end
545
546 @implementation NSNull (Cycript)
547
548 - (JSType) cy$JSType {
549 return kJSTypeNull;
550 }
551
552 - (NSObject *) cy$toJSON:(NSString *)key {
553 return self;
554 }
555
556 - (NSString *) cy$toCYON {
557 return @"null";
558 }
559
560 @end
561
562 @implementation NSArray (Cycript)
563
564 - (NSString *) cy$toCYON {
565 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
566 [json appendString:@"["];
567
568 bool comma(false);
569 for (id object in self) {
570 if (comma)
571 [json appendString:@","];
572 else
573 comma = true;
574 if ([object cy$JSType] != kJSTypeUndefined)
575 [json appendString:[object cy$toCYON]];
576 else {
577 [json appendString:@","];
578 comma = false;
579 }
580 }
581
582 [json appendString:@"]"];
583 return json;
584 }
585
586 - (NSObject *) cy$getProperty:(NSString *)name {
587 if ([name isEqualToString:@"length"])
588 return [NSNumber numberWithUnsignedInteger:[self count]];
589
590 int index([name intValue]);
591 if (index < 0 || index >= static_cast<int>([self count]))
592 return [super cy$getProperty:name];
593 else
594 return [self objectAtIndex:index];
595 }
596
597 @end
598
599 @implementation NSMutableArray (Cycript)
600
601 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
602 int index([name intValue]);
603 if (index < 0 || index >= static_cast<int>([self count]))
604 return [super cy$setProperty:name to:value];
605 else {
606 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
607 return true;
608 }
609 }
610
611 - (bool) cy$deleteProperty:(NSString *)name {
612 int index([name intValue]);
613 if (index < 0 || index >= static_cast<int>([self count]))
614 return [super cy$deleteProperty:name];
615 else {
616 [self removeObjectAtIndex:index];
617 return true;
618 }
619 }
620
621 @end
622
623 @implementation NSDictionary (Cycript)
624
625 - (NSString *) cy$toCYON {
626 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
627 [json appendString:@"({"];
628
629 bool comma(false);
630 for (id key in self) {
631 if (comma)
632 [json appendString:@","];
633 else
634 comma = true;
635 [json appendString:[key cy$toCYON]];
636 [json appendString:@":"];
637 NSObject *object([self objectForKey:key]);
638 [json appendString:[object cy$toCYON]];
639 }
640
641 [json appendString:@"})"];
642 return json;
643 }
644
645 - (NSObject *) cy$getProperty:(NSString *)name {
646 return [self objectForKey:name];
647 }
648
649 @end
650
651 @implementation NSMutableDictionary (Cycript)
652
653 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
654 [self setObject:(value ?: [NSNull null]) forKey:name];
655 return true;
656 }
657
658 - (bool) cy$deleteProperty:(NSString *)name {
659 if ([self objectForKey:name] == nil)
660 return false;
661 else {
662 [self removeObjectForKey:name];
663 return true;
664 }
665 }
666
667 @end
668
669 @implementation NSNumber (Cycript)
670
671 - (JSType) cy$JSType {
672 // XXX: this just seems stupid
673 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
674 }
675
676 - (NSObject *) cy$toJSON:(NSString *)key {
677 return self;
678 }
679
680 - (NSString *) cy$toCYON {
681 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
682 }
683
684 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
685 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
686 }
687
688 - (void *) cy$symbol {
689 return [self pointerValue];
690 }
691
692 @end
693
694 @implementation NSString (Cycript)
695
696 - (JSType) cy$JSType {
697 return kJSTypeString;
698 }
699
700 - (NSObject *) cy$toJSON:(NSString *)key {
701 return self;
702 }
703
704 - (NSString *) cy$toCYON {
705 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
706
707 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
708 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
709 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
710 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
711 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
712
713 CFStringInsert(json, 0, CFSTR("\""));
714 CFStringAppend(json, CFSTR("\""));
715
716 return [reinterpret_cast<const NSString *>(json) autorelease];
717 }
718
719 - (void *) cy$symbol {
720 CYPool pool;
721 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
722 }
723
724 @end
725
726 @interface CYJSObject : NSDictionary {
727 JSObjectRef object_;
728 JSContextRef context_;
729 }
730
731 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
732
733 - (NSString *) cy$toJSON:(NSString *)key;
734
735 - (NSUInteger) count;
736 - (id) objectForKey:(id)key;
737 - (NSEnumerator *) keyEnumerator;
738 - (void) setObject:(id)object forKey:(id)key;
739 - (void) removeObjectForKey:(id)key;
740
741 @end
742
743 @interface CYJSArray : NSArray {
744 JSObjectRef object_;
745 JSContextRef context_;
746 }
747
748 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
749
750 - (NSUInteger) count;
751 - (id) objectAtIndex:(NSUInteger)index;
752
753 @end
754
755 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
756 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
757
758 JSGlobalContextRef CYGetJSContext() {
759 return Context_;
760 }
761
762 #define CYTry \
763 @try
764 #define CYCatch \
765 @catch (id error) { \
766 CYThrow(context, error, exception); \
767 return NULL; \
768 }
769
770 void CYThrow(JSContextRef context, JSValueRef value);
771
772 apr_status_t CYPoolRelease_(void *data) {
773 id object(reinterpret_cast<id>(data));
774 [object release];
775 return APR_SUCCESS;
776 }
777
778 id CYPoolRelease(apr_pool_t *pool, id object) {
779 if (object == nil)
780 return nil;
781 else if (pool == NULL)
782 return [object autorelease];
783 else {
784 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
785 return object;
786 }
787 }
788
789 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
790 return (CFTypeRef) CYPoolRelease(pool, (id) object);
791 }
792
793 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
794 if (JSValueIsObjectOfClass(context, object, Instance_)) {
795 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
796 return data->GetValue();
797 }
798
799 JSValueRef exception(NULL);
800 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
801 CYThrow(context, exception);
802 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
803 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
804 }
805
806 JSStringRef CYCopyJSString(id value) {
807 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
808 }
809
810 JSStringRef CYCopyJSString(const char *value) {
811 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
812 }
813
814 JSStringRef CYCopyJSString(JSStringRef value) {
815 return value == NULL ? NULL : JSStringRetain(value);
816 }
817
818 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
819 if (JSValueIsNull(context, value))
820 return NULL;
821 JSValueRef exception(NULL);
822 JSStringRef string(JSValueToStringCopy(context, value, &exception));
823 CYThrow(context, exception);
824 return string;
825 }
826
827 class CYJSString {
828 private:
829 JSStringRef string_;
830
831 void Clear_() {
832 JSStringRelease(string_);
833 }
834
835 public:
836 CYJSString(const CYJSString &rhs) :
837 string_(CYCopyJSString(rhs.string_))
838 {
839 }
840
841 template <typename Arg0_>
842 CYJSString(Arg0_ arg0) :
843 string_(CYCopyJSString(arg0))
844 {
845 }
846
847 template <typename Arg0_, typename Arg1_>
848 CYJSString(Arg0_ arg0, Arg1_ arg1) :
849 string_(CYCopyJSString(arg0, arg1))
850 {
851 }
852
853 CYJSString &operator =(const CYJSString &rhs) {
854 Clear_();
855 string_ = CYCopyJSString(rhs.string_);
856 return *this;
857 }
858
859 ~CYJSString() {
860 Clear_();
861 }
862
863 void Clear() {
864 Clear_();
865 string_ = NULL;
866 }
867
868 operator JSStringRef() const {
869 return string_;
870 }
871 };
872
873 CFStringRef CYCopyCFString(JSStringRef value) {
874 return JSStringCopyCFString(kCFAllocatorDefault, value);
875 }
876
877 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
878 return CYCopyCFString(CYJSString(context, value));
879 }
880
881 double CYCastDouble(const char *value, size_t size) {
882 char *end;
883 double number(strtod(value, &end));
884 if (end != value + size)
885 return NAN;
886 return number;
887 }
888
889 double CYCastDouble(const char *value) {
890 return CYCastDouble(value, strlen(value));
891 }
892
893 double CYCastDouble(JSContextRef context, JSValueRef value) {
894 JSValueRef exception(NULL);
895 double number(JSValueToNumber(context, value, &exception));
896 CYThrow(context, exception);
897 return number;
898 }
899
900 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
901 double number(CYCastDouble(context, value));
902 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
903 }
904
905 CFStringRef CYCopyCFString(const char *value) {
906 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
907 }
908
909 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
910 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
911 }
912
913 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
914 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
915 }
916
917 bool CYCastBool(JSContextRef context, JSValueRef value) {
918 return JSValueToBoolean(context, value);
919 }
920
921 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
922 CFTypeRef object;
923 bool copy;
924
925 switch (JSType type = JSValueGetType(context, value)) {
926 case kJSTypeUndefined:
927 object = [WebUndefined undefined];
928 copy = false;
929 break;
930
931 case kJSTypeNull:
932 return NULL;
933 break;
934
935 case kJSTypeBoolean:
936 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
937 copy = false;
938 break;
939
940 case kJSTypeNumber:
941 object = CYCopyCFNumber(context, value);
942 copy = true;
943 break;
944
945 case kJSTypeString:
946 object = CYCopyCFString(context, value);
947 copy = true;
948 break;
949
950 case kJSTypeObject:
951 // XXX: this might could be more efficient
952 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
953 copy = false;
954 break;
955
956 default:
957 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
958 break;
959 }
960
961 if (cast != copy)
962 return object;
963 else if (copy)
964 return CYPoolRelease(pool, object);
965 else
966 return CFRetain(object);
967 }
968
969 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
970 return CYCFType(pool, context, value, true);
971 }
972
973 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
974 return CYCFType(pool, context, value, false);
975 }
976
977 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
978 CYPool pool;
979 size_t size(JSPropertyNameArrayGetCount(names));
980 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
981 for (size_t index(0); index != size; ++index)
982 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
983 return array;
984 }
985
986 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
987 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
988 }
989
990 void CYThrow(JSContextRef context, JSValueRef value) {
991 if (value == NULL)
992 return;
993 @throw CYCastNSObject(NULL, context, value);
994 }
995
996 JSValueRef CYJSNull(JSContextRef context) {
997 return JSValueMakeNull(context);
998 }
999
1000 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1001 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1002 }
1003
1004 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1005 return CYCastJSValue(context, CYJSString(value));
1006 }
1007
1008 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
1009 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
1010 }
1011
1012 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1013 JSValueRef exception(NULL);
1014 JSObjectRef object(JSValueToObject(context, value, &exception));
1015 CYThrow(context, exception);
1016 return object;
1017 }
1018
1019 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1020 JSValueRef exception(NULL);
1021 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1022 CYThrow(context, exception);
1023 return value;
1024 }
1025
1026 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1027 JSValueRef exception(NULL);
1028 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1029 CYThrow(context, exception);
1030 return value;
1031 }
1032
1033 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1034 JSValueRef exception(NULL);
1035 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1036 CYThrow(context, exception);
1037 }
1038
1039 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1040 if (exception == NULL)
1041 throw error;
1042 *exception = CYCastJSValue(context, error);
1043 }
1044
1045 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1046 JSValueRef exception(NULL);
1047 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1048 CYThrow(context, exception);
1049 return value;
1050 }
1051
1052 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1053 // XXX: this isn't actually correct
1054 return value != NULL && JSValueIsObject(context, value);
1055 }
1056
1057 @implementation CYJSObject
1058
1059 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1060 if ((self = [super init]) != nil) {
1061 object_ = object;
1062 context_ = context;
1063 } return self;
1064 }
1065
1066 - (NSObject *) cy$toJSON:(NSString *)key {
1067 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1068 if (!CYIsCallable(context_, toJSON))
1069 return [super cy$toJSON:key];
1070 else {
1071 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1072 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1073 // XXX: do I really want an NSNull here?!
1074 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1075 }
1076 }
1077
1078 - (NSString *) cy$toCYON {
1079 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1080 if (!CYIsCallable(context_, toCYON))
1081 return [super cy$toCYON];
1082 else {
1083 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1084 return CYCastNSString(NULL, CYJSString(context_, value));
1085 }
1086 }
1087
1088 - (NSUInteger) count {
1089 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1090 size_t size(JSPropertyNameArrayGetCount(names));
1091 JSPropertyNameArrayRelease(names);
1092 return size;
1093 }
1094
1095 - (id) objectForKey:(id)key {
1096 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1097 }
1098
1099 - (NSEnumerator *) keyEnumerator {
1100 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1101 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1102 JSPropertyNameArrayRelease(names);
1103 return enumerator;
1104 }
1105
1106 - (void) setObject:(id)object forKey:(id)key {
1107 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1108 }
1109
1110 - (void) removeObjectForKey:(id)key {
1111 JSValueRef exception(NULL);
1112 // XXX: this returns a bool... throw exception, or ignore?
1113 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1114 CYThrow(context_, exception);
1115 }
1116
1117 @end
1118
1119 @implementation CYJSArray
1120
1121 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1122 if ((self = [super init]) != nil) {
1123 object_ = object;
1124 context_ = context;
1125 } return self;
1126 }
1127
1128 - (NSUInteger) count {
1129 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1130 }
1131
1132 - (id) objectAtIndex:(NSUInteger)index {
1133 JSValueRef exception(NULL);
1134 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1135 CYThrow(context_, exception);
1136 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1137 }
1138
1139 @end
1140
1141 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1142 CYTry {
1143 CYPoolTry {
1144 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1145 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1146 } CYPoolCatch(NULL)
1147 } CYCatch
1148 }
1149
1150 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1151 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1152 const char *string(CYPoolCString(pool, json));
1153 [json release];
1154 return string;
1155 } else return NULL;
1156 }
1157
1158 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1159 CYPool pool;
1160
1161 CYTry {
1162 NSString *self(CYCastNSObject(pool, context, object));
1163 NSString *name(CYCastNSString(pool, property));
1164
1165 CYPoolTry {
1166 if (NSObject *data = [self cy$getProperty:name])
1167 return CYCastJSValue(context, data);
1168 } CYPoolCatch(NULL)
1169
1170 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1171 PropertyAttributes attributes(property);
1172 SEL sel(sel_registerName(attributes.Getter()));
1173 return CYSendMessage(pool, context, self, sel, 0, NULL, exception);
1174 }
1175
1176 return NULL;
1177 } CYCatch
1178 }
1179
1180 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1181 CYPool pool;
1182
1183 CYTry {
1184 NSString *self(CYCastNSObject(pool, context, object));
1185 NSString *name(CYCastNSString(pool, property));
1186 NSString *data(CYCastNSObject(pool, context, value));
1187
1188 CYPoolTry {
1189 if ([self cy$setProperty:name to:data])
1190 return true;
1191 } CYPoolCatch(NULL)
1192
1193 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1194 PropertyAttributes attributes(property);
1195 if (const char *setter = attributes.Setter()) {
1196 SEL sel(sel_registerName(setter));
1197 JSValueRef arguments[1] = {value};
1198 CYSendMessage(pool, context, self, sel, 1, arguments, exception);
1199 return true;
1200 }
1201 }
1202
1203 return false;
1204 } CYCatch
1205 }
1206
1207 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1208 CYTry {
1209 CYPoolTry {
1210 NSString *self(CYCastNSObject(NULL, context, object));
1211 NSString *name(CYCastNSString(NULL, property));
1212 return [self cy$deleteProperty:name];
1213 } CYPoolCatch(NULL)
1214 } CYCatch
1215 }
1216
1217 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1218 CYTry {
1219 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1220 return CYMakeInstance(context, [data->GetValue() alloc], true);
1221 } CYCatch
1222 }
1223
1224 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1225 Selector_privateData *data(new Selector_privateData(sel));
1226 return JSObjectMake(context, Selector_, data);
1227 }
1228
1229 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1230 Pointer_privateData *data(new Pointer_privateData(pointer));
1231 return JSObjectMake(context, Pointer_, data);
1232 }
1233
1234 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1235 Functor_privateData *data(new Functor_privateData(type, function));
1236 return JSObjectMake(context, Functor_, data);
1237 }
1238
1239 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1240 if (pool == NULL) {
1241 const char *string([CYCastNSString(NULL, value) UTF8String]);
1242 if (length != NULL)
1243 *length = strlen(string);
1244 return string;
1245 } else {
1246 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1247 char *string(new(pool) char[size]);
1248 JSStringGetUTF8CString(value, string, size);
1249 // XXX: this is ironic
1250 if (length != NULL)
1251 *length = strlen(string);
1252 return string;
1253 }
1254 }
1255
1256 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1257 if (!JSValueIsNull(context, value))
1258 return CYPoolCString(pool, CYJSString(context, value), length);
1259 else {
1260 if (length != NULL)
1261 *length = 0;
1262 return NULL;
1263 }
1264 }
1265
1266 // XXX: this macro is unhygenic
1267 #define CYCastCString(context, value) ({ \
1268 char *utf8; \
1269 if (value == NULL) \
1270 utf8 = NULL; \
1271 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1272 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1273 utf8 = reinterpret_cast<char *>(alloca(size)); \
1274 JSStringGetUTF8CString(string, utf8, size); \
1275 JSStringRelease(string); \
1276 } else \
1277 utf8 = NULL; \
1278 utf8; \
1279 })
1280
1281 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1282 switch (JSValueGetType(context, value)) {
1283 case kJSTypeNull:
1284 return NULL;
1285 /*case kJSTypeString:
1286 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1287 case kJSTypeObject:
1288 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1289 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1290 return data->value_;
1291 }*/
1292 default:
1293 double number(CYCastDouble(context, value));
1294 if (std::isnan(number))
1295 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1296 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1297 }
1298 }
1299
1300 template <typename Type_>
1301 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1302 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1303 }
1304
1305 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1306 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1307 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1308 return reinterpret_cast<SEL>(data->value_);
1309 } else
1310 return CYCastPointer<SEL>(context, value);
1311 }
1312
1313 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1314 switch (type->primitive) {
1315 case sig::boolean_P:
1316 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1317 break;
1318
1319 #define CYPoolFFI_(primitive, native) \
1320 case sig::primitive ## _P: \
1321 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1322 break;
1323
1324 CYPoolFFI_(uchar, unsigned char)
1325 CYPoolFFI_(char, char)
1326 CYPoolFFI_(ushort, unsigned short)
1327 CYPoolFFI_(short, short)
1328 CYPoolFFI_(ulong, unsigned long)
1329 CYPoolFFI_(long, long)
1330 CYPoolFFI_(uint, unsigned int)
1331 CYPoolFFI_(int, int)
1332 CYPoolFFI_(ulonglong, unsigned long long)
1333 CYPoolFFI_(longlong, long long)
1334 CYPoolFFI_(float, float)
1335 CYPoolFFI_(double, double)
1336
1337 case sig::object_P:
1338 case sig::typename_P:
1339 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1340 break;
1341
1342 case sig::selector_P:
1343 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1344 break;
1345
1346 case sig::pointer_P:
1347 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1348 break;
1349
1350 case sig::string_P:
1351 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1352 break;
1353
1354 case sig::struct_P: {
1355 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1356 bool aggregate(JSValueIsObject(context, value));
1357 for (size_t index(0); index != type->data.signature.count; ++index) {
1358 ffi_type *element(ffi->elements[index]);
1359 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1360 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1361 // XXX: alignment?
1362 base += element->size;
1363 }
1364 } break;
1365
1366 case sig::void_P:
1367 break;
1368
1369 default:
1370 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1371 _assert(false);
1372 }
1373 }
1374
1375 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1376 JSValueRef value;
1377
1378 switch (type->primitive) {
1379 case sig::boolean_P:
1380 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1381 break;
1382
1383 #define CYFromFFI_(primitive, native) \
1384 case sig::primitive ## _P: \
1385 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1386 break;
1387
1388 CYFromFFI_(uchar, unsigned char)
1389 CYFromFFI_(char, char)
1390 CYFromFFI_(ushort, unsigned short)
1391 CYFromFFI_(short, short)
1392 CYFromFFI_(ulong, unsigned long)
1393 CYFromFFI_(long, long)
1394 CYFromFFI_(uint, unsigned int)
1395 CYFromFFI_(int, int)
1396 CYFromFFI_(ulonglong, unsigned long long)
1397 CYFromFFI_(longlong, long long)
1398 CYFromFFI_(float, float)
1399 CYFromFFI_(double, double)
1400
1401 case sig::object_P:
1402 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1403 break;
1404
1405 case sig::typename_P:
1406 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1407 break;
1408
1409 case sig::selector_P:
1410 if (SEL sel = *reinterpret_cast<SEL *>(data))
1411 value = CYMakeSelector(context, sel);
1412 else goto null;
1413 break;
1414
1415 case sig::pointer_P:
1416 if (void *pointer = *reinterpret_cast<void **>(data))
1417 value = CYMakePointer(context, pointer);
1418 else goto null;
1419 break;
1420
1421 case sig::string_P:
1422 if (char *utf8 = *reinterpret_cast<char **>(data))
1423 value = CYCastJSValue(context, utf8);
1424 else goto null;
1425 break;
1426
1427 case sig::struct_P:
1428 value = CYMakeStruct(context, data, type, ffi, owner);
1429 break;
1430
1431 case sig::void_P:
1432 value = CYJSUndefined(context);
1433 break;
1434
1435 null:
1436 value = CYJSNull(context);
1437 break;
1438
1439 default:
1440 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1441 _assert(false);
1442 }
1443
1444 return value;
1445 }
1446
1447 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1448 Type_privateData *typical(internal->type_);
1449
1450 size_t length;
1451 const char *name(CYPoolCString(pool, property, &length));
1452 double number(CYCastDouble(name, length));
1453
1454 if (std::isnan(number)) {
1455 if (property == NULL)
1456 return false;
1457
1458 // XXX: implement!
1459 return false;
1460 } else {
1461 index = static_cast<ssize_t>(number);
1462 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1463 return false;
1464 }
1465
1466 base = reinterpret_cast<uint8_t *>(internal->value_);
1467 for (ssize_t local(0); local != index; ++local)
1468 base += typical->ffi_.elements[local]->size;
1469
1470 return true;
1471 }
1472
1473 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1474 CYTry {
1475 CYPool pool;
1476 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1477 Type_privateData *typical(internal->type_);
1478
1479 ssize_t index;
1480 uint8_t *base;
1481
1482 if (!Index_(pool, internal, property, index, base))
1483 return NULL;
1484
1485 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1486 } CYCatch
1487 }
1488
1489 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1490 CYTry {
1491 CYPool pool;
1492 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1493 Type_privateData *typical(internal->type_);
1494
1495 ssize_t index;
1496 uint8_t *base;
1497
1498 if (!Index_(pool, internal, property, index, base))
1499 return false;
1500
1501 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1502 return true;
1503 } CYCatch
1504 }
1505
1506 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1507 CYTry {
1508 if (setups + count != signature->count - 1)
1509 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1510
1511 size_t size(setups + count);
1512 void *values[size];
1513 memcpy(values, setup, sizeof(void *) * setups);
1514
1515 for (size_t index(setups); index != size; ++index) {
1516 sig::Element *element(&signature->elements[index + 1]);
1517 ffi_type *ffi(cif->arg_types[index]);
1518 // XXX: alignment?
1519 values[index] = new(pool) uint8_t[ffi->size];
1520 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1521 }
1522
1523 uint8_t value[cif->rtype->size];
1524 ffi_call(cif, function, value, values);
1525
1526 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1527 } CYCatch
1528 }
1529
1530 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1531 ffoData *data(reinterpret_cast<ffoData *>(arg));
1532
1533 JSContextRef context(data->context_);
1534
1535 size_t count(data->cif_.nargs);
1536 JSValueRef values[count];
1537
1538 for (size_t index(0); index != count; ++index)
1539 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1540
1541 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1542 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1543 }
1544
1545 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1546 // XXX: in case of exceptions this will leak
1547 ffoData *data(new ffoData(type));
1548
1549 ffi_closure *closure;
1550 _syscall(closure = (ffi_closure *) mmap(
1551 NULL, sizeof(ffi_closure),
1552 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1553 -1, 0
1554 ));
1555
1556 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1557 _assert(status == FFI_OK);
1558
1559 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1560
1561 data->value_ = closure;
1562
1563 data->context_ = CYGetJSContext();
1564 data->function_ = function;
1565
1566 return JSObjectMake(context, Functor_, data);
1567 }
1568
1569 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1570 CYTry {
1571 CYPool pool;
1572 NSString *name(CYCastNSString(pool, property));
1573 if (Class _class = NSClassFromString(name))
1574 return CYMakeInstance(context, _class, true);
1575 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1576 switch ([[entry objectAtIndex:0] intValue]) {
1577 case 0:
1578 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1579 case 1:
1580 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1581 case 2:
1582 // XXX: this is horrendously inefficient
1583 sig::Signature signature;
1584 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1585 ffi_cif cif;
1586 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1587 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1588 }
1589 return NULL;
1590 } CYCatch
1591 }
1592
1593 bool stret(ffi_type *ffi_type) {
1594 return ffi_type->type == FFI_TYPE_STRUCT && (
1595 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1596 struct_forward_array[ffi_type->size] != 0
1597 );
1598 }
1599
1600 extern "C" {
1601 int *_NSGetArgc(void);
1602 char ***_NSGetArgv(void);
1603 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1604 }
1605
1606 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1607 CYTry {
1608 NSLog(@"%s", CYCastCString(context, arguments[0]));
1609 return CYJSUndefined(context);
1610 } CYCatch
1611 }
1612
1613 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1614 CYTry {
1615 CYPool pool;
1616 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1617 int argc(*_NSGetArgc());
1618 char **argv(*_NSGetArgv());
1619 for (int i(0); i != argc; ++i)
1620 NSLog(@"argv[%i]=%s", i, argv[i]);
1621 _pooled
1622 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1623 } CYCatch
1624 }
1625
1626 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1627 const char *type;
1628
1629 Class _class(object_getClass(self));
1630 if (Method method = class_getInstanceMethod(_class, _cmd))
1631 type = method_getTypeEncoding(method);
1632 else {
1633 CYPoolTry {
1634 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1635 if (method == nil)
1636 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1637 type = CYPoolCString(pool, [method _typeString]);
1638 } CYPoolCatch(NULL)
1639 }
1640
1641 void *setup[2];
1642 setup[0] = &self;
1643 setup[1] = &_cmd;
1644
1645 sig::Signature signature;
1646 sig::Parse(pool, &signature, type);
1647
1648 ffi_cif cif;
1649 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1650
1651 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1652 return CYCallFunction(pool, context, 2, setup, count, arguments, exception, &signature, &cif, function);
1653 }
1654
1655 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1656 CYPool pool;
1657
1658 id self;
1659 SEL _cmd;
1660
1661 CYTry {
1662 if (count < 2)
1663 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1664
1665 self = CYCastNSObject(pool, context, arguments[0]);
1666 if (self == nil)
1667 return CYJSNull(context);
1668
1669 _cmd = CYCastSEL(context, arguments[1]);
1670 } CYCatch
1671
1672 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, exception);
1673 }
1674
1675 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1676 JSValueRef setup[count + 2];
1677 setup[0] = _this;
1678 setup[1] = object;
1679 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
1680 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1681 }
1682
1683 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1684 CYPool pool;
1685 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1686 return CYCallFunction(pool, context, 0, NULL, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1687 }
1688
1689 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1690 CYTry {
1691 if (count != 1)
1692 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1693 const char *name(CYCastCString(context, arguments[0]));
1694 return CYMakeSelector(context, sel_registerName(name));
1695 } CYCatch
1696 }
1697
1698 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1699 CYTry {
1700 if (count != 2)
1701 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1702 const char *type(CYCastCString(context, arguments[1]));
1703 JSValueRef exception(NULL);
1704 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1705 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1706 return CYMakeFunctor(context, function, type);
1707 } else if (exception != NULL) {
1708 return NULL;
1709 } else {
1710 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1711 return CYMakeFunctor(context, function, type);
1712 }
1713 } CYCatch
1714 }
1715
1716 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1717 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1718 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1719 }
1720
1721 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1722 return Function_;
1723 }
1724
1725 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1726 CYTry {
1727 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1728 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1729 } CYCatch
1730 }
1731
1732 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1733 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1734 }
1735
1736 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1737 CYTry {
1738 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1739 char string[32];
1740 sprintf(string, "%p", data->value_);
1741 return CYCastJSValue(context, string);
1742 } CYCatch
1743 }
1744
1745 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1746 CYTry {
1747 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1748 CYPoolTry {
1749 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1750 } CYPoolCatch(NULL)
1751 } CYCatch
1752 }
1753
1754 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1755 CYTry {
1756 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1757 CYPoolTry {
1758 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1759 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1760 } CYPoolCatch(NULL)
1761 } CYCatch
1762 }
1763
1764 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1765 CYTry {
1766 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1767 CYPoolTry {
1768 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1769 } CYPoolCatch(NULL)
1770 } CYCatch
1771 }
1772
1773 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1774 CYTry {
1775 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1776 return CYCastJSValue(context, sel_getName(data->GetValue()));
1777 } CYCatch
1778 }
1779
1780 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1781 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1782 }
1783
1784 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1785 CYTry {
1786 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1787 const char *name(sel_getName(data->GetValue()));
1788 CYPoolTry {
1789 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1790 } CYPoolCatch(NULL)
1791 } CYCatch
1792 }
1793
1794 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1795 CYTry {
1796 if (count != 2)
1797 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1798 CYPool pool;
1799 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1800 Class _class(CYCastNSObject(pool, context, arguments[0]));
1801 bool instance(CYCastBool(context, arguments[1]));
1802 SEL sel(data->GetValue());
1803 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1804 return CYCastJSValue(context, method_getTypeEncoding(method));
1805 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1806 return CYCastJSValue(context, CYJSString(type));
1807 else
1808 return CYJSNull(context);
1809 } CYCatch
1810 }
1811
1812 static JSStaticValue Pointer_staticValues[2] = {
1813 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1814 {NULL, NULL, NULL, 0}
1815 };
1816
1817 static JSStaticFunction Pointer_staticFunctions[4] = {
1818 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1819 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1820 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1821 {NULL, NULL, 0}
1822 };
1823
1824 /*static JSStaticValue Selector_staticValues[2] = {
1825 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1826 {NULL, NULL, NULL, 0}
1827 };*/
1828
1829 static JSStaticFunction Instance_staticFunctions[4] = {
1830 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1831 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1832 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1833 {NULL, NULL, 0}
1834 };
1835
1836 static JSStaticFunction Selector_staticFunctions[5] = {
1837 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1838 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1839 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1840 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1841 {NULL, NULL, 0}
1842 };
1843
1844 CYDriver::CYDriver(const std::string &filename) :
1845 state_(CYClear),
1846 data_(NULL),
1847 size_(0),
1848 filename_(filename),
1849 source_(NULL)
1850 {
1851 ScannerInit();
1852 }
1853
1854 CYDriver::~CYDriver() {
1855 ScannerDestroy();
1856 }
1857
1858 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1859 CYDriver::Error error;
1860 error.location_ = location;
1861 error.message_ = message;
1862 driver.errors_.push_back(error);
1863 }
1864
1865 void CYSetArgs(int argc, const char *argv[]) {
1866 JSContextRef context(CYGetJSContext());
1867 JSValueRef args[argc];
1868 for (int i(0); i != argc; ++i)
1869 args[i] = CYCastJSValue(context, argv[i]);
1870 JSValueRef exception(NULL);
1871 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1872 CYThrow(context, exception);
1873 CYSetProperty(context, System_, CYJSString("args"), array);
1874 }
1875
1876 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1877 return JSContextGetGlobalObject(context);
1878 }
1879
1880 MSInitialize { _pooled
1881 apr_initialize();
1882
1883 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1884
1885 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1886
1887 JSClassDefinition definition;
1888
1889 definition = kJSClassDefinitionEmpty;
1890 definition.className = "Pointer";
1891 definition.staticValues = Pointer_staticValues;
1892 definition.staticFunctions = Pointer_staticFunctions;
1893 definition.finalize = &CYData::Finalize;
1894 Pointer_ = JSClassCreate(&definition);
1895
1896 definition = kJSClassDefinitionEmpty;
1897 definition.className = "Functor";
1898 definition.staticValues = Pointer_staticValues;
1899 definition.staticFunctions = Pointer_staticFunctions;
1900 definition.callAsFunction = &Functor_callAsFunction;
1901 definition.finalize = &CYData::Finalize;
1902 Functor_ = JSClassCreate(&definition);
1903
1904 definition = kJSClassDefinitionEmpty;
1905 definition.className = "Struct";
1906 definition.getProperty = &Struct_getProperty;
1907 definition.setProperty = &Struct_setProperty;
1908 definition.finalize = &CYData::Finalize;
1909 Struct_ = JSClassCreate(&definition);
1910
1911 definition = kJSClassDefinitionEmpty;
1912 definition.className = "Selector";
1913 definition.staticValues = Pointer_staticValues;
1914 //definition.staticValues = Selector_staticValues;
1915 definition.staticFunctions = Selector_staticFunctions;
1916 definition.callAsFunction = &Selector_callAsFunction;
1917 definition.finalize = &CYData::Finalize;
1918 Selector_ = JSClassCreate(&definition);
1919
1920 definition = kJSClassDefinitionEmpty;
1921 definition.className = "Instance";
1922 definition.staticValues = Pointer_staticValues;
1923 definition.staticFunctions = Instance_staticFunctions;
1924 definition.getProperty = &Instance_getProperty;
1925 definition.setProperty = &Instance_setProperty;
1926 definition.deleteProperty = &Instance_deleteProperty;
1927 definition.callAsConstructor = &Instance_callAsConstructor;
1928 definition.finalize = &CYData::Finalize;
1929 Instance_ = JSClassCreate(&definition);
1930
1931 definition = kJSClassDefinitionEmpty;
1932 definition.className = "Runtime";
1933 definition.getProperty = &Runtime_getProperty;
1934 Runtime_ = JSClassCreate(&definition);
1935
1936 definition = kJSClassDefinitionEmpty;
1937 //definition.getProperty = &Global_getProperty;
1938 JSClassRef Global(JSClassCreate(&definition));
1939
1940 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1941 Context_ = context;
1942
1943 JSObjectRef global(CYGetGlobalObject(context));
1944
1945 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1946 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1947
1948 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1949 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1950
1951 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1952 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1953
1954 System_ = JSObjectMake(context, NULL, NULL);
1955 CYSetProperty(context, global, CYJSString("system"), System_);
1956 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1957 //CYSetProperty(context, System_, CYJSString("global"), global);
1958
1959 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1960
1961 length_ = JSStringCreateWithUTF8CString("length");
1962 message_ = JSStringCreateWithUTF8CString("message");
1963 name_ = JSStringCreateWithUTF8CString("name");
1964 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1965 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1966
1967 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1968 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1969 }