]> git.saurik.com Git - cycript.git/blob - Library.mm
64f7562bef6f6d37bc4fd8aa6e22a7ab12140481
[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 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 Finalize(JSObjectRef object) {
139 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
140 data->~CYData();
141 apr_pool_destroy(data->pool_);
142 }
143 };
144
145 struct Pointer_privateData :
146 CYData
147 {
148 void *value_;
149 sig::Type type_;
150
151 Pointer_privateData() {
152 }
153
154 Pointer_privateData(void *value) :
155 value_(value)
156 {
157 }
158 };
159
160 struct Functor_privateData :
161 Pointer_privateData
162 {
163 sig::Signature signature_;
164 ffi_cif cif_;
165
166 Functor_privateData(const char *type, void (*value)()) :
167 Pointer_privateData(reinterpret_cast<void *>(value))
168 {
169 sig::Parse(pool_, &signature_, type);
170 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
171 }
172 };
173
174 struct ffoData :
175 Functor_privateData
176 {
177 JSContextRef context_;
178 JSObjectRef function_;
179
180 ffoData(const char *type) :
181 Functor_privateData(type, NULL)
182 {
183 }
184 };
185
186 struct Selector_privateData : Pointer_privateData {
187 Selector_privateData(SEL value) :
188 Pointer_privateData(value)
189 {
190 }
191
192 SEL GetValue() const {
193 return reinterpret_cast<SEL>(value_);
194 }
195 };
196
197 struct Instance_privateData :
198 Pointer_privateData
199 {
200 bool transient_;
201
202 Instance_privateData(id value, bool transient) :
203 Pointer_privateData(value)
204 {
205 }
206
207 virtual ~Instance_privateData() {
208 if (!transient_)
209 [GetValue() release];
210 }
211
212 id GetValue() const {
213 return reinterpret_cast<id>(value_);
214 }
215 };
216
217 namespace sig {
218
219 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
220
221 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
222 lhs.name = apr_pstrdup(pool, rhs.name);
223 if (rhs.type == NULL)
224 lhs.type = NULL;
225 else {
226 lhs.type = new(pool) Type;
227 Copy(pool, *lhs.type, *rhs.type);
228 }
229 lhs.offset = rhs.offset;
230 }
231
232 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
233 size_t count(rhs.count);
234 lhs.count = count;
235 lhs.elements = new(pool) Element[count];
236 for (size_t index(0); index != count; ++index)
237 Copy(pool, lhs.elements[index], rhs.elements[index]);
238 }
239
240 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
241 lhs.primitive = rhs.primitive;
242 lhs.name = apr_pstrdup(pool, rhs.name);
243 lhs.flags = rhs.flags;
244
245 if (sig::IsAggregate(rhs.primitive))
246 Copy(pool, lhs.data.signature, rhs.data.signature);
247 else {
248 if (rhs.data.data.type != NULL) {
249 lhs.data.data.type = new(pool) Type;
250 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
251 }
252
253 lhs.data.data.size = rhs.data.data.size;
254 }
255 }
256
257 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
258 lhs.size = rhs.size;
259 lhs.alignment = rhs.alignment;
260 lhs.type = rhs.type;
261 if (rhs.elements == NULL)
262 lhs.elements = NULL;
263 else {
264 size_t count(0);
265 while (rhs.elements[count] != NULL)
266 ++count;
267
268 lhs.elements = new(pool) ffi_type *[count + 1];
269 lhs.elements[count] = NULL;
270
271 for (size_t index(0); index != count; ++index) {
272 // XXX: if these are libffi native then you can just take them
273 ffi_type *ffi(new(pool) ffi_type);
274 lhs.elements[index] = ffi;
275 sig::Copy(pool, *ffi, *rhs.elements[index]);
276 }
277 }
278 }
279
280 }
281
282 struct Type_privateData {
283 sig::Type type_;
284 ffi_type ffi_;
285 //size_t count_;
286
287 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
288 sig::Copy(pool, type_, *type);
289 sig::Copy(pool, ffi_, *ffi);
290
291 /*sig::Element element;
292 element.name = NULL;
293 element.type = type;
294 element.offset = 0;
295
296 sig::Signature signature;
297 signature.elements = &element;
298 signature.count = 1;
299
300 ffi_cif cif;
301 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
302 ffi_ = *cif.rtype;*/
303
304 /*if (type_->type != FFI_TYPE_STRUCT)
305 count_ = 0;
306 else {
307 size_t count(0);
308 while (type_->elements[count] != NULL)
309 ++count;
310 count_ = count;
311 }*/
312 }
313 };
314
315 struct Struct_privateData :
316 Pointer_privateData
317 {
318 JSObjectRef owner_;
319 Type_privateData *type_;
320
321 Struct_privateData() {
322 }
323 };
324
325 struct CStringMapLess :
326 std::binary_function<const char *, const char *, bool>
327 {
328 _finline bool operator ()(const char *lhs, const char *rhs) const {
329 return strcmp(lhs, rhs) < 0;
330 }
331 };
332
333 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
334 static TypeMap Types_;
335
336 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
337 Struct_privateData *internal(new Struct_privateData());
338 apr_pool_t *pool(internal->pool_);
339 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
340 internal->type_ = typical;
341
342 if (owner != NULL) {
343 internal->owner_ = owner;
344 internal->value_ = data;
345 } else {
346 internal->owner_ = NULL;
347
348 size_t size(typical->ffi_.size);
349 void *copy(apr_palloc(internal->pool_, size));
350 memcpy(copy, data, size);
351 internal->value_ = copy;
352 }
353
354 return JSObjectMake(context, Struct_, internal);
355 }
356
357 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
358 if (!transient)
359 object = [object retain];
360 Instance_privateData *data(new Instance_privateData(object, transient));
361 return JSObjectMake(context, Instance_, data);
362 }
363
364 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
365 if (pool == NULL)
366 return [value UTF8String];
367 else {
368 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
369 char *string(new(pool) char[size]);
370 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
371 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
372 return string;
373 }
374 }
375
376 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
377 return JSValueMakeBoolean(context, value);
378 }
379
380 JSValueRef CYCastJSValue(JSContextRef context, double value) {
381 return JSValueMakeNumber(context, value);
382 }
383
384 #define CYCastJSValue_(Type_) \
385 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
386 return JSValueMakeNumber(context, static_cast<double>(value)); \
387 }
388
389 CYCastJSValue_(int)
390 CYCastJSValue_(unsigned int)
391 CYCastJSValue_(long int)
392 CYCastJSValue_(long unsigned int)
393 CYCastJSValue_(long long int)
394 CYCastJSValue_(long long unsigned int)
395
396 JSValueRef CYJSUndefined(JSContextRef context) {
397 return JSValueMakeUndefined(context);
398 }
399
400 @interface NSMethodSignature (Cycript)
401 - (NSString *) _typeString;
402 @end
403
404 @interface NSObject (Cycript)
405
406 - (JSType) cy$JSType;
407
408 - (NSObject *) cy$toJSON:(NSString *)key;
409 - (NSString *) cy$toCYON;
410
411 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
412
413 - (NSObject *) cy$getProperty:(NSString *)name;
414 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
415 - (bool) cy$deleteProperty:(NSString *)name;
416
417 @end
418
419 @interface NSString (Cycript)
420 - (void *) cy$symbol;
421 @end
422
423 @interface NSNumber (Cycript)
424 - (void *) cy$symbol;
425 @end
426
427 @implementation NSObject (Cycript)
428
429 - (JSType) cy$JSType {
430 return kJSTypeObject;
431 }
432
433 - (NSObject *) cy$toJSON:(NSString *)key {
434 return [self description];
435 }
436
437 - (NSString *) cy$toCYON {
438 return [[self cy$toJSON:@""] cy$toCYON];
439 }
440
441 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
442 return CYMakeInstance(context, self, transient);
443 }
444
445 - (NSObject *) cy$getProperty:(NSString *)name {
446 if (![name isEqualToString:@"prototype"])
447 NSLog(@"get:%@", name);
448 return nil;
449 }
450
451 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
452 NSLog(@"set:%@", name);
453 return false;
454 }
455
456 - (bool) cy$deleteProperty:(NSString *)name {
457 NSLog(@"delete:%@", name);
458 return false;
459 }
460
461 @end
462
463 @implementation WebUndefined (Cycript)
464
465 - (JSType) cy$JSType {
466 return kJSTypeUndefined;
467 }
468
469 - (NSObject *) cy$toJSON:(NSString *)key {
470 return self;
471 }
472
473 - (NSString *) cy$toCYON {
474 return @"undefined";
475 }
476
477 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
478 return CYJSUndefined(context);
479 }
480
481 @end
482
483 @implementation NSNull (Cycript)
484
485 - (JSType) cy$JSType {
486 return kJSTypeNull;
487 }
488
489 - (NSObject *) cy$toJSON:(NSString *)key {
490 return self;
491 }
492
493 - (NSString *) cy$toCYON {
494 return @"null";
495 }
496
497 @end
498
499 @implementation NSArray (Cycript)
500
501 - (NSString *) cy$toCYON {
502 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
503 [json appendString:@"["];
504
505 bool comma(false);
506 for (id object in self) {
507 if (comma)
508 [json appendString:@","];
509 else
510 comma = true;
511 if ([object cy$JSType] != kJSTypeUndefined)
512 [json appendString:[object cy$toCYON]];
513 else {
514 [json appendString:@","];
515 comma = false;
516 }
517 }
518
519 [json appendString:@"]"];
520 return json;
521 }
522
523 - (NSObject *) cy$getProperty:(NSString *)name {
524 int index([name intValue]);
525 if (index < 0 || index >= static_cast<int>([self count]))
526 return [super cy$getProperty:name];
527 else
528 return [self objectAtIndex:index];
529 }
530
531 @end
532
533 @implementation NSMutableArray (Cycript)
534
535 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
536 int index([name intValue]);
537 if (index < 0 || index >= static_cast<int>([self count]))
538 return [super cy$setProperty:name to:value];
539 else {
540 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
541 return true;
542 }
543 }
544
545 - (bool) cy$deleteProperty:(NSString *)name {
546 int index([name intValue]);
547 if (index < 0 || index >= static_cast<int>([self count]))
548 return [super cy$deleteProperty:name];
549 else {
550 [self removeObjectAtIndex:index];
551 return true;
552 }
553 }
554
555 @end
556
557 @implementation NSDictionary (Cycript)
558
559 - (NSString *) cy$toCYON {
560 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
561 [json appendString:@"({"];
562
563 bool comma(false);
564 for (id key in self) {
565 if (comma)
566 [json appendString:@","];
567 else
568 comma = true;
569 [json appendString:[key cy$toCYON]];
570 [json appendString:@":"];
571 NSObject *object([self objectForKey:key]);
572 [json appendString:[object cy$toCYON]];
573 }
574
575 [json appendString:@"})"];
576 return json;
577 }
578
579 - (NSObject *) cy$getProperty:(NSString *)name {
580 return [self objectForKey:name];
581 }
582
583 @end
584
585 @implementation NSMutableDictionary (Cycript)
586
587 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
588 [self setObject:(value ?: [NSNull null]) forKey:name];
589 return true;
590 }
591
592 - (bool) cy$deleteProperty:(NSString *)name {
593 if ([self objectForKey:name] == nil)
594 return false;
595 else {
596 [self removeObjectForKey:name];
597 return true;
598 }
599 }
600
601 @end
602
603 @implementation NSNumber (Cycript)
604
605 - (JSType) cy$JSType {
606 // XXX: this just seems stupid
607 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
608 }
609
610 - (NSObject *) cy$toJSON:(NSString *)key {
611 return self;
612 }
613
614 - (NSString *) cy$toCYON {
615 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
616 }
617
618 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
619 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
620 }
621
622 - (void *) cy$symbol {
623 return [self pointerValue];
624 }
625
626 @end
627
628 @implementation NSString (Cycript)
629
630 - (JSType) cy$JSType {
631 return kJSTypeString;
632 }
633
634 - (NSObject *) cy$toJSON:(NSString *)key {
635 return self;
636 }
637
638 - (NSString *) cy$toCYON {
639 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
640
641 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
642 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
643 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
644 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
645 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
646
647 CFStringInsert(json, 0, CFSTR("\""));
648 CFStringAppend(json, CFSTR("\""));
649
650 return [reinterpret_cast<const NSString *>(json) autorelease];
651 }
652
653 - (void *) cy$symbol {
654 CYPool pool;
655 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
656 }
657
658 @end
659
660 @interface CYJSObject : NSDictionary {
661 JSObjectRef object_;
662 JSContextRef context_;
663 }
664
665 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
666
667 - (NSString *) cy$toJSON:(NSString *)key;
668
669 - (NSUInteger) count;
670 - (id) objectForKey:(id)key;
671 - (NSEnumerator *) keyEnumerator;
672 - (void) setObject:(id)object forKey:(id)key;
673 - (void) removeObjectForKey:(id)key;
674
675 @end
676
677 @interface CYJSArray : NSArray {
678 JSObjectRef object_;
679 JSContextRef context_;
680 }
681
682 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
683
684 - (NSUInteger) count;
685 - (id) objectAtIndex:(NSUInteger)index;
686
687 @end
688
689 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
690 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
691
692 JSGlobalContextRef CYGetJSContext() {
693 return Context_;
694 }
695
696 #define CYTry \
697 @try
698 #define CYCatch \
699 @catch (id error) { \
700 CYThrow(context, error, exception); \
701 return NULL; \
702 }
703
704 void CYThrow(JSContextRef context, JSValueRef value);
705
706 apr_status_t CYPoolRelease_(void *data) {
707 id object(reinterpret_cast<id>(data));
708 [object release];
709 return APR_SUCCESS;
710 }
711
712 id CYPoolRelease(apr_pool_t *pool, id object) {
713 if (object == nil)
714 return nil;
715 else if (pool == NULL)
716 return [object autorelease];
717 else {
718 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
719 return object;
720 }
721 }
722
723 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
724 return (CFTypeRef) CYPoolRelease(pool, (id) object);
725 }
726
727 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
728 if (JSValueIsObjectOfClass(context, object, Instance_)) {
729 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
730 return data->GetValue();
731 }
732
733 JSValueRef exception(NULL);
734 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
735 CYThrow(context, exception);
736 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
737 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
738 }
739
740 JSStringRef CYCopyJSString(id value) {
741 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
742 }
743
744 JSStringRef CYCopyJSString(const char *value) {
745 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
746 }
747
748 JSStringRef CYCopyJSString(JSStringRef value) {
749 return value == NULL ? NULL : JSStringRetain(value);
750 }
751
752 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
753 if (JSValueIsNull(context, value))
754 return NULL;
755 JSValueRef exception(NULL);
756 JSStringRef string(JSValueToStringCopy(context, value, &exception));
757 CYThrow(context, exception);
758 return string;
759 }
760
761 class CYJSString {
762 private:
763 JSStringRef string_;
764
765 void Clear_() {
766 JSStringRelease(string_);
767 }
768
769 public:
770 CYJSString(const CYJSString &rhs) :
771 string_(CYCopyJSString(rhs.string_))
772 {
773 }
774
775 template <typename Arg0_>
776 CYJSString(Arg0_ arg0) :
777 string_(CYCopyJSString(arg0))
778 {
779 }
780
781 template <typename Arg0_, typename Arg1_>
782 CYJSString(Arg0_ arg0, Arg1_ arg1) :
783 string_(CYCopyJSString(arg0, arg1))
784 {
785 }
786
787 CYJSString &operator =(const CYJSString &rhs) {
788 Clear_();
789 string_ = CYCopyJSString(rhs.string_);
790 return *this;
791 }
792
793 ~CYJSString() {
794 Clear_();
795 }
796
797 void Clear() {
798 Clear_();
799 string_ = NULL;
800 }
801
802 operator JSStringRef() const {
803 return string_;
804 }
805 };
806
807 CFStringRef CYCopyCFString(JSStringRef value) {
808 return JSStringCopyCFString(kCFAllocatorDefault, value);
809 }
810
811 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
812 return CYCopyCFString(CYJSString(context, value));
813 }
814
815 double CYCastDouble(const char *value, size_t size) {
816 char *end;
817 double number(strtod(value, &end));
818 if (end != value + size)
819 return NAN;
820 return number;
821 }
822
823 double CYCastDouble(const char *value) {
824 return CYCastDouble(value, strlen(value));
825 }
826
827 double CYCastDouble(JSContextRef context, JSValueRef value) {
828 JSValueRef exception(NULL);
829 double number(JSValueToNumber(context, value, &exception));
830 CYThrow(context, exception);
831 return number;
832 }
833
834 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
835 double number(CYCastDouble(context, value));
836 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
837 }
838
839 CFStringRef CYCopyCFString(const char *value) {
840 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
841 }
842
843 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
844 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
845 }
846
847 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
848 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
849 }
850
851 bool CYCastBool(JSContextRef context, JSValueRef value) {
852 return JSValueToBoolean(context, value);
853 }
854
855 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
856 CFTypeRef object;
857 bool copy;
858
859 switch (JSType type = JSValueGetType(context, value)) {
860 case kJSTypeUndefined:
861 object = [WebUndefined undefined];
862 copy = false;
863 break;
864
865 case kJSTypeNull:
866 return NULL;
867 break;
868
869 case kJSTypeBoolean:
870 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
871 copy = false;
872 break;
873
874 case kJSTypeNumber:
875 object = CYCopyCFNumber(context, value);
876 copy = true;
877 break;
878
879 case kJSTypeString:
880 object = CYCopyCFString(context, value);
881 copy = true;
882 break;
883
884 case kJSTypeObject:
885 // XXX: this might could be more efficient
886 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
887 copy = false;
888 break;
889
890 default:
891 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
892 break;
893 }
894
895 if (cast != copy)
896 return object;
897 else if (copy)
898 return CYPoolRelease(pool, object);
899 else
900 return CFRetain(object);
901 }
902
903 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
904 return CYCFType(pool, context, value, true);
905 }
906
907 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
908 return CYCFType(pool, context, value, false);
909 }
910
911 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
912 CYPool pool;
913 size_t size(JSPropertyNameArrayGetCount(names));
914 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
915 for (size_t index(0); index != size; ++index)
916 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
917 return array;
918 }
919
920 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
921 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
922 }
923
924 void CYThrow(JSContextRef context, JSValueRef value) {
925 if (value == NULL)
926 return;
927 @throw CYCastNSObject(NULL, context, value);
928 }
929
930 JSValueRef CYJSNull(JSContextRef context) {
931 return JSValueMakeNull(context);
932 }
933
934 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
935 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
936 }
937
938 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
939 return CYCastJSValue(context, CYJSString(value));
940 }
941
942 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
943 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
944 }
945
946 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
947 JSValueRef exception(NULL);
948 JSObjectRef object(JSValueToObject(context, value, &exception));
949 CYThrow(context, exception);
950 return object;
951 }
952
953 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
954 JSValueRef exception(NULL);
955 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
956 CYThrow(context, exception);
957 return value;
958 }
959
960 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
961 JSValueRef exception(NULL);
962 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
963 CYThrow(context, exception);
964 return value;
965 }
966
967 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
968 JSValueRef exception(NULL);
969 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
970 CYThrow(context, exception);
971 }
972
973 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
974 if (exception == NULL)
975 throw error;
976 *exception = CYCastJSValue(context, error);
977 }
978
979 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
980 JSValueRef exception(NULL);
981 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
982 CYThrow(context, exception);
983 return value;
984 }
985
986 bool CYIsCallable(JSContextRef context, JSValueRef value) {
987 // XXX: this isn't actually correct
988 return value != NULL && JSValueIsObject(context, value);
989 }
990
991 @implementation CYJSObject
992
993 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
994 if ((self = [super init]) != nil) {
995 object_ = object;
996 context_ = context;
997 } return self;
998 }
999
1000 - (NSObject *) cy$toJSON:(NSString *)key {
1001 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1002 if (!CYIsCallable(context_, toJSON))
1003 return [super cy$toJSON:key];
1004 else {
1005 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1006 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1007 // XXX: do I really want an NSNull here?!
1008 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1009 }
1010 }
1011
1012 - (NSString *) cy$toCYON {
1013 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1014 if (!CYIsCallable(context_, toCYON))
1015 return [super cy$toCYON];
1016 else {
1017 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1018 return CYCastNSString(NULL, CYJSString(context_, value));
1019 }
1020 }
1021
1022 - (NSUInteger) count {
1023 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1024 size_t size(JSPropertyNameArrayGetCount(names));
1025 JSPropertyNameArrayRelease(names);
1026 return size;
1027 }
1028
1029 - (id) objectForKey:(id)key {
1030 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1031 }
1032
1033 - (NSEnumerator *) keyEnumerator {
1034 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1035 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1036 JSPropertyNameArrayRelease(names);
1037 return enumerator;
1038 }
1039
1040 - (void) setObject:(id)object forKey:(id)key {
1041 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1042 }
1043
1044 - (void) removeObjectForKey:(id)key {
1045 JSValueRef exception(NULL);
1046 // XXX: this returns a bool... throw exception, or ignore?
1047 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1048 CYThrow(context_, exception);
1049 }
1050
1051 @end
1052
1053 @implementation CYJSArray
1054
1055 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1056 if ((self = [super init]) != nil) {
1057 object_ = object;
1058 context_ = context;
1059 } return self;
1060 }
1061
1062 - (NSUInteger) count {
1063 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1064 }
1065
1066 - (id) objectAtIndex:(NSUInteger)index {
1067 JSValueRef exception(NULL);
1068 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1069 CYThrow(context_, exception);
1070 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1071 }
1072
1073 @end
1074
1075 CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1076 CYTry {
1077 CYPoolTry {
1078 id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1079 return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
1080 } CYPoolCatch(NULL)
1081 } CYCatch
1082 }
1083
1084 const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1085 if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
1086 const char *string(CYPoolCString(pool, json));
1087 [json release];
1088 return string;
1089 } else return NULL;
1090 }
1091
1092 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1093 CYTry {
1094 CYPool pool;
1095 NSString *self(CYCastNSObject(pool, context, object));
1096 NSString *name(CYCastNSString(pool, property));
1097 NSObject *data([self cy$getProperty:name]);
1098 return data == nil ? NULL : CYCastJSValue(context, data);
1099 } CYCatch
1100 }
1101
1102 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1103 CYTry {
1104 CYPool pool;
1105 NSString *self(CYCastNSObject(pool, context, object));
1106 NSString *name(CYCastNSString(pool, property));
1107 NSString *data(CYCastNSObject(pool, context, value));
1108 return [self cy$setProperty:name to:data];
1109 } CYCatch
1110 }
1111
1112 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1113 CYTry {
1114 CYPool pool;
1115 NSString *self(CYCastNSObject(pool, context, object));
1116 NSString *name(CYCastNSString(pool, property));
1117 return [self cy$deleteProperty:name];
1118 } CYCatch
1119 }
1120
1121 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1122 CYTry {
1123 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1124 return CYMakeInstance(context, [data->GetValue() alloc], true);
1125 } CYCatch
1126 }
1127
1128 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1129 Selector_privateData *data(new Selector_privateData(sel));
1130 return JSObjectMake(context, Selector_, data);
1131 }
1132
1133 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1134 Pointer_privateData *data(new Pointer_privateData(pointer));
1135 return JSObjectMake(context, Pointer_, data);
1136 }
1137
1138 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1139 Functor_privateData *data(new Functor_privateData(type, function));
1140 return JSObjectMake(context, Functor_, data);
1141 }
1142
1143 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1144 if (pool == NULL) {
1145 const char *string([CYCastNSString(NULL, value) UTF8String]);
1146 if (length != NULL)
1147 *length = strlen(string);
1148 return string;
1149 } else {
1150 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1151 char *string(new(pool) char[size]);
1152 JSStringGetUTF8CString(value, string, size);
1153 // XXX: this is ironic
1154 if (length != NULL)
1155 *length = strlen(string);
1156 return string;
1157 }
1158 }
1159
1160 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1161 if (!JSValueIsNull(context, value))
1162 return CYPoolCString(pool, CYJSString(context, value), length);
1163 else {
1164 if (length != NULL)
1165 *length = 0;
1166 return NULL;
1167 }
1168 }
1169
1170 // XXX: this macro is unhygenic
1171 #define CYCastCString(context, value) ({ \
1172 char *utf8; \
1173 if (value == NULL) \
1174 utf8 = NULL; \
1175 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1176 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1177 utf8 = reinterpret_cast<char *>(alloca(size)); \
1178 JSStringGetUTF8CString(string, utf8, size); \
1179 JSStringRelease(string); \
1180 } else \
1181 utf8 = NULL; \
1182 utf8; \
1183 })
1184
1185 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1186 if (JSValueIsNull(context, value))
1187 return NULL;
1188 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1189 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1190 return reinterpret_cast<SEL>(data->value_);
1191 } else
1192 return sel_registerName(CYCastCString(context, value));
1193 }
1194
1195 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1196 switch (JSValueGetType(context, value)) {
1197 case kJSTypeNull:
1198 return NULL;
1199 /*case kJSTypeString:
1200 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1201 case kJSTypeObject:
1202 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1203 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1204 return data->value_;
1205 }*/
1206 default:
1207 double number(CYCastDouble(context, value));
1208 if (std::isnan(number))
1209 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1210 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1211 }
1212 }
1213
1214 template <typename Type_>
1215 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1216 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1217 }
1218
1219 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1220 switch (type->primitive) {
1221 case sig::boolean_P:
1222 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1223 break;
1224
1225 #define CYPoolFFI_(primitive, native) \
1226 case sig::primitive ## _P: \
1227 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1228 break;
1229
1230 CYPoolFFI_(uchar, unsigned char)
1231 CYPoolFFI_(char, char)
1232 CYPoolFFI_(ushort, unsigned short)
1233 CYPoolFFI_(short, short)
1234 CYPoolFFI_(ulong, unsigned long)
1235 CYPoolFFI_(long, long)
1236 CYPoolFFI_(uint, unsigned int)
1237 CYPoolFFI_(int, int)
1238 CYPoolFFI_(ulonglong, unsigned long long)
1239 CYPoolFFI_(longlong, long long)
1240 CYPoolFFI_(float, float)
1241 CYPoolFFI_(double, double)
1242
1243 case sig::object_P:
1244 case sig::typename_P:
1245 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1246 break;
1247
1248 case sig::selector_P:
1249 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1250 break;
1251
1252 case sig::pointer_P:
1253 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1254 break;
1255
1256 case sig::string_P:
1257 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1258 break;
1259
1260 case sig::struct_P: {
1261 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1262 bool aggregate(JSValueIsObject(context, value));
1263 for (size_t index(0); index != type->data.signature.count; ++index) {
1264 ffi_type *element(ffi->elements[index]);
1265 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1266 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1267 // XXX: alignment?
1268 base += element->size;
1269 }
1270 } break;
1271
1272 case sig::void_P:
1273 break;
1274
1275 default:
1276 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1277 _assert(false);
1278 }
1279 }
1280
1281 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1282 JSValueRef value;
1283
1284 switch (type->primitive) {
1285 case sig::boolean_P:
1286 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1287 break;
1288
1289 #define CYFromFFI_(primitive, native) \
1290 case sig::primitive ## _P: \
1291 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1292 break;
1293
1294 CYFromFFI_(uchar, unsigned char)
1295 CYFromFFI_(char, char)
1296 CYFromFFI_(ushort, unsigned short)
1297 CYFromFFI_(short, short)
1298 CYFromFFI_(ulong, unsigned long)
1299 CYFromFFI_(long, long)
1300 CYFromFFI_(uint, unsigned int)
1301 CYFromFFI_(int, int)
1302 CYFromFFI_(ulonglong, unsigned long long)
1303 CYFromFFI_(longlong, long long)
1304 CYFromFFI_(float, float)
1305 CYFromFFI_(double, double)
1306
1307 case sig::object_P:
1308 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1309 break;
1310
1311 case sig::typename_P:
1312 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1313 break;
1314
1315 case sig::selector_P:
1316 if (SEL sel = *reinterpret_cast<SEL *>(data))
1317 value = CYMakeSelector(context, sel);
1318 else goto null;
1319 break;
1320
1321 case sig::pointer_P:
1322 if (void *pointer = *reinterpret_cast<void **>(data))
1323 value = CYMakePointer(context, pointer);
1324 else goto null;
1325 break;
1326
1327 case sig::string_P:
1328 if (char *utf8 = *reinterpret_cast<char **>(data))
1329 value = CYCastJSValue(context, utf8);
1330 else goto null;
1331 break;
1332
1333 case sig::struct_P:
1334 value = CYMakeStruct(context, data, type, ffi, owner);
1335 break;
1336
1337 case sig::void_P:
1338 value = CYJSUndefined(context);
1339 break;
1340
1341 null:
1342 value = CYJSNull(context);
1343 break;
1344
1345 default:
1346 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1347 _assert(false);
1348 }
1349
1350 return value;
1351 }
1352
1353 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1354 Type_privateData *typical(internal->type_);
1355
1356 size_t length;
1357 const char *name(CYPoolCString(pool, property, &length));
1358 double number(CYCastDouble(name, length));
1359
1360 if (std::isnan(number)) {
1361 if (property == NULL)
1362 return false;
1363
1364 // XXX: implement!
1365 return false;
1366 } else {
1367 index = static_cast<ssize_t>(number);
1368 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1369 return false;
1370 }
1371
1372 base = reinterpret_cast<uint8_t *>(internal->value_);
1373 for (ssize_t local(0); local != index; ++local)
1374 base += typical->ffi_.elements[local]->size;
1375
1376 return true;
1377 }
1378
1379 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1380 CYTry {
1381 CYPool pool;
1382 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1383 Type_privateData *typical(internal->type_);
1384
1385 ssize_t index;
1386 uint8_t *base;
1387
1388 if (!Index_(pool, internal, property, index, base))
1389 return NULL;
1390
1391 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1392 } CYCatch
1393 }
1394
1395 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1396 CYTry {
1397 CYPool pool;
1398 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1399 Type_privateData *typical(internal->type_);
1400
1401 ssize_t index;
1402 uint8_t *base;
1403
1404 if (!Index_(pool, internal, property, index, base))
1405 return false;
1406
1407 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1408 return true;
1409 } CYCatch
1410 }
1411
1412 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1413 CYTry {
1414 if (count != signature->count - 1)
1415 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1416
1417 CYPool pool;
1418 void *values[count];
1419
1420 for (unsigned index(0); index != count; ++index) {
1421 sig::Element *element(&signature->elements[index + 1]);
1422 ffi_type *ffi(cif->arg_types[index]);
1423 // XXX: alignment?
1424 values[index] = new(pool) uint8_t[ffi->size];
1425 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1426 }
1427
1428 uint8_t value[cif->rtype->size];
1429 ffi_call(cif, function, value, values);
1430
1431 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1432 } CYCatch
1433 }
1434
1435 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1436 ffoData *data(reinterpret_cast<ffoData *>(arg));
1437
1438 JSContextRef context(data->context_);
1439
1440 size_t count(data->cif_.nargs);
1441 JSValueRef values[count];
1442
1443 for (size_t index(0); index != count; ++index)
1444 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1445
1446 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1447 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1448 }
1449
1450 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1451 // XXX: in case of exceptions this will leak
1452 ffoData *data(new ffoData(type));
1453
1454 ffi_closure *closure;
1455 _syscall(closure = (ffi_closure *) mmap(
1456 NULL, sizeof(ffi_closure),
1457 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1458 -1, 0
1459 ));
1460
1461 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1462 _assert(status == FFI_OK);
1463
1464 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1465
1466 data->value_ = closure;
1467
1468 data->context_ = CYGetJSContext();
1469 data->function_ = function;
1470
1471 return JSObjectMake(context, Functor_, data);
1472 }
1473
1474 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1475 CYTry {
1476 CYPool pool;
1477 NSString *name(CYCastNSString(pool, property));
1478 if (Class _class = NSClassFromString(name))
1479 return CYMakeInstance(context, _class, true);
1480 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1481 switch ([[entry objectAtIndex:0] intValue]) {
1482 case 0:
1483 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1484 case 1:
1485 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1486 case 2:
1487 // XXX: this is horrendously inefficient
1488 sig::Signature signature;
1489 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1490 ffi_cif cif;
1491 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1492 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1493 }
1494 return NULL;
1495 } CYCatch
1496 }
1497
1498 bool stret(ffi_type *ffi_type) {
1499 return ffi_type->type == FFI_TYPE_STRUCT && (
1500 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1501 struct_forward_array[ffi_type->size] != 0
1502 );
1503 }
1504
1505 extern "C" {
1506 int *_NSGetArgc(void);
1507 char ***_NSGetArgv(void);
1508 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1509 }
1510
1511 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1512 CYTry {
1513 NSLog(@"%s", CYCastCString(context, arguments[0]));
1514 return CYJSUndefined(context);
1515 } CYCatch
1516 }
1517
1518 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1519 CYTry {
1520 CYPool pool;
1521 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1522 int argc(*_NSGetArgc());
1523 char **argv(*_NSGetArgv());
1524 for (int i(0); i != argc; ++i)
1525 NSLog(@"argv[%i]=%s", i, argv[i]);
1526 _pooled
1527 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1528 } CYCatch
1529 }
1530
1531 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1532 const char *type;
1533
1534 CYPool pool;
1535
1536 CYTry {
1537 if (count < 2)
1538 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1539
1540 id self(CYCastNSObject(pool, context, arguments[0]));
1541 if (self == nil)
1542 return CYJSNull(context);
1543
1544 SEL _cmd(CYCastSEL(context, arguments[1]));
1545
1546 Class _class(object_getClass(self));
1547 if (Method method = class_getInstanceMethod(_class, _cmd))
1548 type = method_getTypeEncoding(method);
1549 else {
1550 CYPoolTry {
1551 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1552 if (method == nil)
1553 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1554 type = CYPoolCString(pool, [method _typeString]);
1555 } CYPoolCatch(NULL)
1556 }
1557 } CYCatch
1558
1559 sig::Signature signature;
1560 sig::Parse(pool, &signature, type);
1561
1562 ffi_cif cif;
1563 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1564
1565 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1566 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1567 }
1568
1569 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1570 JSValueRef setup[count + 2];
1571 setup[0] = _this;
1572 setup[1] = object;
1573 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1574 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1575 }
1576
1577 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1578 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1579 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1580 }
1581
1582 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1583 CYTry {
1584 if (count != 1)
1585 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1586 const char *name(CYCastCString(context, arguments[0]));
1587 return CYMakeSelector(context, sel_registerName(name));
1588 } CYCatch
1589 }
1590
1591 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1592 CYTry {
1593 if (count != 2)
1594 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1595 const char *type(CYCastCString(context, arguments[1]));
1596 JSValueRef exception(NULL);
1597 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1598 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1599 return CYMakeFunctor(context, function, type);
1600 } else if (exception != NULL) {
1601 return NULL;
1602 } else {
1603 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1604 return CYMakeFunctor(context, function, type);
1605 }
1606 } CYCatch
1607 }
1608
1609 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1610 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1611 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1612 }
1613
1614 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1615 return Function_;
1616 }
1617
1618 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1619 CYTry {
1620 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1621 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1622 } CYCatch
1623 }
1624
1625 static JSValueRef Pointer_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1626 return Pointer_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1627 }
1628
1629 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1630 CYTry {
1631 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1632 CYPoolTry {
1633 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toCYON]));
1634 } CYPoolCatch(NULL)
1635 } CYCatch
1636 }
1637
1638 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1639 CYTry {
1640 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1641 CYPoolTry {
1642 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
1643 return CYCastJSValue(context, CYJSString([data->GetValue() cy$toJSON:key]));
1644 } CYPoolCatch(NULL)
1645 } CYCatch
1646 }
1647
1648 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1649 CYTry {
1650 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1651 CYPoolTry {
1652 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1653 } CYPoolCatch(NULL)
1654 } CYCatch
1655 }
1656
1657 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1658 CYTry {
1659 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1660 return CYCastJSValue(context, sel_getName(data->GetValue()));
1661 } CYCatch
1662 }
1663
1664 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1665 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
1666 }
1667
1668 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1669 CYTry {
1670 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1671 const char *name(sel_getName(data->GetValue()));
1672 CYPoolTry {
1673 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
1674 } CYPoolCatch(NULL)
1675 } CYCatch
1676 }
1677
1678 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1679 CYTry {
1680 if (count != 2)
1681 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1682 CYPool pool;
1683 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1684 Class _class(CYCastNSObject(pool, context, arguments[0]));
1685 bool instance(CYCastBool(context, arguments[1]));
1686 SEL sel(data->GetValue());
1687 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1688 return CYCastJSValue(context, method_getTypeEncoding(method));
1689 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1690 return CYCastJSValue(context, CYJSString(type));
1691 else
1692 return CYJSNull(context);
1693 } CYCatch
1694 }
1695
1696 static JSStaticValue Pointer_staticValues[2] = {
1697 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1698 {NULL, NULL, NULL, 0}
1699 };
1700
1701 static JSStaticFunction Pointer_staticFunctions[3] = {
1702 {"toJSON", &Pointer_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1703 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1704 {NULL, NULL, 0}
1705 };
1706
1707 /*static JSStaticValue Selector_staticValues[2] = {
1708 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1709 {NULL, NULL, NULL, 0}
1710 };*/
1711
1712 static JSStaticFunction Instance_staticFunctions[4] = {
1713 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1714 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1715 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1716 {NULL, NULL, 0}
1717 };
1718
1719 static JSStaticFunction Selector_staticFunctions[5] = {
1720 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1721 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1722 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1723 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1724 {NULL, NULL, 0}
1725 };
1726
1727 CYDriver::CYDriver(const std::string &filename) :
1728 state_(CYClear),
1729 data_(NULL),
1730 size_(0),
1731 filename_(filename),
1732 source_(NULL)
1733 {
1734 ScannerInit();
1735 }
1736
1737 CYDriver::~CYDriver() {
1738 ScannerDestroy();
1739 }
1740
1741 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1742 CYDriver::Error error;
1743 error.location_ = location;
1744 error.message_ = message;
1745 driver.errors_.push_back(error);
1746 }
1747
1748 void CYSetArgs(int argc, const char *argv[]) {
1749 JSContextRef context(CYGetJSContext());
1750 JSValueRef args[argc];
1751 for (int i(0); i != argc; ++i)
1752 args[i] = CYCastJSValue(context, argv[i]);
1753 JSValueRef exception(NULL);
1754 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1755 CYThrow(context, exception);
1756 CYSetProperty(context, System_, CYJSString("args"), array);
1757 }
1758
1759 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1760 return JSContextGetGlobalObject(context);
1761 }
1762
1763 MSInitialize { _pooled
1764 apr_initialize();
1765
1766 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1767
1768 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1769
1770 JSClassDefinition definition;
1771
1772 definition = kJSClassDefinitionEmpty;
1773 definition.className = "Pointer";
1774 definition.staticValues = Pointer_staticValues;
1775 definition.staticFunctions = Pointer_staticFunctions;
1776 definition.finalize = &CYData::Finalize;
1777 Pointer_ = JSClassCreate(&definition);
1778
1779 definition = kJSClassDefinitionEmpty;
1780 definition.className = "Functor";
1781 definition.staticValues = Pointer_staticValues;
1782 definition.staticFunctions = Pointer_staticFunctions;
1783 definition.callAsFunction = &Functor_callAsFunction;
1784 definition.finalize = &CYData::Finalize;
1785 Functor_ = JSClassCreate(&definition);
1786
1787 definition = kJSClassDefinitionEmpty;
1788 definition.className = "Struct";
1789 definition.getProperty = &Struct_getProperty;
1790 definition.setProperty = &Struct_setProperty;
1791 definition.finalize = &CYData::Finalize;
1792 Struct_ = JSClassCreate(&definition);
1793
1794 definition = kJSClassDefinitionEmpty;
1795 definition.className = "Selector";
1796 definition.staticValues = Pointer_staticValues;
1797 //definition.staticValues = Selector_staticValues;
1798 definition.staticFunctions = Selector_staticFunctions;
1799 definition.callAsFunction = &Selector_callAsFunction;
1800 definition.finalize = &CYData::Finalize;
1801 Selector_ = JSClassCreate(&definition);
1802
1803 definition = kJSClassDefinitionEmpty;
1804 definition.className = "Instance";
1805 definition.staticValues = Pointer_staticValues;
1806 definition.staticFunctions = Instance_staticFunctions;
1807 definition.getProperty = &Instance_getProperty;
1808 definition.setProperty = &Instance_setProperty;
1809 definition.deleteProperty = &Instance_deleteProperty;
1810 definition.callAsConstructor = &Instance_callAsConstructor;
1811 definition.finalize = &CYData::Finalize;
1812 Instance_ = JSClassCreate(&definition);
1813
1814 definition = kJSClassDefinitionEmpty;
1815 definition.className = "Runtime";
1816 definition.getProperty = &Runtime_getProperty;
1817 Runtime_ = JSClassCreate(&definition);
1818
1819 definition = kJSClassDefinitionEmpty;
1820 //definition.getProperty = &Global_getProperty;
1821 JSClassRef Global(JSClassCreate(&definition));
1822
1823 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1824 Context_ = context;
1825
1826 JSObjectRef global(CYGetGlobalObject(context));
1827
1828 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1829 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1830
1831 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1832 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1833
1834 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1835 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1836
1837 System_ = JSObjectMake(context, NULL, NULL);
1838 CYSetProperty(context, global, CYJSString("system"), System_);
1839 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1840 //CYSetProperty(context, System_, CYJSString("global"), global);
1841
1842 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1843
1844 length_ = JSStringCreateWithUTF8CString("length");
1845 message_ = JSStringCreateWithUTF8CString("message");
1846 name_ = JSStringCreateWithUTF8CString("name");
1847 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1848 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1849
1850 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1851 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1852 }