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