]> git.saurik.com Git - cycript.git/blob - Library.mm
Support -p and <script> at the same time.
[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/un.h>
62
63 #include <sys/mman.h>
64
65 #include <iostream>
66 #include <ext/stdio_filebuf.h>
67 #include <set>
68 #include <map>
69
70 #include <sstream>
71 #include <cmath>
72
73 #include "Parser.hpp"
74 #include "Cycript.tab.hh"
75
76 #include <fcntl.h>
77
78 #include <apr-1/apr_thread_proc.h>
79
80 #undef _assert
81 #undef _trace
82
83 #define _assert(test) do { \
84 if (!(test)) \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
86 } while (false)
87
88 #define _trace() do { \
89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
90 } while (false)
91
92 #define CYPoolTry { \
93 id _saved(nil); \
94 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
95 @try
96 #define CYPoolCatch(value) \
97 @catch (NSException *error) { \
98 _saved = [error retain]; \
99 @throw; \
100 return value; \
101 } @finally { \
102 [_pool release]; \
103 if (_saved != nil) \
104 [_saved autorelease]; \
105 } \
106 }
107
108 static JSGlobalContextRef Context_;
109 static JSObjectRef System_;
110
111 static JSClassRef Functor_;
112 static JSClassRef Instance_;
113 static JSClassRef Pointer_;
114 static JSClassRef Runtime_;
115 static JSClassRef Selector_;
116 static JSClassRef Struct_;
117 static JSClassRef Type_;
118
119 static JSObjectRef Array_;
120 static JSObjectRef Function_;
121
122 static JSStringRef Result_;
123
124 static JSStringRef length_;
125 static JSStringRef message_;
126 static JSStringRef name_;
127 static JSStringRef toCYON_;
128 static JSStringRef toJSON_;
129
130 static Class NSCFBoolean_;
131
132 static NSArray *Bridge_;
133
134 struct CYData {
135 apr_pool_t *pool_;
136
137 virtual ~CYData() {
138 }
139
140 static void *operator new(size_t size, apr_pool_t *pool) {
141 void *data(apr_palloc(pool, size));
142 reinterpret_cast<CYData *>(data)->pool_ = pool;
143 return data;
144 }
145
146 static void *operator new(size_t size) {
147 apr_pool_t *pool;
148 apr_pool_create(&pool, NULL);
149 return operator new(size, pool);
150 }
151
152 static void operator delete(void *data) {
153 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
154 }
155
156 static void Finalize(JSObjectRef object) {
157 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
158 }
159 };
160
161 struct CYValue :
162 CYData
163 {
164 void *value_;
165
166 CYValue() {
167 }
168
169 CYValue(void *value) :
170 value_(value)
171 {
172 }
173 };
174
175 struct Selector_privateData :
176 CYValue
177 {
178 Selector_privateData(SEL value) :
179 CYValue(value)
180 {
181 }
182
183 SEL GetValue() const {
184 return reinterpret_cast<SEL>(value_);
185 }
186 };
187
188 struct Instance :
189 CYValue
190 {
191 enum Flags {
192 None = 0,
193 Transient = (1 << 0),
194 Uninitialized = (1 << 1),
195 };
196
197 Flags flags_;
198
199 Instance(id value, Flags flags) :
200 CYValue(value),
201 flags_(flags)
202 {
203 }
204
205 virtual ~Instance() {
206 if ((flags_ & Transient) == 0)
207 // XXX: does this handle background threads correctly?
208 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
209 }
210
211 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
212 return JSObjectMake(context, Instance_, new Instance(object, flags));
213 }
214
215 id GetValue() const {
216 return reinterpret_cast<id>(value_);
217 }
218
219 bool IsUninitialized() const {
220 return (flags_ & Uninitialized) != 0;
221 }
222 };
223
224 namespace sig {
225
226 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
227
228 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
229 lhs.name = apr_pstrdup(pool, rhs.name);
230 if (rhs.type == NULL)
231 lhs.type = NULL;
232 else {
233 lhs.type = new(pool) Type;
234 Copy(pool, *lhs.type, *rhs.type);
235 }
236 lhs.offset = rhs.offset;
237 }
238
239 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
240 size_t count(rhs.count);
241 lhs.count = count;
242 lhs.elements = new(pool) Element[count];
243 for (size_t index(0); index != count; ++index)
244 Copy(pool, lhs.elements[index], rhs.elements[index]);
245 }
246
247 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
248 lhs.primitive = rhs.primitive;
249 lhs.name = apr_pstrdup(pool, rhs.name);
250 lhs.flags = rhs.flags;
251
252 if (sig::IsAggregate(rhs.primitive))
253 Copy(pool, lhs.data.signature, rhs.data.signature);
254 else {
255 if (rhs.data.data.type != NULL) {
256 lhs.data.data.type = new(pool) Type;
257 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
258 }
259
260 lhs.data.data.size = rhs.data.data.size;
261 }
262 }
263
264 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
265 lhs.size = rhs.size;
266 lhs.alignment = rhs.alignment;
267 lhs.type = rhs.type;
268 if (rhs.elements == NULL)
269 lhs.elements = NULL;
270 else {
271 size_t count(0);
272 while (rhs.elements[count] != NULL)
273 ++count;
274
275 lhs.elements = new(pool) ffi_type *[count + 1];
276 lhs.elements[count] = NULL;
277
278 for (size_t index(0); index != count; ++index) {
279 // XXX: if these are libffi native then you can just take them
280 ffi_type *ffi(new(pool) ffi_type);
281 lhs.elements[index] = ffi;
282 sig::Copy(pool, *ffi, *rhs.elements[index]);
283 }
284 }
285 }
286
287 }
288
289 struct CStringMapLess :
290 std::binary_function<const char *, const char *, bool>
291 {
292 _finline bool operator ()(const char *lhs, const char *rhs) const {
293 return strcmp(lhs, rhs) < 0;
294 }
295 };
296
297 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
298 if (name == NULL)
299 return;
300
301 CYPoolTry {
302 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
303 switch ([[entry objectAtIndex:0] intValue]) {
304 case 0: {
305 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
306 } break;
307
308 case 1: {
309 sig::Signature signature;
310 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
311 type = signature.elements[0].type;
312 } break;
313 }
314 } CYPoolCatch()
315 }
316
317 struct Type_privateData :
318 CYData
319 {
320 ffi_type *ffi_;
321 sig::Type *type_;
322
323 void Set(sig::Type *type) {
324 type_ = new(pool_) sig::Type;
325 sig::Copy(pool_, *type_, *type);
326 }
327
328 Type_privateData(const char *type) :
329 ffi_(NULL)
330 {
331 sig::Signature signature;
332 sig::Parse(pool_, &signature, type, &Structor_);
333 type_ = signature.elements[0].type;
334 }
335
336 Type_privateData(sig::Type *type) :
337 ffi_(NULL)
338 {
339 if (type != NULL)
340 Set(type);
341 }
342
343 Type_privateData(sig::Type *type, ffi_type *ffi) {
344 ffi_ = new(pool_) ffi_type;
345 sig::Copy(pool_, *ffi_, *ffi);
346 Set(type);
347 }
348
349 ffi_type *GetFFI() {
350 if (ffi_ == NULL) {
351 ffi_ = new(pool_) ffi_type;
352
353 sig::Element element;
354 element.name = NULL;
355 element.type = type_;
356 element.offset = 0;
357
358 sig::Signature signature;
359 signature.elements = &element;
360 signature.count = 1;
361
362 ffi_cif cif;
363 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
364 *ffi_ = *cif.rtype;
365 }
366
367 return ffi_;
368 }
369 };
370
371 struct Pointer :
372 CYValue
373 {
374 JSObjectRef owner_;
375 Type_privateData *type_;
376
377 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
378 CYValue(value),
379 owner_(owner),
380 type_(new(pool_) Type_privateData(type))
381 {
382 }
383 };
384
385 struct Struct_privateData :
386 CYValue
387 {
388 JSObjectRef owner_;
389 Type_privateData *type_;
390
391 Struct_privateData(JSObjectRef owner) :
392 owner_(owner)
393 {
394 }
395 };
396
397 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
398 static TypeMap Types_;
399
400 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
401 Struct_privateData *internal(new Struct_privateData(owner));
402 apr_pool_t *pool(internal->pool_);
403 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
404 internal->type_ = typical;
405
406 if (owner != NULL)
407 internal->value_ = data;
408 else {
409 size_t size(typical->GetFFI()->size);
410 void *copy(apr_palloc(internal->pool_, size));
411 memcpy(copy, data, size);
412 internal->value_ = copy;
413 }
414
415 return JSObjectMake(context, Struct_, internal);
416 }
417
418 struct Functor_privateData :
419 CYValue
420 {
421 sig::Signature signature_;
422 ffi_cif cif_;
423
424 Functor_privateData(const char *type, void (*value)()) :
425 CYValue(reinterpret_cast<void *>(value))
426 {
427 sig::Parse(pool_, &signature_, type, &Structor_);
428 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
429 }
430 };
431
432 struct ffoData :
433 Functor_privateData
434 {
435 JSContextRef context_;
436 JSObjectRef function_;
437
438 ffoData(const char *type) :
439 Functor_privateData(type, NULL)
440 {
441 }
442 };
443
444 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
445 Instance::Flags flags;
446
447 if (transient)
448 flags = Instance::Transient;
449 else {
450 flags = Instance::None;
451 object = [object retain];
452 }
453
454 return Instance::Make(context, object, flags);
455 }
456
457 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
458 if (pool == NULL)
459 return [value UTF8String];
460 else {
461 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
462 char *string(new(pool) char[size]);
463 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
464 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
465 return string;
466 }
467 }
468
469 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
470 return JSValueMakeBoolean(context, value);
471 }
472
473 JSValueRef CYCastJSValue(JSContextRef context, double value) {
474 return JSValueMakeNumber(context, value);
475 }
476
477 #define CYCastJSValue_(Type_) \
478 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
479 return JSValueMakeNumber(context, static_cast<double>(value)); \
480 }
481
482 CYCastJSValue_(int)
483 CYCastJSValue_(unsigned int)
484 CYCastJSValue_(long int)
485 CYCastJSValue_(long unsigned int)
486 CYCastJSValue_(long long int)
487 CYCastJSValue_(long long unsigned int)
488
489 JSValueRef CYJSUndefined(JSContextRef context) {
490 return JSValueMakeUndefined(context);
491 }
492
493 bool CYGetIndex(const char *value, ssize_t &index) {
494 if (value[0] != '0') {
495 char *end;
496 index = strtol(value, &end, 10);
497 if (value + strlen(value) == end)
498 return true;
499 } else if (value[1] == '\0') {
500 index = 0;
501 return true;
502 }
503
504 return false;
505 }
506
507 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
508 return CYGetIndex(CYPoolCString(pool, value), index);
509 }
510
511 @interface NSMethodSignature (Cycript)
512 - (NSString *) _typeString;
513 @end
514
515 @interface NSObject (Cycript)
516
517 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
518 - (JSType) cy$JSType;
519
520 - (NSObject *) cy$toJSON:(NSString *)key;
521 - (NSString *) cy$toCYON;
522 - (NSString *) cy$toKey;
523
524 - (NSObject *) cy$getProperty:(NSString *)name;
525 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
526 - (bool) cy$deleteProperty:(NSString *)name;
527
528 @end
529
530 @protocol Cycript
531 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
532 @end
533
534 @interface NSString (Cycript)
535 - (void *) cy$symbol;
536 @end
537
538 struct PropertyAttributes {
539 CYPool pool_;
540
541 const char *name;
542
543 const char *variable;
544
545 const char *getter_;
546 const char *setter_;
547
548 bool readonly;
549 bool copy;
550 bool retain;
551 bool nonatomic;
552 bool dynamic;
553 bool weak;
554 bool garbage;
555
556 PropertyAttributes(objc_property_t property) :
557 variable(NULL),
558 getter_(NULL),
559 setter_(NULL),
560 readonly(false),
561 copy(false),
562 retain(false),
563 nonatomic(false),
564 dynamic(false),
565 weak(false),
566 garbage(false)
567 {
568 name = property_getName(property);
569 const char *attributes(property_getAttributes(property));
570
571 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
572 switch (*token) {
573 case 'R': readonly = true; break;
574 case 'C': copy = true; break;
575 case '&': retain = true; break;
576 case 'N': nonatomic = true; break;
577 case 'G': getter_ = token + 1; break;
578 case 'S': setter_ = token + 1; break;
579 case 'V': variable = token + 1; break;
580 }
581 }
582
583 /*if (variable == NULL) {
584 variable = property_getName(property);
585 size_t size(strlen(variable));
586 char *name(new(pool_) char[size + 2]);
587 name[0] = '_';
588 memcpy(name + 1, variable, size);
589 name[size + 1] = '\0';
590 variable = name;
591 }*/
592 }
593
594 const char *Getter() {
595 if (getter_ == NULL)
596 getter_ = apr_pstrdup(pool_, name);
597 return getter_;
598 }
599
600 const char *Setter() {
601 if (setter_ == NULL && !readonly) {
602 size_t length(strlen(name));
603
604 char *temp(new(pool_) char[length + 5]);
605 temp[0] = 's';
606 temp[1] = 'e';
607 temp[2] = 't';
608
609 if (length != 0) {
610 temp[3] = toupper(name[0]);
611 memcpy(temp + 4, name + 1, length - 1);
612 }
613
614 temp[length + 3] = ':';
615 temp[length + 4] = '\0';
616 setter_ = temp;
617 }
618
619 return setter_;
620 }
621
622 };
623
624 @implementation NSObject (Cycript)
625
626 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
627 return CYMakeInstance(context, self, false);
628 }
629
630 - (JSType) cy$JSType {
631 return kJSTypeObject;
632 }
633
634 - (NSObject *) cy$toJSON:(NSString *)key {
635 return [self description];
636 }
637
638 - (NSString *) cy$toCYON {
639 return [[self cy$toJSON:@""] cy$toCYON];
640 }
641
642 - (NSString *) cy$toKey {
643 return [self cy$toCYON];
644 }
645
646 - (NSObject *) cy$getProperty:(NSString *)name {
647 /*if (![name isEqualToString:@"prototype"])
648 NSLog(@"get:%@", name);*/
649 return nil;
650 }
651
652 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
653 //NSLog(@"set:%@", name);
654 return false;
655 }
656
657 - (bool) cy$deleteProperty:(NSString *)name {
658 //NSLog(@"delete:%@", name);
659 return false;
660 }
661
662 @end
663
664 @implementation WebUndefined (Cycript)
665
666 - (JSType) cy$JSType {
667 return kJSTypeUndefined;
668 }
669
670 - (NSObject *) cy$toJSON:(NSString *)key {
671 return self;
672 }
673
674 - (NSString *) cy$toCYON {
675 return @"undefined";
676 }
677
678 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
679 return CYJSUndefined(context);
680 }
681
682 @end
683
684 @implementation NSNull (Cycript)
685
686 - (JSType) cy$JSType {
687 return kJSTypeNull;
688 }
689
690 - (NSObject *) cy$toJSON:(NSString *)key {
691 return self;
692 }
693
694 - (NSString *) cy$toCYON {
695 return @"null";
696 }
697
698 @end
699
700 @implementation NSArray (Cycript)
701
702 - (NSString *) cy$toCYON {
703 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
704 [json appendString:@"["];
705
706 bool comma(false);
707 for (id object in self) {
708 if (comma)
709 [json appendString:@","];
710 else
711 comma = true;
712 if ([object cy$JSType] != kJSTypeUndefined)
713 [json appendString:[object cy$toCYON]];
714 else {
715 [json appendString:@","];
716 comma = false;
717 }
718 }
719
720 [json appendString:@"]"];
721 return json;
722 }
723
724 - (NSObject *) cy$getProperty:(NSString *)name {
725 if ([name isEqualToString:@"length"])
726 return [NSNumber numberWithUnsignedInteger:[self count]];
727
728 ssize_t index;
729 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
730 return [super cy$getProperty:name];
731 else
732 return [self objectAtIndex:index];
733 }
734
735 @end
736
737 @implementation NSMutableArray (Cycript)
738
739 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
740 ssize_t index;
741 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
742 return [super cy$setProperty:name to:value];
743 else {
744 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
745 return true;
746 }
747 }
748
749 - (bool) cy$deleteProperty:(NSString *)name {
750 ssize_t index;
751 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
752 return [super cy$deleteProperty:name];
753 else {
754 [self removeObjectAtIndex:index];
755 return true;
756 }
757 }
758
759 @end
760
761 @implementation NSDictionary (Cycript)
762
763 - (NSString *) cy$toCYON {
764 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
765 [json appendString:@"{"];
766
767 bool comma(false);
768 for (id key in self) {
769 if (comma)
770 [json appendString:@","];
771 else
772 comma = true;
773 [json appendString:[key cy$toKey]];
774 [json appendString:@":"];
775 NSObject *object([self objectForKey:key]);
776 [json appendString:[object cy$toCYON]];
777 }
778
779 [json appendString:@"}"];
780 return json;
781 }
782
783 - (NSObject *) cy$getProperty:(NSString *)name {
784 return [self objectForKey:name];
785 }
786
787 @end
788
789 @implementation NSMutableDictionary (Cycript)
790
791 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
792 [self setObject:(value ?: [NSNull null]) forKey:name];
793 return true;
794 }
795
796 - (bool) cy$deleteProperty:(NSString *)name {
797 if ([self objectForKey:name] == nil)
798 return false;
799 else {
800 [self removeObjectForKey:name];
801 return true;
802 }
803 }
804
805 @end
806
807 @implementation NSNumber (Cycript)
808
809 - (JSType) cy$JSType {
810 // XXX: this just seems stupid
811 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
812 }
813
814 - (NSObject *) cy$toJSON:(NSString *)key {
815 return self;
816 }
817
818 - (NSString *) cy$toCYON {
819 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
820 }
821
822 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
823 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
824 }
825
826 @end
827
828 @implementation NSString (Cycript)
829
830 - (JSType) cy$JSType {
831 return kJSTypeString;
832 }
833
834 - (NSObject *) cy$toJSON:(NSString *)key {
835 return self;
836 }
837
838 - (NSString *) cy$toCYON {
839 // XXX: this should use the better code from Output.cpp
840 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
841
842 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
843 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
844 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
845 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
846 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
847
848 CFStringInsert(json, 0, CFSTR("\""));
849 CFStringAppend(json, CFSTR("\""));
850
851 return [reinterpret_cast<const NSString *>(json) autorelease];
852 }
853
854 - (NSString *) cy$toKey {
855 const char *value([self UTF8String]);
856 size_t size(strlen(value));
857
858 if (size == 0)
859 goto cyon;
860
861 if (DigitRange_[value[0]]) {
862 ssize_t index;
863 if (!CYGetIndex(NULL, self, index) || index < 0)
864 goto cyon;
865 } else {
866 if (!WordStartRange_[value[0]])
867 goto cyon;
868 for (size_t i(1); i != size; ++i)
869 if (!WordEndRange_[value[i]])
870 goto cyon;
871 }
872
873 return self;
874
875 cyon:
876 return [self cy$toCYON];
877 }
878
879 - (void *) cy$symbol {
880 CYPool pool;
881 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
882 }
883
884 @end
885
886 @interface CYJSObject : NSDictionary {
887 JSObjectRef object_;
888 JSContextRef context_;
889 }
890
891 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
892
893 - (NSString *) cy$toJSON:(NSString *)key;
894
895 - (NSUInteger) count;
896 - (id) objectForKey:(id)key;
897 - (NSEnumerator *) keyEnumerator;
898 - (void) setObject:(id)object forKey:(id)key;
899 - (void) removeObjectForKey:(id)key;
900
901 @end
902
903 @interface CYJSArray : NSArray {
904 JSObjectRef object_;
905 JSContextRef context_;
906 }
907
908 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
909
910 - (NSUInteger) count;
911 - (id) objectAtIndex:(NSUInteger)index;
912
913 @end
914
915 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
916 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
917 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
918
919 #define CYTry \
920 @try
921 #define CYCatch \
922 @catch (id error) { \
923 CYThrow(context, error, exception); \
924 return NULL; \
925 }
926
927 void CYThrow(JSContextRef context, JSValueRef value);
928
929 apr_status_t CYPoolRelease_(void *data) {
930 id object(reinterpret_cast<id>(data));
931 [object release];
932 return APR_SUCCESS;
933 }
934
935 id CYPoolRelease(apr_pool_t *pool, id object) {
936 if (object == nil)
937 return nil;
938 else if (pool == NULL)
939 return [object autorelease];
940 else {
941 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
942 return object;
943 }
944 }
945
946 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
947 return (CFTypeRef) CYPoolRelease(pool, (id) object);
948 }
949
950 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
951 JSValueRef exception(NULL);
952 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
953 CYThrow(context, exception);
954 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
955 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
956 }
957
958 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
959 if (!JSValueIsObjectOfClass(context, object, Instance_))
960 return CYCastNSObject_(pool, context, object);
961 else {
962 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
963 return data->GetValue();
964 }
965 }
966
967 JSStringRef CYCopyJSString(id value) {
968 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
969 }
970
971 JSStringRef CYCopyJSString(const char *value) {
972 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
973 }
974
975 JSStringRef CYCopyJSString(JSStringRef value) {
976 return value == NULL ? NULL : JSStringRetain(value);
977 }
978
979 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
980 if (JSValueIsNull(context, value))
981 return NULL;
982 JSValueRef exception(NULL);
983 JSStringRef string(JSValueToStringCopy(context, value, &exception));
984 CYThrow(context, exception);
985 return string;
986 }
987
988 class CYJSString {
989 private:
990 JSStringRef string_;
991
992 void Clear_() {
993 if (string_ != NULL)
994 JSStringRelease(string_);
995 }
996
997 public:
998 CYJSString(const CYJSString &rhs) :
999 string_(CYCopyJSString(rhs.string_))
1000 {
1001 }
1002
1003 template <typename Arg0_>
1004 CYJSString(Arg0_ arg0) :
1005 string_(CYCopyJSString(arg0))
1006 {
1007 }
1008
1009 template <typename Arg0_, typename Arg1_>
1010 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1011 string_(CYCopyJSString(arg0, arg1))
1012 {
1013 }
1014
1015 CYJSString &operator =(const CYJSString &rhs) {
1016 Clear_();
1017 string_ = CYCopyJSString(rhs.string_);
1018 return *this;
1019 }
1020
1021 ~CYJSString() {
1022 Clear_();
1023 }
1024
1025 void Clear() {
1026 Clear_();
1027 string_ = NULL;
1028 }
1029
1030 operator JSStringRef() const {
1031 return string_;
1032 }
1033 };
1034
1035 CFStringRef CYCopyCFString(JSStringRef value) {
1036 return JSStringCopyCFString(kCFAllocatorDefault, value);
1037 }
1038
1039 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1040 return CYCopyCFString(CYJSString(context, value));
1041 }
1042
1043 double CYCastDouble(const char *value, size_t size) {
1044 char *end;
1045 double number(strtod(value, &end));
1046 if (end != value + size)
1047 return NAN;
1048 return number;
1049 }
1050
1051 double CYCastDouble(const char *value) {
1052 return CYCastDouble(value, strlen(value));
1053 }
1054
1055 double CYCastDouble(JSContextRef context, JSValueRef value) {
1056 JSValueRef exception(NULL);
1057 double number(JSValueToNumber(context, value, &exception));
1058 CYThrow(context, exception);
1059 return number;
1060 }
1061
1062 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1063 double number(CYCastDouble(context, value));
1064 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1065 }
1066
1067 CFStringRef CYCopyCFString(const char *value) {
1068 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1069 }
1070
1071 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1072 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1073 }
1074
1075 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1076 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1077 }
1078
1079 bool CYCastBool(JSContextRef context, JSValueRef value) {
1080 return JSValueToBoolean(context, value);
1081 }
1082
1083 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1084 CFTypeRef object;
1085 bool copy;
1086
1087 switch (JSType type = JSValueGetType(context, value)) {
1088 case kJSTypeUndefined:
1089 object = [WebUndefined undefined];
1090 copy = false;
1091 break;
1092
1093 case kJSTypeNull:
1094 return NULL;
1095 break;
1096
1097 case kJSTypeBoolean:
1098 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1099 copy = false;
1100 break;
1101
1102 case kJSTypeNumber:
1103 object = CYCopyCFNumber(context, value);
1104 copy = true;
1105 break;
1106
1107 case kJSTypeString:
1108 object = CYCopyCFString(context, value);
1109 copy = true;
1110 break;
1111
1112 case kJSTypeObject:
1113 // XXX: this might could be more efficient
1114 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1115 copy = false;
1116 break;
1117
1118 default:
1119 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1120 break;
1121 }
1122
1123 if (cast != copy)
1124 return object;
1125 else if (copy)
1126 return CYPoolRelease(pool, object);
1127 else
1128 return CFRetain(object);
1129 }
1130
1131 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1132 return CYCFType(pool, context, value, true);
1133 }
1134
1135 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1136 return CYCFType(pool, context, value, false);
1137 }
1138
1139 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1140 CYPool pool;
1141 size_t size(JSPropertyNameArrayGetCount(names));
1142 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1143 for (size_t index(0); index != size; ++index)
1144 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1145 return array;
1146 }
1147
1148 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1149 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1150 }
1151
1152 void CYThrow(JSContextRef context, JSValueRef value) {
1153 if (value == NULL)
1154 return;
1155 @throw CYCastNSObject(NULL, context, value);
1156 }
1157
1158 JSValueRef CYJSNull(JSContextRef context) {
1159 return JSValueMakeNull(context);
1160 }
1161
1162 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1163 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1164 }
1165
1166 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1167 return CYCastJSValue(context, CYJSString(value));
1168 }
1169
1170 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1171 if (value == nil)
1172 return CYJSNull(context);
1173 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1174 return [value cy$JSValueInContext:context];
1175 else
1176 return CYMakeInstance(context, value, false);
1177 }
1178
1179 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1180 JSValueRef exception(NULL);
1181 JSObjectRef object(JSValueToObject(context, value, &exception));
1182 CYThrow(context, exception);
1183 return object;
1184 }
1185
1186 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1187 JSValueRef exception(NULL);
1188 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1189 CYThrow(context, exception);
1190 return value;
1191 }
1192
1193 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1194 JSValueRef exception(NULL);
1195 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1196 CYThrow(context, exception);
1197 return value;
1198 }
1199
1200 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1201 JSValueRef exception(NULL);
1202 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1203 CYThrow(context, exception);
1204 }
1205
1206 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1207 if (exception == NULL)
1208 throw error;
1209 *exception = CYCastJSValue(context, error);
1210 }
1211
1212 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1213 JSValueRef exception(NULL);
1214 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1215 CYThrow(context, exception);
1216 return value;
1217 }
1218
1219 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1220 // XXX: this isn't actually correct
1221 return value != NULL && JSValueIsObject(context, value);
1222 }
1223
1224 @implementation CYJSObject
1225
1226 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1227 if ((self = [super init]) != nil) {
1228 object_ = object;
1229 context_ = context;
1230 } return self;
1231 }
1232
1233 - (NSObject *) cy$toJSON:(NSString *)key {
1234 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1235 if (!CYIsCallable(context_, toJSON))
1236 return [super cy$toJSON:key];
1237 else {
1238 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1239 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1240 // XXX: do I really want an NSNull here?!
1241 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1242 }
1243 }
1244
1245 - (NSString *) cy$toCYON {
1246 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1247 if (!CYIsCallable(context_, toCYON))
1248 return [super cy$toCYON];
1249 else {
1250 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1251 return CYCastNSString(NULL, CYJSString(context_, value));
1252 }
1253 }
1254
1255 - (NSUInteger) count {
1256 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1257 size_t size(JSPropertyNameArrayGetCount(names));
1258 JSPropertyNameArrayRelease(names);
1259 return size;
1260 }
1261
1262 - (id) objectForKey:(id)key {
1263 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1264 }
1265
1266 - (NSEnumerator *) keyEnumerator {
1267 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1268 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1269 JSPropertyNameArrayRelease(names);
1270 return enumerator;
1271 }
1272
1273 - (void) setObject:(id)object forKey:(id)key {
1274 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1275 }
1276
1277 - (void) removeObjectForKey:(id)key {
1278 JSValueRef exception(NULL);
1279 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1280 CYThrow(context_, exception);
1281 }
1282
1283 @end
1284
1285 @implementation CYJSArray
1286
1287 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1288 if ((self = [super init]) != nil) {
1289 object_ = object;
1290 context_ = context;
1291 } return self;
1292 }
1293
1294 - (NSUInteger) count {
1295 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1296 }
1297
1298 - (id) objectAtIndex:(NSUInteger)index {
1299 JSValueRef exception(NULL);
1300 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1301 CYThrow(context_, exception);
1302 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1303 }
1304
1305 @end
1306
1307 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1308 CYTry {
1309 CYPoolTry {
1310 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1311 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1312 } CYPoolCatch(NULL)
1313 } CYCatch
1314 }
1315
1316 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1317 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1318 const char *string(CYPoolCString(pool, json));
1319 [json release];
1320 return string;
1321 } else return NULL;
1322 }
1323
1324 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1325 struct CYInternal :
1326 CYData
1327 {
1328 JSObjectRef object_;
1329
1330 CYInternal() :
1331 object_(NULL)
1332 {
1333 }
1334
1335 ~CYInternal() {
1336 // XXX: delete object_? ;(
1337 }
1338
1339 static CYInternal *Get(id self) {
1340 CYInternal *internal(NULL);
1341 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1342 // XXX: do something epic? ;P
1343 }
1344
1345 return internal;
1346 }
1347
1348 static CYInternal *Set(id self) {
1349 CYInternal *internal(NULL);
1350 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1351 if (internal == NULL) {
1352 internal = new CYInternal();
1353 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1354 }
1355 } else {
1356 // XXX: do something epic? ;P
1357 }
1358
1359 return internal;
1360 }
1361
1362 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1363 if (object_ == NULL)
1364 return NULL;
1365 return CYGetProperty(context, object_, name);
1366 }
1367
1368 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1369 if (object_ == NULL)
1370 object_ = JSObjectMake(context, NULL, NULL);
1371 CYSetProperty(context, object_, name, value);
1372 }
1373 };
1374
1375 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1376 CYPool pool;
1377
1378 CYTry {
1379 NSString *self(CYCastNSObject(pool, context, object));
1380 NSString *name(CYCastNSString(pool, property));
1381
1382 if (CYInternal *internal = CYInternal::Get(self))
1383 if (JSValueRef value = internal->GetProperty(context, property))
1384 return value;
1385
1386 CYPoolTry {
1387 if (NSObject *data = [self cy$getProperty:name])
1388 return CYCastJSValue(context, data);
1389 } CYPoolCatch(NULL)
1390
1391 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1392 PropertyAttributes attributes(property);
1393 SEL sel(sel_registerName(attributes.Getter()));
1394 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1395 }
1396
1397 return NULL;
1398 } CYCatch
1399 }
1400
1401 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1402 CYPool pool;
1403
1404 CYTry {
1405 NSString *self(CYCastNSObject(pool, context, object));
1406 NSString *name(CYCastNSString(pool, property));
1407 NSString *data(CYCastNSObject(pool, context, value));
1408
1409 CYPoolTry {
1410 if ([self cy$setProperty:name to:data])
1411 return true;
1412 } CYPoolCatch(NULL)
1413
1414 if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
1415 PropertyAttributes attributes(property);
1416 if (const char *setter = attributes.Setter()) {
1417 SEL sel(sel_registerName(setter));
1418 JSValueRef arguments[1] = {value};
1419 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1420 return true;
1421 }
1422 }
1423
1424 if (CYInternal *internal = CYInternal::Set(self)) {
1425 internal->SetProperty(context, property, value);
1426 return true;
1427 }
1428
1429 return false;
1430 } CYCatch
1431 }
1432
1433 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1434 CYTry {
1435 CYPoolTry {
1436 NSString *self(CYCastNSObject(NULL, context, object));
1437 NSString *name(CYCastNSString(NULL, property));
1438 return [self cy$deleteProperty:name];
1439 } CYPoolCatch(NULL)
1440 } CYCatch
1441 }
1442
1443 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1444 CYTry {
1445 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1446 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1447 return value;
1448 } CYCatch
1449 }
1450
1451 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1452 Selector_privateData *data(new Selector_privateData(sel));
1453 return JSObjectMake(context, Selector_, data);
1454 }
1455
1456 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1457 Pointer *data(new Pointer(pointer, type, owner));
1458 return JSObjectMake(context, Pointer_, data);
1459 }
1460
1461 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1462 Functor_privateData *data(new Functor_privateData(type, function));
1463 return JSObjectMake(context, Functor_, data);
1464 }
1465
1466 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1467 if (pool == NULL) {
1468 const char *string([CYCastNSString(NULL, value) UTF8String]);
1469 return string;
1470 } else {
1471 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1472 char *string(new(pool) char[size]);
1473 JSStringGetUTF8CString(value, string, size);
1474 return string;
1475 }
1476 }
1477
1478 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1479 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1480 }
1481
1482 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1483 return CYGetIndex(CYPoolCString(pool, value), index);
1484 }
1485
1486 // XXX: this macro is unhygenic
1487 #define CYCastCString(context, value) ({ \
1488 char *utf8; \
1489 if (value == NULL) \
1490 utf8 = NULL; \
1491 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1492 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1493 utf8 = reinterpret_cast<char *>(alloca(size)); \
1494 JSStringGetUTF8CString(string, utf8, size); \
1495 JSStringRelease(string); \
1496 } else \
1497 utf8 = NULL; \
1498 utf8; \
1499 })
1500
1501 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1502 switch (JSValueGetType(context, value)) {
1503 case kJSTypeNull:
1504 return NULL;
1505 /*case kJSTypeString:
1506 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1507 case kJSTypeObject:
1508 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1509 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1510 return data->value_;
1511 }*/
1512 default:
1513 double number(CYCastDouble(context, value));
1514 if (std::isnan(number))
1515 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1516 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1517 }
1518 }
1519
1520 template <typename Type_>
1521 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1522 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1523 }
1524
1525 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1526 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1527 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1528 return reinterpret_cast<SEL>(data->value_);
1529 } else
1530 return CYCastPointer<SEL>(context, value);
1531 }
1532
1533 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1534 switch (type->primitive) {
1535 case sig::boolean_P:
1536 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1537 break;
1538
1539 #define CYPoolFFI_(primitive, native) \
1540 case sig::primitive ## _P: \
1541 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1542 break;
1543
1544 CYPoolFFI_(uchar, unsigned char)
1545 CYPoolFFI_(char, char)
1546 CYPoolFFI_(ushort, unsigned short)
1547 CYPoolFFI_(short, short)
1548 CYPoolFFI_(ulong, unsigned long)
1549 CYPoolFFI_(long, long)
1550 CYPoolFFI_(uint, unsigned int)
1551 CYPoolFFI_(int, int)
1552 CYPoolFFI_(ulonglong, unsigned long long)
1553 CYPoolFFI_(longlong, long long)
1554 CYPoolFFI_(float, float)
1555 CYPoolFFI_(double, double)
1556
1557 case sig::object_P:
1558 case sig::typename_P:
1559 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1560 break;
1561
1562 case sig::selector_P:
1563 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1564 break;
1565
1566 case sig::pointer_P:
1567 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1568 break;
1569
1570 case sig::string_P:
1571 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1572 break;
1573
1574 case sig::struct_P: {
1575 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1576 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1577 for (size_t index(0); index != type->data.signature.count; ++index) {
1578 sig::Element *element(&type->data.signature.elements[index]);
1579 ffi_type *field(ffi->elements[index]);
1580
1581 JSValueRef rhs;
1582 if (aggregate == NULL)
1583 rhs = value;
1584 else {
1585 rhs = CYGetProperty(context, aggregate, index);
1586 if (JSValueIsUndefined(context, rhs)) {
1587 if (element->name != NULL)
1588 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1589 else
1590 goto undefined;
1591 if (JSValueIsUndefined(context, rhs)) undefined:
1592 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1593 }
1594 }
1595
1596 CYPoolFFI(pool, context, element->type, field, base, rhs);
1597 // XXX: alignment?
1598 base += field->size;
1599 }
1600 } break;
1601
1602 case sig::void_P:
1603 break;
1604
1605 default:
1606 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1607 _assert(false);
1608 }
1609 }
1610
1611 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
1612 JSValueRef value;
1613
1614 switch (type->primitive) {
1615 case sig::boolean_P:
1616 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1617 break;
1618
1619 #define CYFromFFI_(primitive, native) \
1620 case sig::primitive ## _P: \
1621 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1622 break;
1623
1624 CYFromFFI_(uchar, unsigned char)
1625 CYFromFFI_(char, char)
1626 CYFromFFI_(ushort, unsigned short)
1627 CYFromFFI_(short, short)
1628 CYFromFFI_(ulong, unsigned long)
1629 CYFromFFI_(long, long)
1630 CYFromFFI_(uint, unsigned int)
1631 CYFromFFI_(int, int)
1632 CYFromFFI_(ulonglong, unsigned long long)
1633 CYFromFFI_(longlong, long long)
1634 CYFromFFI_(float, float)
1635 CYFromFFI_(double, double)
1636
1637 case sig::object_P: {
1638 if (id object = *reinterpret_cast<id *>(data)) {
1639 value = CYCastJSValue(context, object);
1640 if (initialize)
1641 [object release];
1642 } else goto null;
1643 } break;
1644
1645 case sig::typename_P:
1646 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1647 break;
1648
1649 case sig::selector_P:
1650 if (SEL sel = *reinterpret_cast<SEL *>(data))
1651 value = CYMakeSelector(context, sel);
1652 else goto null;
1653 break;
1654
1655 case sig::pointer_P:
1656 if (void *pointer = *reinterpret_cast<void **>(data))
1657 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1658 else goto null;
1659 break;
1660
1661 case sig::string_P:
1662 if (char *utf8 = *reinterpret_cast<char **>(data))
1663 value = CYCastJSValue(context, utf8);
1664 else goto null;
1665 break;
1666
1667 case sig::struct_P:
1668 value = CYMakeStruct(context, data, type, ffi, owner);
1669 break;
1670
1671 case sig::void_P:
1672 value = CYJSUndefined(context);
1673 break;
1674
1675 null:
1676 value = CYJSNull(context);
1677 break;
1678
1679 default:
1680 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1681 _assert(false);
1682 }
1683
1684 return value;
1685 }
1686
1687 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1688 Type_privateData *typical(internal->type_);
1689 sig::Type *type(typical->type_);
1690 if (type == NULL)
1691 return false;
1692
1693 const char *name(CYPoolCString(pool, property));
1694 size_t length(strlen(name));
1695 double number(CYCastDouble(name, length));
1696
1697 size_t count(type->data.signature.count);
1698
1699 if (std::isnan(number)) {
1700 if (property == NULL)
1701 return false;
1702
1703 sig::Element *elements(type->data.signature.elements);
1704
1705 for (size_t local(0); local != count; ++local) {
1706 sig::Element *element(&elements[local]);
1707 if (element->name != NULL && strcmp(name, element->name) == 0) {
1708 index = local;
1709 goto base;
1710 }
1711 }
1712
1713 return false;
1714 } else {
1715 index = static_cast<ssize_t>(number);
1716 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1717 return false;
1718 }
1719
1720 base:
1721 ffi_type **elements(typical->GetFFI()->elements);
1722
1723 base = reinterpret_cast<uint8_t *>(internal->value_);
1724 for (ssize_t local(0); local != index; ++local)
1725 base += elements[local]->size;
1726
1727 return true;
1728 }
1729
1730 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1731 CYPool pool;
1732 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1733 Type_privateData *typical(internal->type_);
1734
1735 if (typical->type_ == NULL)
1736 return NULL;
1737
1738 ssize_t index;
1739 if (!CYGetIndex(pool, property, index))
1740 return NULL;
1741
1742 ffi_type *ffi(typical->GetFFI());
1743
1744 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1745 base += ffi->size * index;
1746
1747 JSObjectRef owner(internal->owner_ ?: object);
1748
1749 CYTry {
1750 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1751 } CYCatch
1752 }
1753
1754 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1755 CYPool pool;
1756 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1757 Type_privateData *typical(internal->type_);
1758
1759 if (typical->type_ == NULL)
1760 return NULL;
1761
1762 ssize_t index;
1763 if (!CYGetIndex(pool, property, index))
1764 return NULL;
1765
1766 ffi_type *ffi(typical->GetFFI());
1767
1768 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1769 base += ffi->size * index;
1770
1771 CYTry {
1772 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1773 return true;
1774 } CYCatch
1775 }
1776
1777 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1778 CYPool pool;
1779 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1780 Type_privateData *typical(internal->type_);
1781
1782 ssize_t index;
1783 uint8_t *base;
1784
1785 if (!Index_(pool, internal, property, index, base))
1786 return NULL;
1787
1788 JSObjectRef owner(internal->owner_ ?: object);
1789
1790 CYTry {
1791 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1792 } CYCatch
1793 }
1794
1795 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1796 CYPool pool;
1797 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1798 Type_privateData *typical(internal->type_);
1799
1800 ssize_t index;
1801 uint8_t *base;
1802
1803 if (!Index_(pool, internal, property, index, base))
1804 return false;
1805
1806 CYTry {
1807 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1808 return true;
1809 } CYCatch
1810 }
1811
1812 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1813 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1814 Type_privateData *typical(internal->type_);
1815 sig::Type *type(typical->type_);
1816
1817 if (type == NULL)
1818 return;
1819
1820 size_t count(type->data.signature.count);
1821 sig::Element *elements(type->data.signature.elements);
1822
1823 char number[32];
1824
1825 for (size_t index(0); index != count; ++index) {
1826 const char *name;
1827 name = elements[index].name;
1828
1829 if (name == NULL) {
1830 sprintf(number, "%lu", index);
1831 name = number;
1832 }
1833
1834 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1835 }
1836 }
1837
1838 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1839 CYTry {
1840 if (setups + count != signature->count - 1)
1841 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1842
1843 size_t size(setups + count);
1844 void *values[size];
1845 memcpy(values, setup, sizeof(void *) * setups);
1846
1847 for (size_t index(setups); index != size; ++index) {
1848 sig::Element *element(&signature->elements[index + 1]);
1849 ffi_type *ffi(cif->arg_types[index]);
1850 // XXX: alignment?
1851 values[index] = new(pool) uint8_t[ffi->size];
1852 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1853 }
1854
1855 uint8_t value[cif->rtype->size];
1856 ffi_call(cif, function, value, values);
1857
1858 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1859 } CYCatch
1860 }
1861
1862 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1863 ffoData *data(reinterpret_cast<ffoData *>(arg));
1864
1865 JSContextRef context(data->context_);
1866
1867 size_t count(data->cif_.nargs);
1868 JSValueRef values[count];
1869
1870 for (size_t index(0); index != count; ++index)
1871 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
1872
1873 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1874 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1875 }
1876
1877 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1878 // XXX: in case of exceptions this will leak
1879 ffoData *data(new ffoData(type));
1880
1881 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1882 NULL, sizeof(ffi_closure),
1883 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1884 -1, 0
1885 )));
1886
1887 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1888 _assert(status == FFI_OK);
1889
1890 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1891
1892 data->value_ = closure;
1893
1894 data->context_ = CYGetJSContext();
1895 data->function_ = function;
1896
1897 return JSObjectMake(context, Functor_, data);
1898 }
1899
1900 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1901 CYTry {
1902 CYPool pool;
1903 NSString *name(CYCastNSString(pool, property));
1904 if (Class _class = NSClassFromString(name))
1905 return CYMakeInstance(context, _class, true);
1906 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1907 switch ([[entry objectAtIndex:0] intValue]) {
1908 case 0:
1909 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1910 case 1:
1911 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1912 case 2:
1913 // XXX: this is horrendously inefficient
1914 sig::Signature signature;
1915 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
1916 ffi_cif cif;
1917 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1918 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
1919 }
1920 return NULL;
1921 } CYCatch
1922 }
1923
1924 bool stret(ffi_type *ffi_type) {
1925 return ffi_type->type == FFI_TYPE_STRUCT && (
1926 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1927 struct_forward_array[ffi_type->size] != 0
1928 );
1929 }
1930
1931 extern "C" {
1932 int *_NSGetArgc(void);
1933 char ***_NSGetArgv(void);
1934 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1935 }
1936
1937 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1938 CYTry {
1939 NSLog(@"%s", CYCastCString(context, arguments[0]));
1940 return CYJSUndefined(context);
1941 } CYCatch
1942 }
1943
1944 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
1945 const char *type;
1946
1947 Class _class(object_getClass(self));
1948 if (Method method = class_getInstanceMethod(_class, _cmd))
1949 type = method_getTypeEncoding(method);
1950 else {
1951 CYTry {
1952 CYPoolTry {
1953 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1954 if (method == nil)
1955 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1956 type = CYPoolCString(pool, [method _typeString]);
1957 } CYPoolCatch(NULL)
1958 } CYCatch
1959 }
1960
1961 void *setup[2];
1962 setup[0] = &self;
1963 setup[1] = &_cmd;
1964
1965 sig::Signature signature;
1966 sig::Parse(pool, &signature, type, &Structor_);
1967
1968 ffi_cif cif;
1969 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1970
1971 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1972 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
1973 }
1974
1975 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1976 CYPool pool;
1977
1978 bool uninitialized;
1979
1980 id self;
1981 SEL _cmd;
1982
1983 CYTry {
1984 if (count < 2)
1985 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1986
1987 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
1988 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
1989 self = data->GetValue();
1990 uninitialized = data->IsUninitialized();
1991 if (uninitialized)
1992 data->value_ = nil;
1993 } else {
1994 self = CYCastNSObject(pool, context, arguments[0]);
1995 uninitialized = false;
1996 }
1997
1998 if (self == nil)
1999 return CYJSNull(context);
2000
2001 _cmd = CYCastSEL(context, arguments[1]);
2002 } CYCatch
2003
2004 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2005 }
2006
2007 MSHook(void, CYDealloc, id self, SEL sel) {
2008 CYInternal *internal;
2009 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2010 if (internal != NULL)
2011 delete internal;
2012 _CYDealloc(self, sel);
2013 }
2014
2015 MSHook(void, objc_registerClassPair, Class _class) {
2016 Class super(class_getSuperclass(_class));
2017 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2018 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2019 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2020 }
2021
2022 _objc_registerClassPair(_class);
2023 }
2024
2025 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2026 CYTry {
2027 if (count != 1)
2028 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2029 CYPool pool;
2030 Class _class(CYCastNSObject(pool, context, arguments[0]));
2031 $objc_registerClassPair(_class);
2032 return CYJSUndefined(context);
2033 } CYCatch
2034 }
2035
2036 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2037 JSValueRef setup[count + 2];
2038 setup[0] = _this;
2039 setup[1] = object;
2040 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2041 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2042 }
2043
2044 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2045 CYPool pool;
2046 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2047 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2048 }
2049
2050 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2051 CYTry {
2052 if (count != 1)
2053 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2054 const char *name(CYCastCString(context, arguments[0]));
2055 return CYMakeSelector(context, sel_registerName(name));
2056 } CYCatch
2057 }
2058
2059 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2060 CYTry {
2061 if (count != 2)
2062 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2063
2064 void *value(CYCastPointer<void *>(context, arguments[0]));
2065 const char *type(CYCastCString(context, arguments[1]));
2066
2067 CYPool pool;
2068
2069 sig::Signature signature;
2070 sig::Parse(pool, &signature, type, &Structor_);
2071
2072 return CYMakePointer(context, value, signature.elements[0].type, NULL);
2073 } CYCatch
2074 }
2075
2076 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2077 Type_privateData *internal(new Type_privateData(type));
2078 return JSObjectMake(context, Type_, internal);
2079 }
2080
2081 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2082 CYTry {
2083 if (count != 1)
2084 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2085 const char *type(CYCastCString(context, arguments[0]));
2086 return CYMakeType(context, object, type);
2087 } CYCatch
2088 }
2089
2090 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2091 CYTry {
2092 if (count != 1)
2093 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2094 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2095 sig::Type *type(internal->type_);
2096 ffi_type *ffi(internal->GetFFI());
2097 // XXX: alignment?
2098 uint8_t value[ffi->size];
2099 CYPool pool;
2100 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2101 return CYFromFFI(context, type, ffi, value, false);
2102 } CYCatch
2103 }
2104
2105 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2106 CYTry {
2107 if (count > 1)
2108 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2109 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2110 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2111 // XXX: alignment?
2112 void *value(malloc(internal->GetFFI()->size * size));
2113 return CYMakePointer(context, value, internal->type_, NULL);
2114 } CYCatch
2115 }
2116
2117 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2118 CYTry {
2119 if (count != 2)
2120 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2121 const char *type(CYCastCString(context, arguments[1]));
2122 JSValueRef exception(NULL);
2123 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2124 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2125 return CYMakeFunctor(context, function, type);
2126 } else if (exception != NULL) {
2127 return NULL;
2128 } else {
2129 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2130 return CYMakeFunctor(context, function, type);
2131 }
2132 } CYCatch
2133 }
2134
2135 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2136 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2137 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2138 }
2139
2140 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2141 return Function_;
2142 }
2143
2144 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2145 CYTry {
2146 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2147 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2148 } CYCatch
2149 }
2150
2151 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2152 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2153 }
2154
2155 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2156 CYTry {
2157 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2158 char string[32];
2159 sprintf(string, "%p", internal->value_);
2160 return CYCastJSValue(context, string);
2161 } CYCatch
2162 }
2163
2164 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2165 CYTry {
2166 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2167 CYPoolTry {
2168 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2169 } CYPoolCatch(NULL)
2170 } CYCatch
2171 }
2172
2173 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2174 CYTry {
2175 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2176 CYPoolTry {
2177 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2178 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2179 } CYPoolCatch(NULL)
2180 } CYCatch
2181 }
2182
2183 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2184 CYTry {
2185 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2186 CYPoolTry {
2187 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2188 } CYPoolCatch(NULL)
2189 } CYCatch
2190 }
2191
2192 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2193 CYTry {
2194 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2195 return CYCastJSValue(context, sel_getName(data->GetValue()));
2196 } CYCatch
2197 }
2198
2199 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2200 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2201 }
2202
2203 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2204 CYTry {
2205 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2206 const char *name(sel_getName(internal->GetValue()));
2207 CYPoolTry {
2208 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2209 } CYPoolCatch(NULL)
2210 } CYCatch
2211 }
2212
2213 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2214 CYTry {
2215 if (count != 1)
2216 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2217 CYPool pool;
2218 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2219 Class _class(CYCastNSObject(pool, context, arguments[0]));
2220 SEL sel(internal->GetValue());
2221 if (Method method = class_getInstanceMethod(_class, sel))
2222 return CYCastJSValue(context, method_getTypeEncoding(method));
2223 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2224 return CYCastJSValue(context, CYJSString(type));
2225 else
2226 return CYJSNull(context);
2227 } CYCatch
2228 }
2229
2230 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2231 CYTry {
2232 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2233 CYPool pool;
2234 const char *type(sig::Unparse(pool, internal->type_));
2235 CYPoolTry {
2236 return CYCastJSValue(context, CYJSString(type));
2237 } CYPoolCatch(NULL)
2238 } CYCatch
2239 }
2240
2241 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2242 CYTry {
2243 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2244 CYPool pool;
2245 const char *type(sig::Unparse(pool, internal->type_));
2246 CYPoolTry {
2247 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2248 } CYPoolCatch(NULL)
2249 } CYCatch
2250 }
2251
2252 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2253 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2254 }
2255
2256 static JSStaticValue CYValue_staticValues[2] = {
2257 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2258 {NULL, NULL, NULL, 0}
2259 };
2260
2261 static JSStaticFunction Pointer_staticFunctions[4] = {
2262 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2263 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2264 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2265 {NULL, NULL, 0}
2266 };
2267
2268 static JSStaticFunction Functor_staticFunctions[4] = {
2269 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2270 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2271 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2272 {NULL, NULL, 0}
2273 };
2274
2275 /*static JSStaticValue Selector_staticValues[2] = {
2276 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2277 {NULL, NULL, NULL, 0}
2278 };*/
2279
2280 static JSStaticFunction Instance_staticFunctions[4] = {
2281 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2282 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2283 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2284 {NULL, NULL, 0}
2285 };
2286
2287 static JSStaticFunction Selector_staticFunctions[5] = {
2288 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2289 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2290 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2291 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2292 {NULL, NULL, 0}
2293 };
2294
2295 static JSStaticFunction Type_staticFunctions[5] = {
2296 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2297 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2298 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2299 {NULL, NULL, 0}
2300 };
2301
2302 CYDriver::CYDriver(const std::string &filename) :
2303 state_(CYClear),
2304 data_(NULL),
2305 size_(0),
2306 filename_(filename),
2307 source_(NULL)
2308 {
2309 ScannerInit();
2310 }
2311
2312 CYDriver::~CYDriver() {
2313 ScannerDestroy();
2314 }
2315
2316 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2317 CYDriver::Error error;
2318 error.location_ = location;
2319 error.message_ = message;
2320 driver.errors_.push_back(error);
2321 }
2322
2323 void CYSetArgs(int argc, const char *argv[]) {
2324 JSContextRef context(CYGetJSContext());
2325 JSValueRef args[argc];
2326 for (int i(0); i != argc; ++i)
2327 args[i] = CYCastJSValue(context, argv[i]);
2328 JSValueRef exception(NULL);
2329 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2330 CYThrow(context, exception);
2331 CYSetProperty(context, System_, CYJSString("args"), array);
2332 }
2333
2334 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2335 return JSContextGetGlobalObject(context);
2336 }
2337
2338 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
2339 JSStringRef script(JSStringCreateWithUTF8CString(code));
2340
2341 JSContextRef context(CYGetJSContext());
2342
2343 JSValueRef exception(NULL);
2344 JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
2345 JSStringRelease(script);
2346
2347 if (exception != NULL) { error:
2348 result = exception;
2349 exception = NULL;
2350 }
2351
2352 if (JSValueIsUndefined(context, result))
2353 return NULL;
2354
2355 const char *json(CYPoolCYONString(pool, context, result, &exception));
2356 if (exception != NULL)
2357 goto error;
2358
2359 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
2360 return json;
2361 }
2362
2363 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
2364 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
2365 data += writ;
2366 size -= writ;
2367 } else
2368 return false;
2369 return true;
2370 }
2371
2372 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
2373 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
2374 data += writ;
2375 size -= writ;
2376 } else
2377 return false;
2378 return true;
2379 }
2380
2381 static int Socket_;
2382 apr_pool_t *Pool_;
2383
2384 struct CYExecute_ {
2385 apr_pool_t *pool_;
2386 const char * volatile data_;
2387 };
2388
2389 // XXX: this is "tre lame"
2390 @interface CYClient_ : NSObject {
2391 }
2392
2393 - (void) execute:(NSValue *)value;
2394
2395 @end
2396
2397 @implementation CYClient_
2398
2399 - (void) execute:(NSValue *)value {
2400 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
2401 execute->data_ = CYExecute(execute->pool_, execute->data_);
2402 }
2403
2404 @end
2405
2406 struct CYClient :
2407 CYData
2408 {
2409 int socket_;
2410 apr_thread_t *thread_;
2411
2412 CYClient(int socket) :
2413 socket_(socket)
2414 {
2415 }
2416
2417 ~CYClient() {
2418 _syscall(close(socket_));
2419 }
2420
2421 void Handle() { _pooled
2422 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
2423
2424 for (;;) {
2425 size_t size;
2426 if (!CYRecvAll(socket_, &size, sizeof(size)))
2427 return;
2428
2429 CYPool pool;
2430 char *data(new(pool) char[size + 1]);
2431 if (!CYRecvAll(socket_, data, size))
2432 return;
2433 data[size] = '\0';
2434
2435 CYDriver driver("");
2436 cy::parser parser(driver);
2437
2438 driver.data_ = data;
2439 driver.size_ = size;
2440
2441 const char *json;
2442 if (parser.parse() != 0 || !driver.errors_.empty()) {
2443 json = NULL;
2444 size = _not(size_t);
2445 } else {
2446 std::ostringstream str;
2447 driver.source_->Show(str);
2448 std::string code(str.str());
2449 CYExecute_ execute = {pool, code.c_str()};
2450 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
2451 json = execute.data_;
2452 size = json == NULL ? _not(size_t) : strlen(json);
2453 }
2454
2455 if (!CYSendAll(socket_, &size, sizeof(size)))
2456 return;
2457 if (json != NULL)
2458 if (!CYSendAll(socket_, json, size))
2459 return;
2460 }
2461 }
2462 };
2463
2464 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
2465 CYClient *client(reinterpret_cast<CYClient *>(data));
2466 client->Handle();
2467 delete client;
2468 return NULL;
2469 }
2470
2471 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
2472 for (;;) {
2473 int socket(_syscall(accept(Socket_, NULL, NULL)));
2474 CYClient *client(new CYClient(socket));
2475 apr_threadattr_t *attr;
2476 _aprcall(apr_threadattr_create(&attr, Pool_));
2477 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
2478 }
2479
2480 return NULL;
2481 }
2482
2483 void Unlink() {
2484 pid_t pid(getpid());
2485 char path[104];
2486 sprintf(path, "/tmp/.s.cy.%u", pid);
2487 unlink(path);
2488 }
2489
2490 MSInitialize { _pooled
2491 _aprcall(apr_initialize());
2492 _aprcall(apr_pool_create(&Pool_, NULL));
2493
2494 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2495 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2496
2497 Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
2498
2499 struct sockaddr_un address;
2500 memset(&address, 0, sizeof(address));
2501 address.sun_family = AF_UNIX;
2502
2503 pid_t pid(getpid());
2504 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
2505
2506 try {
2507 _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
2508 atexit(&Unlink);
2509 _syscall(listen(Socket_, 0));
2510
2511 apr_threadattr_t *attr;
2512 _aprcall(apr_threadattr_create(&attr, Pool_));
2513
2514 apr_thread_t *thread;
2515 _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
2516 } catch (...) {
2517 NSLog(@"failed to setup Cyrver");
2518 }
2519 }
2520
2521 JSGlobalContextRef CYGetJSContext() {
2522 if (Context_ == NULL) {
2523 JSClassDefinition definition;
2524
2525 definition = kJSClassDefinitionEmpty;
2526 definition.className = "Functor";
2527 definition.staticFunctions = Functor_staticFunctions;
2528 definition.callAsFunction = &Functor_callAsFunction;
2529 definition.finalize = &CYData::Finalize;
2530 Functor_ = JSClassCreate(&definition);
2531
2532 definition = kJSClassDefinitionEmpty;
2533 definition.className = "Instance";
2534 definition.staticValues = CYValue_staticValues;
2535 definition.staticFunctions = Instance_staticFunctions;
2536 definition.getProperty = &Instance_getProperty;
2537 definition.setProperty = &Instance_setProperty;
2538 definition.deleteProperty = &Instance_deleteProperty;
2539 definition.callAsConstructor = &Instance_callAsConstructor;
2540 definition.finalize = &CYData::Finalize;
2541 Instance_ = JSClassCreate(&definition);
2542
2543 definition = kJSClassDefinitionEmpty;
2544 definition.className = "Pointer";
2545 definition.staticFunctions = Pointer_staticFunctions;
2546 definition.getProperty = &Pointer_getProperty;
2547 definition.setProperty = &Pointer_setProperty;
2548 definition.finalize = &CYData::Finalize;
2549 Pointer_ = JSClassCreate(&definition);
2550
2551 definition = kJSClassDefinitionEmpty;
2552 definition.className = "Selector";
2553 definition.staticValues = CYValue_staticValues;
2554 //definition.staticValues = Selector_staticValues;
2555 definition.staticFunctions = Selector_staticFunctions;
2556 definition.callAsFunction = &Selector_callAsFunction;
2557 definition.finalize = &CYData::Finalize;
2558 Selector_ = JSClassCreate(&definition);
2559
2560 definition = kJSClassDefinitionEmpty;
2561 definition.className = "Struct";
2562 definition.getProperty = &Struct_getProperty;
2563 definition.setProperty = &Struct_setProperty;
2564 definition.getPropertyNames = &Struct_getPropertyNames;
2565 definition.finalize = &CYData::Finalize;
2566 Struct_ = JSClassCreate(&definition);
2567
2568 definition = kJSClassDefinitionEmpty;
2569 definition.className = "Type";
2570 definition.staticFunctions = Type_staticFunctions;
2571 definition.callAsFunction = &Type_callAsFunction;
2572 definition.callAsConstructor = &Type_callAsConstructor;
2573 definition.finalize = &CYData::Finalize;
2574 Type_ = JSClassCreate(&definition);
2575
2576 definition = kJSClassDefinitionEmpty;
2577 definition.className = "Runtime";
2578 definition.getProperty = &Runtime_getProperty;
2579 Runtime_ = JSClassCreate(&definition);
2580
2581 definition = kJSClassDefinitionEmpty;
2582 //definition.getProperty = &Global_getProperty;
2583 JSClassRef Global(JSClassCreate(&definition));
2584
2585 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2586 Context_ = context;
2587
2588 JSObjectRef global(CYGetGlobalObject(context));
2589
2590 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2591 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
2592
2593 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2594 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
2595 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2596 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2597 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
2598
2599 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2600
2601 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2602 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2603
2604 System_ = JSObjectMake(context, NULL, NULL);
2605 CYSetProperty(context, global, CYJSString("system"), System_);
2606 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2607 //CYSetProperty(context, System_, CYJSString("global"), global);
2608
2609 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2610
2611 Result_ = JSStringCreateWithUTF8CString("_");
2612
2613 length_ = JSStringCreateWithUTF8CString("length");
2614 message_ = JSStringCreateWithUTF8CString("message");
2615 name_ = JSStringCreateWithUTF8CString("name");
2616 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2617 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2618
2619 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2620 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
2621 }
2622
2623 return Context_;
2624 }