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