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