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