]> git.saurik.com Git - cycript.git/blob - Library.mm
aa6569713c52c8180fc456ad22c1a2886fe0a886
[cycript.git] / Library.mm
1 /* Cyrker - 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 <CFNetwork/CFNetwork.h>
57
58 #include <WebKit/WebScriptObject.h>
59
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63 #include <sys/mman.h>
64
65 #include <iostream>
66 #include <ext/stdio_filebuf.h>
67 #include <set>
68 #include <map>
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 Selector_;
108
109 static JSObjectRef Array_;
110 static JSObjectRef Function_;
111
112 static JSStringRef name_;
113 static JSStringRef message_;
114 static JSStringRef length_;
115
116 static Class NSCFBoolean_;
117
118 static NSMutableDictionary *Bridge_;
119
120 struct Client {
121 CFHTTPMessageRef message_;
122 CFSocketRef socket_;
123 };
124
125 struct ptrData {
126 apr_pool_t *pool_;
127 void *value_;
128 sig::Type type_;
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<ptrData *>(data)->pool_ = pool;
135 return data;;
136 }
137
138 ptrData(void *value) :
139 value_(value)
140 {
141 }
142
143 virtual ~ptrData() {
144 }
145 };
146
147 struct ffiData : ptrData {
148 sig::Signature signature_;
149 ffi_cif cif_;
150
151 ffiData(const char *type, void (*value)()) :
152 ptrData(reinterpret_cast<void *>(value))
153 {
154 sig::Parse(pool_, &signature_, type);
155 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
156 }
157 };
158
159 struct ffoData : ffiData {
160 JSContextRef context_;
161 JSObjectRef function_;
162
163 ffoData(const char *type) :
164 ffiData(type, NULL)
165 {
166 }
167 };
168
169 struct selData : ptrData {
170 selData(SEL value) :
171 ptrData(value)
172 {
173 }
174
175 SEL GetValue() const {
176 return reinterpret_cast<SEL>(value_);
177 }
178 };
179
180 struct jocData : ptrData {
181 bool transient_;
182
183 jocData(id value, bool transient) :
184 ptrData(value)
185 {
186 }
187
188 virtual ~jocData() {
189 if (!transient_)
190 [GetValue() release];
191 }
192
193 id GetValue() const {
194 return reinterpret_cast<id>(value_);
195 }
196 };
197
198 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
199 if (!transient)
200 object = [object retain];
201 jocData *data(new jocData(object, transient));
202 return JSObjectMake(context, Instance_, data);
203 }
204
205 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
206 if (pool == NULL)
207 return [value UTF8String];
208 else {
209 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
210 char *string(new(pool) char[size]);
211 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
212 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
213 return string;
214 }
215 }
216
217 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
218 return JSValueMakeBoolean(context, value);
219 }
220
221 JSValueRef CYCastJSValue(JSContextRef context, double value) {
222 return JSValueMakeNumber(context, value);
223 }
224
225 #define CYCastJSValue_(Type_) \
226 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
227 return JSValueMakeNumber(context, static_cast<double>(value)); \
228 }
229
230 CYCastJSValue_(int)
231 CYCastJSValue_(unsigned int)
232 CYCastJSValue_(long int)
233 CYCastJSValue_(long unsigned int)
234 CYCastJSValue_(long long int)
235 CYCastJSValue_(long long unsigned int)
236
237 JSValueRef CYJSUndefined(JSContextRef context) {
238 return JSValueMakeUndefined(context);
239 }
240
241 @interface NSMethodSignature (Cycript)
242 - (NSString *) _typeString;
243 @end
244
245 @interface NSObject (Cycript)
246 - (bool) cy$isUndefined;
247 - (NSString *) cy$toJSON;
248 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
249 - (NSObject *) cy$getProperty:(NSString *)name;
250 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
251 - (bool) cy$deleteProperty:(NSString *)name;
252 @end
253
254 @interface NSString (Cycript)
255 - (void *) cy$symbol;
256 @end
257
258 @interface NSNumber (Cycript)
259 - (void *) cy$symbol;
260 @end
261
262 @implementation NSObject (Cycript)
263
264 - (bool) cy$isUndefined {
265 return false;
266 }
267
268 - (NSString *) cy$toJSON {
269 return [self description];
270 }
271
272 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
273 return CYMakeInstance(context, self, transient);
274 }
275
276 - (NSObject *) cy$getProperty:(NSString *)name {
277 NSLog(@"get:%@", name);
278 return nil;
279 }
280
281 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
282 NSLog(@"set:%@", name);
283 return false;
284 }
285
286 - (bool) cy$deleteProperty:(NSString *)name {
287 NSLog(@"delete:%@", name);
288 return false;
289 }
290
291 @end
292
293 @implementation WebUndefined (Cycript)
294
295 - (bool) cy$isUndefined {
296 return true;
297 }
298
299 - (NSString *) cy$toJSON {
300 return @"undefined";
301 }
302
303 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
304 return CYJSUndefined(context);
305 }
306
307 @end
308
309 @implementation NSNull (Cycript)
310
311 - (NSString *) cy$toJSON {
312 return @"null";
313 }
314
315 @end
316
317 @implementation NSArray (Cycript)
318
319 - (NSString *) cy$toJSON {
320 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
321 [json appendString:@"["];
322
323 bool comma(false);
324 for (id object in self) {
325 if (comma)
326 [json appendString:@","];
327 else
328 comma = true;
329 if (![object cy$isUndefined])
330 [json appendString:[object cy$toJSON]];
331 else {
332 [json appendString:@","];
333 comma = false;
334 }
335 }
336
337 [json appendString:@"]"];
338 return json;
339 }
340
341 - (NSObject *) cy$getProperty:(NSString *)name {
342 int index([name intValue]);
343 if (index < 0 || index >= static_cast<int>([self count]))
344 return [super cy$getProperty:name];
345 else
346 return [self objectAtIndex:index];
347 }
348
349 @end
350
351 @implementation NSMutableArray (Cycript)
352
353 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
354 int index([name intValue]);
355 if (index < 0 || index >= static_cast<int>([self count]))
356 return [super cy$setProperty:name to:value];
357 else {
358 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
359 return true;
360 }
361 }
362
363 - (bool) cy$deleteProperty:(NSString *)name {
364 int index([name intValue]);
365 if (index < 0 || index >= static_cast<int>([self count]))
366 return [super cy$deleteProperty:name];
367 else {
368 [self removeObjectAtIndex:index];
369 return true;
370 }
371 }
372
373 @end
374
375 @implementation NSDictionary (Cycript)
376
377 - (NSString *) cy$toJSON {
378 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
379 [json appendString:@"({"];
380
381 bool comma(false);
382 for (id key in self) {
383 if (comma)
384 [json appendString:@","];
385 else
386 comma = true;
387 [json appendString:[key cy$toJSON]];
388 [json appendString:@":"];
389 NSObject *object([self objectForKey:key]);
390 [json appendString:[object cy$toJSON]];
391 }
392
393 [json appendString:@"})"];
394 return json;
395 }
396
397 - (NSObject *) cy$getProperty:(NSString *)name {
398 return [self objectForKey:name];
399 }
400
401 @end
402
403 @implementation NSMutableDictionary (Cycript)
404
405 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
406 [self setObject:(value ?: [NSNull null]) forKey:name];
407 return true;
408 }
409
410 - (bool) cy$deleteProperty:(NSString *)name {
411 if ([self objectForKey:name] == nil)
412 return false;
413 else {
414 [self removeObjectForKey:name];
415 return true;
416 }
417 }
418
419 @end
420
421 @implementation NSNumber (Cycript)
422
423 - (NSString *) cy$toJSON {
424 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
425 }
426
427 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
428 return [self class] != NSCFBoolean_ ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
429 }
430
431 - (void *) cy$symbol {
432 return [self pointerValue];
433 }
434
435 @end
436
437 @implementation NSString (Cycript)
438
439 - (NSString *) cy$toJSON {
440 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
441
442 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
443 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
444 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
445 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
446 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
447
448 CFStringInsert(json, 0, CFSTR("\""));
449 CFStringAppend(json, CFSTR("\""));
450
451 return [reinterpret_cast<const NSString *>(json) autorelease];
452 }
453
454 - (void *) cy$symbol {
455 CYPool pool;
456 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
457 }
458
459 @end
460
461 @interface CYJSObject : NSDictionary {
462 JSObjectRef object_;
463 JSContextRef context_;
464 }
465
466 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
467
468 - (NSUInteger) count;
469 - (id) objectForKey:(id)key;
470 - (NSEnumerator *) keyEnumerator;
471 - (void) setObject:(id)object forKey:(id)key;
472 - (void) removeObjectForKey:(id)key;
473
474 @end
475
476 @interface CYJSArray : NSArray {
477 JSObjectRef object_;
478 JSContextRef context_;
479 }
480
481 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
482
483 - (NSUInteger) count;
484 - (id) objectAtIndex:(NSUInteger)index;
485
486 @end
487
488 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
489 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
490
491 JSGlobalContextRef CYGetJSContext() {
492 return Context_;
493 }
494
495 #define CYTry \
496 @try
497 #define CYCatch \
498 @catch (id error) { \
499 NSLog(@"e:%@", error); \
500 CYThrow(context, error, exception); \
501 return NULL; \
502 }
503
504 void CYThrow(JSContextRef context, JSValueRef value);
505
506 apr_status_t CYPoolRelease_(void *data) {
507 id object(reinterpret_cast<id>(data));
508 [object release];
509 return APR_SUCCESS;
510 }
511
512 id CYPoolRelease(apr_pool_t *pool, id object) {
513 if (pool == NULL)
514 return [object autorelease];
515 else {
516 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
517 return object;
518 }
519 }
520
521 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
522 if (JSValueIsObjectOfClass(context, object, Instance_)) {
523 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(object)));
524 return data->GetValue();
525 }
526
527 JSValueRef exception(NULL);
528 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
529 CYThrow(context, exception);
530 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
531 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
532 }
533
534 JSStringRef CYCopyJSString(id value) {
535 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
536 }
537
538 JSStringRef CYCopyJSString(const char *value) {
539 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
540 }
541
542 JSStringRef CYCopyJSString(JSStringRef value) {
543 return value == NULL ? NULL : JSStringRetain(value);
544 }
545
546 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
547 if (JSValueIsNull(context, value))
548 return NULL;
549 JSValueRef exception(NULL);
550 JSStringRef string(JSValueToStringCopy(context, value, &exception));
551 CYThrow(context, exception);
552 return string;
553 }
554
555 class CYJSString {
556 private:
557 JSStringRef string_;
558
559 void Clear_() {
560 JSStringRelease(string_);
561 }
562
563 public:
564 CYJSString(const CYJSString &rhs) :
565 string_(CYCopyJSString(rhs.string_))
566 {
567 }
568
569 template <typename Arg0_>
570 CYJSString(Arg0_ arg0) :
571 string_(CYCopyJSString(arg0))
572 {
573 }
574
575 template <typename Arg0_, typename Arg1_>
576 CYJSString(Arg0_ arg0, Arg1_ arg1) :
577 string_(CYCopyJSString(arg0, arg1))
578 {
579 }
580
581 CYJSString &operator =(const CYJSString &rhs) {
582 Clear_();
583 string_ = CYCopyJSString(rhs.string_);
584 return *this;
585 }
586
587 ~CYJSString() {
588 Clear_();
589 }
590
591 void Clear() {
592 Clear_();
593 string_ = NULL;
594 }
595
596 operator JSStringRef() const {
597 return string_;
598 }
599 };
600
601 CFStringRef CYCopyCFString(JSStringRef value) {
602 return JSStringCopyCFString(kCFAllocatorDefault, value);
603 }
604
605 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
606 return CYCopyCFString(CYJSString(context, value));
607 }
608
609 double CYCastDouble(JSContextRef context, JSValueRef value) {
610 JSValueRef exception(NULL);
611 double number(JSValueToNumber(context, value, &exception));
612 CYThrow(context, exception);
613 return number;
614 }
615
616 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
617 double number(CYCastDouble(context, value));
618 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
619 }
620
621 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
622 return CYPoolRelease(pool, reinterpret_cast<const NSString *>(CYCopyCFString(value)));
623 }
624
625 bool CYCastBool(JSContextRef context, JSValueRef value) {
626 return JSValueToBoolean(context, value);
627 }
628
629 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
630 CFTypeRef object;
631 bool copy;
632
633 switch (JSType type = JSValueGetType(context, value)) {
634 case kJSTypeUndefined:
635 object = [WebUndefined undefined];
636 copy = false;
637 break;
638
639 case kJSTypeNull:
640 return NULL;
641 break;
642
643 case kJSTypeBoolean:
644 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
645 copy = false;
646 break;
647
648 case kJSTypeNumber:
649 object = CYCopyCFNumber(context, value);
650 copy = true;
651 break;
652
653 case kJSTypeString:
654 object = CYCopyCFString(context, value);
655 copy = true;
656 break;
657
658 case kJSTypeObject:
659 // XXX: this might could be more efficient
660 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
661 copy = false;
662 break;
663
664 default:
665 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
666 break;
667 }
668
669 if (cast != copy)
670 return object;
671 else if (copy)
672 return CYPoolRelease(pool, (id) object);
673 else
674 return CFRetain(object);
675 }
676
677 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
678 return CYCFType(pool, context, value, true);
679 }
680
681 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
682 return CYCFType(pool, context, value, false);
683 }
684
685 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
686 CYPool pool;
687 size_t size(JSPropertyNameArrayGetCount(names));
688 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
689 for (size_t index(0); index != size; ++index)
690 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
691 return array;
692 }
693
694 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
695 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
696 }
697
698 void CYThrow(JSContextRef context, JSValueRef value) {
699 if (value == NULL)
700 return;
701 @throw CYCastNSObject(NULL, context, value);
702 }
703
704 JSValueRef CYJSNull(JSContextRef context) {
705 return JSValueMakeNull(context);
706 }
707
708 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
709 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
710 }
711
712 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
713 return CYCastJSValue(context, CYJSString(value));
714 }
715
716 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
717 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
718 }
719
720 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
721 JSValueRef exception(NULL);
722 JSObjectRef object(JSValueToObject(context, value, &exception));
723 CYThrow(context, exception);
724 return object;
725 }
726
727 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
728 JSValueRef exception(NULL);
729 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
730 CYThrow(context, exception);
731 return value;
732 }
733
734 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
735 JSValueRef exception(NULL);
736 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
737 CYThrow(context, exception);
738 }
739
740 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
741 if (exception == NULL)
742 throw error;
743 *exception = CYCastJSValue(context, error);
744 }
745
746 @implementation CYJSObject
747
748 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
749 if ((self = [super init]) != nil) {
750 object_ = object;
751 context_ = context;
752 } return self;
753 }
754
755 - (NSUInteger) count {
756 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
757 size_t size(JSPropertyNameArrayGetCount(names));
758 JSPropertyNameArrayRelease(names);
759 return size;
760 }
761
762 - (id) objectForKey:(id)key {
763 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
764 }
765
766 - (NSEnumerator *) keyEnumerator {
767 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
768 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
769 JSPropertyNameArrayRelease(names);
770 return enumerator;
771 }
772
773 - (void) setObject:(id)object forKey:(id)key {
774 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
775 }
776
777 - (void) removeObjectForKey:(id)key {
778 JSValueRef exception(NULL);
779 // XXX: this returns a bool... throw exception, or ignore?
780 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
781 CYThrow(context_, exception);
782 }
783
784 @end
785
786 @implementation CYJSArray
787
788 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
789 if ((self = [super init]) != nil) {
790 object_ = object;
791 context_ = context;
792 } return self;
793 }
794
795 - (NSUInteger) count {
796 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
797 }
798
799 - (id) objectAtIndex:(NSUInteger)index {
800 JSValueRef exception(NULL);
801 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
802 CYThrow(context_, exception);
803 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
804 }
805
806 @end
807
808 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
809 CYTry {
810 CYPoolTry {
811 id object(CYCastNSObject(NULL, context, value));
812 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
813 } CYPoolCatch(NULL)
814 } CYCatch
815 }
816
817 const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
818 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
819 const char *string(CYPoolCString(pool, json));
820 [json release];
821 return string;
822 } else return NULL;
823 }
824
825 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
826 switch (type) {
827 case kCFSocketDataCallBack:
828 CFDataRef data(reinterpret_cast<CFDataRef>(value));
829 Client *client(reinterpret_cast<Client *>(info));
830
831 if (client->message_ == NULL)
832 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
833
834 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
835 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
836 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
837 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
838 Boolean absolute;
839 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
840 CFRelease(client->message_);
841
842 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
843 CFRelease(path);
844
845 JSStringRef script(JSStringCreateWithCFString(code));
846 CFRelease(code);
847
848 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
849 JSStringRelease(script);
850
851 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
852 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
853
854 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
855 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
856 CFRelease(json);
857
858 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
859 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
860 CFRelease(length);
861
862 CFHTTPMessageSetBody(response, body);
863 CFRelease(body);
864
865 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
866 CFRelease(response);
867
868 CFSocketSendData(socket, NULL, serialized, 0);
869 CFRelease(serialized);
870
871 CFRelease(url);
872 }
873 break;
874 }
875 }
876
877 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
878 switch (type) {
879 case kCFSocketAcceptCallBack:
880 Client *client(new Client());
881
882 client->message_ = NULL;
883
884 CFSocketContext context;
885 context.version = 0;
886 context.info = client;
887 context.retain = NULL;
888 context.release = NULL;
889 context.copyDescription = NULL;
890
891 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
892
893 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
894 break;
895 }
896 }
897
898 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
899 CYTry {
900 CYPool pool;
901 NSString *self(CYCastNSObject(pool, context, object));
902 NSString *name(CYCastNSString(pool, property));
903 NSObject *data([self cy$getProperty:name]);
904 return data == nil ? NULL : CYCastJSValue(context, data);
905 } CYCatch
906 }
907
908 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
909 CYTry {
910 CYPool pool;
911 NSString *self(CYCastNSObject(pool, context, object));
912 NSString *name(CYCastNSString(pool, property));
913 NSString *data(CYCastNSObject(pool, context, value));
914 return [self cy$setProperty:name to:data];
915 } CYCatch
916 }
917
918 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
919 CYTry {
920 CYPool pool;
921 NSString *self(CYCastNSObject(pool, context, object));
922 NSString *name(CYCastNSString(pool, property));
923 return [self cy$deleteProperty:name];
924 } CYCatch
925 }
926
927 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
928 CYTry {
929 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(object)));
930 return CYMakeInstance(context, [data->GetValue() alloc], true);
931 } CYCatch
932 }
933
934 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
935 selData *data(new selData(sel));
936 return JSObjectMake(context, Selector_, data);
937 }
938
939 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
940 ptrData *data(new ptrData(pointer));
941 return JSObjectMake(context, Pointer_, data);
942 }
943
944 static void Pointer_finalize(JSObjectRef object) {
945 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
946 data->~ptrData();
947 apr_pool_destroy(data->pool_);
948 }
949
950 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
951 ffiData *data(new ffiData(type, function));
952 return JSObjectMake(context, Functor_, data);
953 }
954
955 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
956 if (pool == NULL)
957 return [CYCastNSString(NULL, value) UTF8String];
958 else {
959 size_t size(JSStringGetMaximumUTF8CStringSize(value));
960 char *string(new(pool) char[size]);
961 JSStringGetUTF8CString(value, string, size);
962 return string;
963 }
964 }
965
966 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
967 if (JSValueIsNull(context, value))
968 return NULL;
969 return CYPoolCString(pool, CYJSString(context, value));
970 }
971
972 // XXX: this macro is unhygenic
973 #define CYCastCString(context, value) ({ \
974 char *utf8; \
975 if (value == NULL) \
976 utf8 = NULL; \
977 else if (JSStringRef string = CYCopyJSString(context, value)) { \
978 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
979 utf8 = reinterpret_cast<char *>(alloca(size)); \
980 JSStringGetUTF8CString(string, utf8, size); \
981 JSStringRelease(string); \
982 } else \
983 utf8 = NULL; \
984 utf8; \
985 })
986
987 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
988 if (JSValueIsNull(context, value))
989 return NULL;
990 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
991 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
992 return reinterpret_cast<SEL>(data->value_);
993 } else
994 return sel_registerName(CYCastCString(context, value));
995 }
996
997 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
998 switch (JSValueGetType(context, value)) {
999 case kJSTypeNull:
1000 return NULL;
1001 case kJSTypeString:
1002 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1003 case kJSTypeObject:
1004 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1005 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
1006 return data->value_;
1007 }
1008 default:
1009 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
1010 }
1011 }
1012
1013 template <typename Type_>
1014 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1015 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1016 }
1017
1018 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
1019 switch (type->primitive) {
1020 case sig::boolean_P:
1021 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1022 break;
1023
1024 #define CYPoolFFI_(primitive, native) \
1025 case sig::primitive ## _P: \
1026 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1027 break;
1028
1029 CYPoolFFI_(uchar, unsigned char)
1030 CYPoolFFI_(char, char)
1031 CYPoolFFI_(ushort, unsigned short)
1032 CYPoolFFI_(short, short)
1033 CYPoolFFI_(ulong, unsigned long)
1034 CYPoolFFI_(long, long)
1035 CYPoolFFI_(uint, unsigned int)
1036 CYPoolFFI_(int, int)
1037 CYPoolFFI_(ulonglong, unsigned long long)
1038 CYPoolFFI_(longlong, long long)
1039 CYPoolFFI_(float, float)
1040 CYPoolFFI_(double, double)
1041
1042 case sig::object_P:
1043 case sig::typename_P:
1044 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1045 break;
1046
1047 case sig::selector_P:
1048 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1049 break;
1050
1051 case sig::pointer_P:
1052 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1053 break;
1054
1055 case sig::string_P:
1056 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1057 break;
1058
1059 case sig::struct_P:
1060 goto fail;
1061
1062 case sig::void_P:
1063 break;
1064
1065 default: fail:
1066 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1067 _assert(false);
1068 }
1069 }
1070
1071 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
1072 JSValueRef value;
1073
1074 switch (type->primitive) {
1075 case sig::boolean_P:
1076 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1077 break;
1078
1079 #define CYFromFFI_(primitive, native) \
1080 case sig::primitive ## _P: \
1081 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1082 break;
1083
1084 CYFromFFI_(uchar, unsigned char)
1085 CYFromFFI_(char, char)
1086 CYFromFFI_(ushort, unsigned short)
1087 CYFromFFI_(short, short)
1088 CYFromFFI_(ulong, unsigned long)
1089 CYFromFFI_(long, long)
1090 CYFromFFI_(uint, unsigned int)
1091 CYFromFFI_(int, int)
1092 CYFromFFI_(ulonglong, unsigned long long)
1093 CYFromFFI_(longlong, long long)
1094 CYFromFFI_(float, float)
1095 CYFromFFI_(double, double)
1096
1097 case sig::object_P:
1098 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1099 break;
1100
1101 case sig::typename_P:
1102 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1103 break;
1104
1105 case sig::selector_P:
1106 if (SEL sel = *reinterpret_cast<SEL *>(data))
1107 value = CYMakeSelector(context, sel);
1108 else goto null;
1109 break;
1110
1111 case sig::pointer_P:
1112 if (void *pointer = *reinterpret_cast<void **>(data))
1113 value = CYMakePointer(context, pointer);
1114 else goto null;
1115 break;
1116
1117 case sig::string_P:
1118 if (char *utf8 = *reinterpret_cast<char **>(data))
1119 value = CYCastJSValue(context, utf8);
1120 else goto null;
1121 break;
1122
1123 case sig::struct_P:
1124 goto fail;
1125
1126 case sig::void_P:
1127 value = CYJSUndefined(context);
1128 break;
1129
1130 null:
1131 value = CYJSNull(context);
1132 break;
1133
1134 default: fail:
1135 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1136 _assert(false);
1137 }
1138
1139 return value;
1140 }
1141
1142 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1143 CYTry {
1144 if (count != signature->count - 1)
1145 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1146
1147 CYPool pool;
1148 void *values[count];
1149
1150 for (unsigned index(0); index != count; ++index) {
1151 sig::Element *element(&signature->elements[index + 1]);
1152 // XXX: alignment?
1153 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
1154 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
1155 }
1156
1157 uint8_t value[cif->rtype->size];
1158 ffi_call(cif, function, value, values);
1159
1160 return CYFromFFI(context, signature->elements[0].type, value);
1161 } CYCatch
1162 }
1163
1164 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1165 ffoData *data(reinterpret_cast<ffoData *>(arg));
1166
1167 JSContextRef context(data->context_);
1168
1169 size_t count(data->cif_.nargs);
1170 JSValueRef values[count];
1171
1172 for (size_t index(0); index != count; ++index)
1173 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, arguments[index]);
1174
1175 JSValueRef exception(NULL);
1176 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1177 CYThrow(context, exception);
1178
1179 CYPoolFFI(NULL, context, data->signature_.elements[0].type, result, value);
1180 }
1181
1182 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1183 // XXX: in case of exceptions this will leak
1184 ffoData *data(new ffoData(type));
1185
1186 ffi_closure *closure;
1187 _syscall(closure = (ffi_closure *) mmap(
1188 NULL, sizeof(ffi_closure),
1189 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1190 -1, 0
1191 ));
1192
1193 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1194 _assert(status == FFI_OK);
1195
1196 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1197
1198 data->value_ = closure;
1199
1200 data->context_ = CYGetJSContext();
1201 data->function_ = function;
1202
1203 return JSObjectMake(context, Functor_, data);
1204 }
1205
1206 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1207 CYTry {
1208 CYPool pool;
1209 NSString *name(CYCastNSString(pool, property));
1210 if (Class _class = NSClassFromString(name))
1211 return CYMakeInstance(context, _class, true);
1212 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
1213 switch ([[entry objectAtIndex:0] intValue]) {
1214 case 0:
1215 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1216 case 1:
1217 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1218 case 2:
1219 sig::Signature signature;
1220 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1221 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
1222 }
1223 return NULL;
1224 } CYCatch
1225 }
1226
1227 bool stret(ffi_type *ffi_type) {
1228 return ffi_type->type == FFI_TYPE_STRUCT && (
1229 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1230 struct_forward_array[ffi_type->size] != 0
1231 );
1232 }
1233
1234 extern "C" {
1235 int *_NSGetArgc(void);
1236 char ***_NSGetArgv(void);
1237 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1238 }
1239
1240 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1241 CYTry {
1242 NSLog(@"%s", CYCastCString(context, arguments[0]));
1243 return CYJSUndefined(context);
1244 } CYCatch
1245 }
1246
1247 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1248 CYTry {
1249 CYPool pool;
1250 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1251 int argc(*_NSGetArgc());
1252 char **argv(*_NSGetArgv());
1253 for (int i(0); i != argc; ++i)
1254 NSLog(@"argv[%i]=%s", i, argv[i]);
1255 _pooled
1256 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1257 } CYCatch
1258 }
1259
1260 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1261 const char *type;
1262
1263 CYPool pool;
1264
1265 CYTry {
1266 if (count < 2)
1267 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1268
1269 id self(CYCastNSObject(pool, context, arguments[0]));
1270 if (self == nil)
1271 return CYJSNull(context);
1272
1273 SEL _cmd(CYCastSEL(context, arguments[1]));
1274
1275 Class _class(object_getClass(self));
1276 if (Method method = class_getInstanceMethod(_class, _cmd))
1277 type = method_getTypeEncoding(method);
1278 else {
1279 CYPoolTry {
1280 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1281 if (method == nil)
1282 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1283 type = CYPoolCString(pool, [method _typeString]);
1284 } CYPoolCatch(NULL)
1285 }
1286 } CYCatch
1287
1288 sig::Signature signature;
1289 sig::Parse(pool, &signature, type);
1290
1291 ffi_cif cif;
1292 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1293
1294 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1295 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1296 }
1297
1298 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1299 JSValueRef setup[count + 2];
1300 setup[0] = _this;
1301 setup[1] = object;
1302 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1303 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1304 }
1305
1306 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1307 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
1308 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1309 }
1310
1311 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1312 CYTry {
1313 if (count != 1)
1314 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1315 const char *name(CYCastCString(context, arguments[0]));
1316 return CYMakeSelector(context, sel_registerName(name));
1317 } CYCatch
1318 }
1319
1320 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1321 CYTry {
1322 if (count != 2)
1323 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1324 const char *type(CYCastCString(context, arguments[1]));
1325 JSValueRef exception(NULL);
1326 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1327 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1328 return CYMakeFunctor(context, function, type);
1329 } else if (exception != NULL) {
1330 return NULL;
1331 } else {
1332 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1333 return CYMakeFunctor(context, function, type);
1334 }
1335 } CYCatch
1336 }
1337
1338 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1339 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
1340 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1341 }
1342
1343 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1344 return Function_;
1345 }
1346
1347 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1348 CYTry {
1349 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(_this)));
1350 NSString *description; CYPoolTry {
1351 description = [data->GetValue() description];
1352 } CYPoolCatch(NULL)
1353 return CYCastJSValue(context, CYJSString(description));
1354 } CYCatch
1355 }
1356
1357 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1358 CYTry {
1359 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate(_this)));
1360 return CYCastJSValue(context, sel_getName(data->GetValue()));
1361 } CYCatch
1362 }
1363
1364 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1365 CYTry {
1366 if (count != 2)
1367 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1368 CYPool pool;
1369 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate(_this)));
1370 Class _class(CYCastNSObject(pool, context, arguments[0]));
1371 bool instance(CYCastBool(context, arguments[1]));
1372 SEL sel(data->GetValue());
1373 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1374 return CYCastJSValue(context, method_getTypeEncoding(method));
1375 else if (NSString *type = [Bridge_ objectForKey:CYPoolRelease(pool, [[NSString alloc] initWithFormat:@":%s", sel_getName(sel)])])
1376 return CYCastJSValue(context, CYJSString(type));
1377 else
1378 return CYJSNull(context);
1379 } CYCatch
1380 }
1381
1382 static JSStaticValue Pointer_staticValues[2] = {
1383 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1384 {NULL, NULL, NULL, 0}
1385 };
1386
1387 /*static JSStaticValue Selector_staticValues[2] = {
1388 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1389 {NULL, NULL, NULL, 0}
1390 };*/
1391
1392 static JSStaticFunction Instance_staticFunctions[2] = {
1393 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1394 {NULL, NULL, 0}
1395 };
1396
1397 static JSStaticFunction Selector_staticFunctions[3] = {
1398 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1399 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1400 {NULL, NULL, 0}
1401 };
1402
1403 CYDriver::CYDriver(const std::string &filename) :
1404 state_(CYClear),
1405 data_(NULL),
1406 size_(0),
1407 filename_(filename),
1408 source_(NULL)
1409 {
1410 ScannerInit();
1411 }
1412
1413 CYDriver::~CYDriver() {
1414 ScannerDestroy();
1415 }
1416
1417 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1418 CYDriver::Error error;
1419 error.location_ = location;
1420 error.message_ = message;
1421 driver.errors_.push_back(error);
1422 }
1423
1424 void CYSetArgs(int argc, const char *argv[]) {
1425 JSContextRef context(CYGetJSContext());
1426 JSValueRef args[argc];
1427 for (int i(0); i != argc; ++i)
1428 args[i] = CYCastJSValue(context, argv[i]);
1429 JSValueRef exception(NULL);
1430 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1431 CYThrow(context, exception);
1432 CYSetProperty(context, System_, CYJSString("args"), array);
1433 }
1434
1435 MSInitialize { _pooled
1436 apr_initialize();
1437
1438 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1439
1440 pid_t pid(getpid());
1441
1442 struct sockaddr_in address;
1443 address.sin_len = sizeof(address);
1444 address.sin_family = AF_INET;
1445 address.sin_addr.s_addr = INADDR_ANY;
1446 address.sin_port = htons(10000 + pid);
1447
1448 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1449
1450 CFSocketSignature signature;
1451 signature.protocolFamily = AF_INET;
1452 signature.socketType = SOCK_STREAM;
1453 signature.protocol = IPPROTO_TCP;
1454 signature.address = data;
1455
1456 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1457 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1458
1459 JSClassDefinition definition;
1460
1461 definition = kJSClassDefinitionEmpty;
1462 definition.className = "Pointer";
1463 definition.staticValues = Pointer_staticValues;
1464 definition.finalize = &Pointer_finalize;
1465 Pointer_ = JSClassCreate(&definition);
1466
1467 definition = kJSClassDefinitionEmpty;
1468 definition.className = "Functor";
1469 definition.parentClass = Pointer_;
1470 definition.callAsFunction = &Functor_callAsFunction;
1471 Functor_ = JSClassCreate(&definition);
1472
1473 definition = kJSClassDefinitionEmpty;
1474 definition.className = "Selector";
1475 definition.parentClass = Pointer_;
1476 //definition.staticValues = Selector_staticValues;
1477 definition.staticFunctions = Selector_staticFunctions;
1478 definition.callAsFunction = &Selector_callAsFunction;
1479 Selector_ = JSClassCreate(&definition);
1480
1481 definition = kJSClassDefinitionEmpty;
1482 definition.className = "Instance";
1483 definition.parentClass = Pointer_;
1484 definition.staticFunctions = Instance_staticFunctions;
1485 definition.getProperty = &Instance_getProperty;
1486 definition.setProperty = &Instance_setProperty;
1487 definition.deleteProperty = &Instance_deleteProperty;
1488 definition.callAsConstructor = &Instance_callAsConstructor;
1489 Instance_ = JSClassCreate(&definition);
1490
1491 definition = kJSClassDefinitionEmpty;
1492 definition.getProperty = &Global_getProperty;
1493 JSClassRef Global(JSClassCreate(&definition));
1494
1495 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1496 Context_ = context;
1497
1498 JSObjectRef global(JSContextGetGlobalObject(context));
1499
1500 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1501 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1502
1503 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1504 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1505
1506 System_ = JSObjectMake(context, NULL, NULL);
1507 CYSetProperty(context, global, CYJSString("system"), System_);
1508 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1509 CYSetProperty(context, System_, CYJSString("global"), global);
1510
1511 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1512
1513 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1514
1515 name_ = JSStringCreateWithUTF8CString("name");
1516 message_ = JSStringCreateWithUTF8CString("message");
1517 length_ = JSStringCreateWithUTF8CString("length");
1518
1519 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1520 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1521 }