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