1 /* Cyrker - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
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
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.
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.
42 #include <substrate.h>
43 #include "cycript.hpp"
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
48 #include "Pooling.hpp"
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
56 #include <CFNetwork/CFNetwork.h>
58 #include <WebKit/WebScriptObject.h>
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
66 #include <ext/stdio_filebuf.h>
73 #include "Cycript.tab.hh"
78 #define _assert(test) do { \
80 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
83 #define _trace() do { \
84 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
89 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
91 #define CYPoolCatch(value) \
92 @catch (NSException *error) { \
93 _saved = [error retain]; \
99 [_saved autorelease]; \
103 static JSGlobalContextRef Context_;
104 static JSObjectRef System_;
106 static JSClassRef Functor_;
107 static JSClassRef Instance_;
108 static JSClassRef Pointer_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
113 static JSObjectRef Array_;
114 static JSObjectRef Function_;
116 static JSStringRef name_;
117 static JSStringRef message_;
118 static JSStringRef length_;
120 static Class NSCFBoolean_;
122 static NSArray *Bridge_;
125 CFHTTPMessageRef message_;
135 void *operator new(size_t size) {
137 apr_pool_create(&pool, NULL);
138 void *data(apr_palloc(pool, size));
139 reinterpret_cast<CYData *>(data)->pool_ = pool;
143 static void Finalize(JSObjectRef object) {
144 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
146 apr_pool_destroy(data->pool_);
150 struct Pointer_privateData :
156 Pointer_privateData() {
159 Pointer_privateData(void *value) :
165 struct Functor_privateData :
168 sig::Signature signature_;
171 Functor_privateData(const char *type, void (*value)()) :
172 Pointer_privateData(reinterpret_cast<void *>(value))
174 sig::Parse(pool_, &signature_, type);
175 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
182 JSContextRef context_;
183 JSObjectRef function_;
185 ffoData(const char *type) :
186 Functor_privateData(type, NULL)
191 struct Selector_privateData : Pointer_privateData {
192 Selector_privateData(SEL value) :
193 Pointer_privateData(value)
197 SEL GetValue() const {
198 return reinterpret_cast<SEL>(value_);
202 struct Instance_privateData :
207 Instance_privateData(id value, bool transient) :
208 Pointer_privateData(value)
212 virtual ~Instance_privateData() {
214 [GetValue() release];
217 id GetValue() const {
218 return reinterpret_cast<id>(value_);
224 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
226 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
227 lhs.name = apr_pstrdup(pool, rhs.name);
228 if (rhs.type == NULL)
231 lhs.type = new(pool) Type;
232 Copy(pool, *lhs.type, *rhs.type);
234 lhs.offset = rhs.offset;
237 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
238 size_t count(rhs.count);
240 lhs.elements = new(pool) Element[count];
241 for (size_t index(0); index != count; ++index)
242 Copy(pool, lhs.elements[index], rhs.elements[index]);
245 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
246 lhs.primitive = rhs.primitive;
247 lhs.name = apr_pstrdup(pool, rhs.name);
248 lhs.flags = rhs.flags;
250 if (sig::IsAggregate(rhs.primitive))
251 Copy(pool, lhs.data.signature, rhs.data.signature);
253 if (rhs.data.data.type != NULL) {
254 lhs.data.data.type = new(pool) Type;
255 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
258 lhs.data.data.size = rhs.data.data.size;
262 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
264 lhs.alignment = rhs.alignment;
266 if (rhs.elements == NULL)
270 while (rhs.elements[count] != NULL)
273 lhs.elements = new(pool) ffi_type *[count + 1];
274 lhs.elements[count] = NULL;
276 for (size_t index(0); index != count; ++index) {
277 // XXX: if these are libffi native then you can just take them
278 ffi_type *ffi(new(pool) ffi_type);
279 lhs.elements[index] = ffi;
280 sig::Copy(pool, *ffi, *rhs.elements[index]);
287 struct Type_privateData {
292 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
293 sig::Copy(pool, type_, *type);
294 sig::Copy(pool, ffi_, *ffi);
296 /*sig::Element element;
301 sig::Signature signature;
302 signature.elements = &element;
306 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
309 /*if (type_->type != FFI_TYPE_STRUCT)
313 while (type_->elements[count] != NULL)
320 struct Struct_privateData :
324 Type_privateData *type_;
326 Struct_privateData() {
330 struct CStringMapLess :
331 std::binary_function<const char *, const char *, bool>
333 _finline bool operator ()(const char *lhs, const char *rhs) const {
334 return strcmp(lhs, rhs) < 0;
338 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
339 static TypeMap Types_;
341 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
342 Struct_privateData *internal(new Struct_privateData());
343 apr_pool_t *pool(internal->pool_);
344 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
345 internal->type_ = typical;
348 internal->owner_ = owner;
349 internal->value_ = data;
351 internal->owner_ = NULL;
353 size_t size(typical->ffi_.size);
354 void *copy(apr_palloc(internal->pool_, size));
355 memcpy(copy, data, size);
356 internal->value_ = copy;
359 NSLog(@"%s", type->name);
360 return JSObjectMake(context, Struct_, internal);
363 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
365 object = [object retain];
366 Instance_privateData *data(new Instance_privateData(object, transient));
367 return JSObjectMake(context, Instance_, data);
370 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
372 return [value UTF8String];
374 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
375 char *string(new(pool) char[size]);
376 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
377 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
382 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
383 return JSValueMakeBoolean(context, value);
386 JSValueRef CYCastJSValue(JSContextRef context, double value) {
387 return JSValueMakeNumber(context, value);
390 #define CYCastJSValue_(Type_) \
391 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
392 return JSValueMakeNumber(context, static_cast<double>(value)); \
396 CYCastJSValue_(unsigned int)
397 CYCastJSValue_(long int)
398 CYCastJSValue_(long unsigned int)
399 CYCastJSValue_(long long int)
400 CYCastJSValue_(long long unsigned int)
402 JSValueRef CYJSUndefined(JSContextRef context) {
403 return JSValueMakeUndefined(context);
406 @interface NSMethodSignature (Cycript)
407 - (NSString *) _typeString;
410 @interface NSObject (Cycript)
411 - (bool) cy$isUndefined;
412 - (NSString *) cy$toJSON;
413 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
414 - (NSObject *) cy$getProperty:(NSString *)name;
415 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
416 - (bool) cy$deleteProperty:(NSString *)name;
419 @interface NSString (Cycript)
420 - (void *) cy$symbol;
423 @interface NSNumber (Cycript)
424 - (void *) cy$symbol;
427 @implementation NSObject (Cycript)
429 - (bool) cy$isUndefined {
433 - (NSString *) cy$toJSON {
434 return [self description];
437 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
438 return CYMakeInstance(context, self, transient);
441 - (NSObject *) cy$getProperty:(NSString *)name {
442 if (![name isEqualToString:@"prototype"])
443 NSLog(@"get:%@", name);
447 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
448 NSLog(@"set:%@", name);
452 - (bool) cy$deleteProperty:(NSString *)name {
453 NSLog(@"delete:%@", name);
459 @implementation WebUndefined (Cycript)
461 - (bool) cy$isUndefined {
465 - (NSString *) cy$toJSON {
469 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
470 return CYJSUndefined(context);
475 @implementation NSNull (Cycript)
477 - (NSString *) cy$toJSON {
483 @implementation NSArray (Cycript)
485 - (NSString *) cy$toJSON {
486 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
487 [json appendString:@"["];
490 for (id object in self) {
492 [json appendString:@","];
495 if (![object cy$isUndefined])
496 [json appendString:[object cy$toJSON]];
498 [json appendString:@","];
503 [json appendString:@"]"];
507 - (NSObject *) cy$getProperty:(NSString *)name {
508 int index([name intValue]);
509 if (index < 0 || index >= static_cast<int>([self count]))
510 return [super cy$getProperty:name];
512 return [self objectAtIndex:index];
517 @implementation NSMutableArray (Cycript)
519 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
520 int index([name intValue]);
521 if (index < 0 || index >= static_cast<int>([self count]))
522 return [super cy$setProperty:name to:value];
524 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
529 - (bool) cy$deleteProperty:(NSString *)name {
530 int index([name intValue]);
531 if (index < 0 || index >= static_cast<int>([self count]))
532 return [super cy$deleteProperty:name];
534 [self removeObjectAtIndex:index];
541 @implementation NSDictionary (Cycript)
543 - (NSString *) cy$toJSON {
544 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
545 [json appendString:@"({"];
548 for (id key in self) {
550 [json appendString:@","];
553 [json appendString:[key cy$toJSON]];
554 [json appendString:@":"];
555 NSObject *object([self objectForKey:key]);
556 [json appendString:[object cy$toJSON]];
559 [json appendString:@"})"];
563 - (NSObject *) cy$getProperty:(NSString *)name {
564 return [self objectForKey:name];
569 @implementation NSMutableDictionary (Cycript)
571 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
572 [self setObject:(value ?: [NSNull null]) forKey:name];
576 - (bool) cy$deleteProperty:(NSString *)name {
577 if ([self objectForKey:name] == nil)
580 [self removeObjectForKey:name];
587 @implementation NSNumber (Cycript)
589 - (NSString *) cy$toJSON {
590 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
593 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
594 return [self class] != NSCFBoolean_ ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
597 - (void *) cy$symbol {
598 return [self pointerValue];
603 @implementation NSString (Cycript)
605 - (NSString *) cy$toJSON {
606 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
608 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
609 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
610 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
611 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
612 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
614 CFStringInsert(json, 0, CFSTR("\""));
615 CFStringAppend(json, CFSTR("\""));
617 return [reinterpret_cast<const NSString *>(json) autorelease];
620 - (void *) cy$symbol {
622 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
627 @interface CYJSObject : NSDictionary {
629 JSContextRef context_;
632 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
634 - (NSUInteger) count;
635 - (id) objectForKey:(id)key;
636 - (NSEnumerator *) keyEnumerator;
637 - (void) setObject:(id)object forKey:(id)key;
638 - (void) removeObjectForKey:(id)key;
642 @interface CYJSArray : NSArray {
644 JSContextRef context_;
647 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
649 - (NSUInteger) count;
650 - (id) objectAtIndex:(NSUInteger)index;
654 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
655 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
657 JSGlobalContextRef CYGetJSContext() {
664 @catch (id error) { \
665 NSLog(@"e:%@", error); \
666 CYThrow(context, error, exception); \
670 void CYThrow(JSContextRef context, JSValueRef value);
672 apr_status_t CYPoolRelease_(void *data) {
673 id object(reinterpret_cast<id>(data));
678 id CYPoolRelease(apr_pool_t *pool, id object) {
680 return [object autorelease];
682 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
687 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
688 return (CFTypeRef) CYPoolRelease(pool, (id) object);
691 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
692 if (JSValueIsObjectOfClass(context, object, Instance_)) {
693 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
694 return data->GetValue();
697 JSValueRef exception(NULL);
698 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
699 CYThrow(context, exception);
700 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
701 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
704 JSStringRef CYCopyJSString(id value) {
705 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
708 JSStringRef CYCopyJSString(const char *value) {
709 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
712 JSStringRef CYCopyJSString(JSStringRef value) {
713 return value == NULL ? NULL : JSStringRetain(value);
716 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
717 if (JSValueIsNull(context, value))
719 JSValueRef exception(NULL);
720 JSStringRef string(JSValueToStringCopy(context, value, &exception));
721 CYThrow(context, exception);
730 JSStringRelease(string_);
734 CYJSString(const CYJSString &rhs) :
735 string_(CYCopyJSString(rhs.string_))
739 template <typename Arg0_>
740 CYJSString(Arg0_ arg0) :
741 string_(CYCopyJSString(arg0))
745 template <typename Arg0_, typename Arg1_>
746 CYJSString(Arg0_ arg0, Arg1_ arg1) :
747 string_(CYCopyJSString(arg0, arg1))
751 CYJSString &operator =(const CYJSString &rhs) {
753 string_ = CYCopyJSString(rhs.string_);
766 operator JSStringRef() const {
771 CFStringRef CYCopyCFString(JSStringRef value) {
772 return JSStringCopyCFString(kCFAllocatorDefault, value);
775 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
776 return CYCopyCFString(CYJSString(context, value));
779 double CYCastDouble(const char *value, size_t size) {
781 double number(strtod(value, &end));
782 if (end != value + size)
787 double CYCastDouble(const char *value) {
788 return CYCastDouble(value, strlen(value));
791 double CYCastDouble(JSContextRef context, JSValueRef value) {
792 JSValueRef exception(NULL);
793 double number(JSValueToNumber(context, value, &exception));
794 CYThrow(context, exception);
798 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
799 double number(CYCastDouble(context, value));
800 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
803 CFStringRef CYCopyCFString(const char *value) {
804 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
807 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
808 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
811 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
812 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
815 bool CYCastBool(JSContextRef context, JSValueRef value) {
816 return JSValueToBoolean(context, value);
819 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
823 switch (JSType type = JSValueGetType(context, value)) {
824 case kJSTypeUndefined:
825 object = [WebUndefined undefined];
834 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
839 object = CYCopyCFNumber(context, value);
844 object = CYCopyCFString(context, value);
849 // XXX: this might could be more efficient
850 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
855 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
862 return CYPoolRelease(pool, object);
864 return CFRetain(object);
867 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
868 return CYCFType(pool, context, value, true);
871 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
872 return CYCFType(pool, context, value, false);
875 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
877 size_t size(JSPropertyNameArrayGetCount(names));
878 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
879 for (size_t index(0); index != size; ++index)
880 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
884 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
885 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
888 void CYThrow(JSContextRef context, JSValueRef value) {
891 @throw CYCastNSObject(NULL, context, value);
894 JSValueRef CYJSNull(JSContextRef context) {
895 return JSValueMakeNull(context);
898 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
899 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
902 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
903 return CYCastJSValue(context, CYJSString(value));
906 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
907 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
910 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
911 JSValueRef exception(NULL);
912 JSObjectRef object(JSValueToObject(context, value, &exception));
913 CYThrow(context, exception);
917 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
918 JSValueRef exception(NULL);
919 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
920 CYThrow(context, exception);
924 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
925 JSValueRef exception(NULL);
926 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
927 CYThrow(context, exception);
931 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
932 JSValueRef exception(NULL);
933 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
934 CYThrow(context, exception);
937 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
938 if (exception == NULL)
940 *exception = CYCastJSValue(context, error);
943 @implementation CYJSObject
945 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
946 if ((self = [super init]) != nil) {
952 - (NSUInteger) count {
953 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
954 size_t size(JSPropertyNameArrayGetCount(names));
955 JSPropertyNameArrayRelease(names);
959 - (id) objectForKey:(id)key {
960 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
963 - (NSEnumerator *) keyEnumerator {
964 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
965 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
966 JSPropertyNameArrayRelease(names);
970 - (void) setObject:(id)object forKey:(id)key {
971 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
974 - (void) removeObjectForKey:(id)key {
975 JSValueRef exception(NULL);
976 // XXX: this returns a bool... throw exception, or ignore?
977 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
978 CYThrow(context_, exception);
983 @implementation CYJSArray
985 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
986 if ((self = [super init]) != nil) {
992 - (NSUInteger) count {
993 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
996 - (id) objectAtIndex:(NSUInteger)index {
997 JSValueRef exception(NULL);
998 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
999 CYThrow(context_, exception);
1000 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1005 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1008 id object(CYCastNSObject(NULL, context, value));
1009 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
1014 const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1015 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
1016 const char *string(CYPoolCString(pool, json));
1022 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1024 case kCFSocketDataCallBack:
1025 CFDataRef data(reinterpret_cast<CFDataRef>(value));
1026 Client *client(reinterpret_cast<Client *>(info));
1028 if (client->message_ == NULL)
1029 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
1031 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
1032 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
1033 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
1034 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
1036 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
1037 CFRelease(client->message_);
1039 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
1042 JSStringRef script(JSStringCreateWithCFString(code));
1045 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
1046 JSStringRelease(script);
1048 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
1049 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
1051 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
1052 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
1055 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
1056 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
1059 CFHTTPMessageSetBody(response, body);
1062 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
1063 CFRelease(response);
1065 CFSocketSendData(socket, NULL, serialized, 0);
1066 CFRelease(serialized);
1074 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1076 case kCFSocketAcceptCallBack:
1077 Client *client(new Client());
1079 client->message_ = NULL;
1081 CFSocketContext context;
1082 context.version = 0;
1083 context.info = client;
1084 context.retain = NULL;
1085 context.release = NULL;
1086 context.copyDescription = NULL;
1088 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
1090 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
1095 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1098 NSString *self(CYCastNSObject(pool, context, object));
1099 NSString *name(CYCastNSString(pool, property));
1100 NSObject *data([self cy$getProperty:name]);
1101 return data == nil ? NULL : CYCastJSValue(context, data);
1105 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1108 NSString *self(CYCastNSObject(pool, context, object));
1109 NSString *name(CYCastNSString(pool, property));
1110 NSString *data(CYCastNSObject(pool, context, value));
1111 return [self cy$setProperty:name to:data];
1115 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1118 NSString *self(CYCastNSObject(pool, context, object));
1119 NSString *name(CYCastNSString(pool, property));
1120 return [self cy$deleteProperty:name];
1124 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1126 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1127 return CYMakeInstance(context, [data->GetValue() alloc], true);
1131 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1132 Selector_privateData *data(new Selector_privateData(sel));
1133 return JSObjectMake(context, Selector_, data);
1136 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1137 Pointer_privateData *data(new Pointer_privateData(pointer));
1138 return JSObjectMake(context, Pointer_, data);
1141 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1142 Functor_privateData *data(new Functor_privateData(type, function));
1143 return JSObjectMake(context, Functor_, data);
1146 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1148 const char *string([CYCastNSString(NULL, value) UTF8String]);
1150 *length = strlen(string);
1153 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1154 char *string(new(pool) char[size]);
1155 JSStringGetUTF8CString(value, string, size);
1156 // XXX: this is ironic
1158 *length = strlen(string);
1163 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1164 if (!JSValueIsNull(context, value))
1165 return CYPoolCString(pool, CYJSString(context, value), length);
1173 // XXX: this macro is unhygenic
1174 #define CYCastCString(context, value) ({ \
1176 if (value == NULL) \
1178 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1179 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1180 utf8 = reinterpret_cast<char *>(alloca(size)); \
1181 JSStringGetUTF8CString(string, utf8, size); \
1182 JSStringRelease(string); \
1188 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1189 if (JSValueIsNull(context, value))
1191 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1192 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1193 return reinterpret_cast<SEL>(data->value_);
1195 return sel_registerName(CYCastCString(context, value));
1198 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1199 switch (JSValueGetType(context, value)) {
1202 /*case kJSTypeString:
1203 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1205 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1206 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1207 return data->value_;
1210 double number(CYCastDouble(context, value));
1211 if (std::isnan(number))
1212 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1213 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1217 template <typename Type_>
1218 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1219 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1222 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1223 switch (type->primitive) {
1224 case sig::boolean_P:
1225 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1228 #define CYPoolFFI_(primitive, native) \
1229 case sig::primitive ## _P: \
1230 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1233 CYPoolFFI_(uchar, unsigned char)
1234 CYPoolFFI_(char, char)
1235 CYPoolFFI_(ushort, unsigned short)
1236 CYPoolFFI_(short, short)
1237 CYPoolFFI_(ulong, unsigned long)
1238 CYPoolFFI_(long, long)
1239 CYPoolFFI_(uint, unsigned int)
1240 CYPoolFFI_(int, int)
1241 CYPoolFFI_(ulonglong, unsigned long long)
1242 CYPoolFFI_(longlong, long long)
1243 CYPoolFFI_(float, float)
1244 CYPoolFFI_(double, double)
1247 case sig::typename_P:
1248 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1251 case sig::selector_P:
1252 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1255 case sig::pointer_P:
1256 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1260 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1263 case sig::struct_P: {
1264 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1265 bool aggregate(JSValueIsObject(context, value));
1266 for (size_t index(0); index != type->data.signature.count; ++index) {
1267 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1268 CYPoolFFI(pool, context, type->data.signature.elements[index].type, ffi->elements[index], base, rhs);
1276 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1281 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1284 switch (type->primitive) {
1285 case sig::boolean_P:
1286 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1289 #define CYFromFFI_(primitive, native) \
1290 case sig::primitive ## _P: \
1291 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
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)
1308 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1311 case sig::typename_P:
1312 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1315 case sig::selector_P:
1316 if (SEL sel = *reinterpret_cast<SEL *>(data))
1317 value = CYMakeSelector(context, sel);
1321 case sig::pointer_P:
1322 if (void *pointer = *reinterpret_cast<void **>(data))
1323 value = CYMakePointer(context, pointer);
1328 if (char *utf8 = *reinterpret_cast<char **>(data))
1329 value = CYCastJSValue(context, utf8);
1334 value = CYMakeStruct(context, data, type, ffi, owner);
1338 value = CYJSUndefined(context);
1342 value = CYJSNull(context);
1346 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1353 void Index_(Struct_privateData *internal, double number, ssize_t &index, uint8_t *&base) {
1354 Type_privateData *typical(internal->type_);
1356 index = static_cast<ssize_t>(number);
1357 if (index != number)
1358 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index non-integral" userInfo:nil];
1360 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index negative" userInfo:nil];
1362 base = reinterpret_cast<uint8_t *>(internal->value_);
1363 for (ssize_t local(0); local != index; ++local)
1364 if (ffi_type *element = typical->ffi_.elements[local])
1365 base += element->size;
1367 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index out-of-range" userInfo:nil];
1370 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1373 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1374 Type_privateData *typical(internal->type_);
1377 const char *name(CYPoolCString(pool, property, &length));
1378 double number(CYCastDouble(name, length));
1380 if (std::isnan(number)) {
1388 Index_(internal, number, index, base);
1390 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1394 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1397 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1398 Type_privateData *typical(internal->type_);
1401 const char *name(CYPoolCString(pool, property, &length));
1402 double number(CYCastDouble(name, length));
1404 if (std::isnan(number)) {
1412 Index_(internal, number, index, base);
1414 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1419 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1421 if (count != signature->count - 1)
1422 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1425 void *values[count];
1427 for (unsigned index(0); index != count; ++index) {
1428 sig::Element *element(&signature->elements[index + 1]);
1429 ffi_type *ffi(cif->arg_types[index]);
1431 values[index] = new(pool) uint8_t[ffi->size];
1432 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1435 uint8_t value[cif->rtype->size];
1436 ffi_call(cif, function, value, values);
1438 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1442 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1443 ffoData *data(reinterpret_cast<ffoData *>(arg));
1445 JSContextRef context(data->context_);
1447 size_t count(data->cif_.nargs);
1448 JSValueRef values[count];
1450 for (size_t index(0); index != count; ++index)
1451 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1453 JSValueRef exception(NULL);
1454 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1455 CYThrow(context, exception);
1457 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1460 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1461 // XXX: in case of exceptions this will leak
1462 ffoData *data(new ffoData(type));
1464 ffi_closure *closure;
1465 _syscall(closure = (ffi_closure *) mmap(
1466 NULL, sizeof(ffi_closure),
1467 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1471 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1472 _assert(status == FFI_OK);
1474 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1476 data->value_ = closure;
1478 data->context_ = CYGetJSContext();
1479 data->function_ = function;
1481 return JSObjectMake(context, Functor_, data);
1484 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1487 NSString *name(CYCastNSString(pool, property));
1488 if (Class _class = NSClassFromString(name))
1489 return CYMakeInstance(context, _class, true);
1490 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1491 switch ([[entry objectAtIndex:0] intValue]) {
1493 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1495 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1497 // XXX: this is horrendously inefficient
1498 sig::Signature signature;
1499 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1501 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1502 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1508 bool stret(ffi_type *ffi_type) {
1509 return ffi_type->type == FFI_TYPE_STRUCT && (
1510 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1511 struct_forward_array[ffi_type->size] != 0
1516 int *_NSGetArgc(void);
1517 char ***_NSGetArgv(void);
1518 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1521 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1523 NSLog(@"%s", CYCastCString(context, arguments[0]));
1524 return CYJSUndefined(context);
1528 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1531 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1532 int argc(*_NSGetArgc());
1533 char **argv(*_NSGetArgv());
1534 for (int i(0); i != argc; ++i)
1535 NSLog(@"argv[%i]=%s", i, argv[i]);
1537 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1541 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1548 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1550 id self(CYCastNSObject(pool, context, arguments[0]));
1552 return CYJSNull(context);
1554 SEL _cmd(CYCastSEL(context, arguments[1]));
1556 Class _class(object_getClass(self));
1557 if (Method method = class_getInstanceMethod(_class, _cmd))
1558 type = method_getTypeEncoding(method);
1561 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1563 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1564 type = CYPoolCString(pool, [method _typeString]);
1569 sig::Signature signature;
1570 sig::Parse(pool, &signature, type);
1573 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1575 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1576 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1579 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1580 JSValueRef setup[count + 2];
1583 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1584 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1587 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1588 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1589 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1592 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1595 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1596 const char *name(CYCastCString(context, arguments[0]));
1597 return CYMakeSelector(context, sel_registerName(name));
1601 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1604 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1605 const char *type(CYCastCString(context, arguments[1]));
1606 JSValueRef exception(NULL);
1607 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1608 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1609 return CYMakeFunctor(context, function, type);
1610 } else if (exception != NULL) {
1613 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1614 return CYMakeFunctor(context, function, type);
1619 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1620 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1621 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1624 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1628 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1630 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1631 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1635 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1637 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1638 NSString *description; CYPoolTry {
1639 description = [data->GetValue() description];
1641 return CYCastJSValue(context, CYJSString(description));
1645 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1647 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1648 return CYCastJSValue(context, sel_getName(data->GetValue()));
1652 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1655 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1657 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1658 Class _class(CYCastNSObject(pool, context, arguments[0]));
1659 bool instance(CYCastBool(context, arguments[1]));
1660 SEL sel(data->GetValue());
1661 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1662 return CYCastJSValue(context, method_getTypeEncoding(method));
1663 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1664 return CYCastJSValue(context, CYJSString(type));
1666 return CYJSNull(context);
1670 static JSStaticValue Pointer_staticValues[2] = {
1671 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1672 {NULL, NULL, NULL, 0}
1675 static JSStaticFunction Pointer_staticFunctions[2] = {
1676 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1680 /*static JSStaticValue Selector_staticValues[2] = {
1681 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1682 {NULL, NULL, NULL, 0}
1685 static JSStaticFunction Instance_staticFunctions[2] = {
1686 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1690 static JSStaticFunction Selector_staticFunctions[3] = {
1691 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1692 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1696 CYDriver::CYDriver(const std::string &filename) :
1700 filename_(filename),
1706 CYDriver::~CYDriver() {
1710 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1711 CYDriver::Error error;
1712 error.location_ = location;
1713 error.message_ = message;
1714 driver.errors_.push_back(error);
1717 void CYSetArgs(int argc, const char *argv[]) {
1718 JSContextRef context(CYGetJSContext());
1719 JSValueRef args[argc];
1720 for (int i(0); i != argc; ++i)
1721 args[i] = CYCastJSValue(context, argv[i]);
1722 JSValueRef exception(NULL);
1723 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1724 CYThrow(context, exception);
1725 CYSetProperty(context, System_, CYJSString("args"), array);
1728 MSInitialize { _pooled
1731 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1733 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1735 pid_t pid(getpid());
1737 struct sockaddr_in address;
1738 address.sin_len = sizeof(address);
1739 address.sin_family = AF_INET;
1740 address.sin_addr.s_addr = INADDR_ANY;
1741 address.sin_port = htons(10000 + pid);
1743 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1745 CFSocketSignature signature;
1746 signature.protocolFamily = AF_INET;
1747 signature.socketType = SOCK_STREAM;
1748 signature.protocol = IPPROTO_TCP;
1749 signature.address = data;
1751 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1752 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1754 JSClassDefinition definition;
1756 definition = kJSClassDefinitionEmpty;
1757 definition.className = "Pointer";
1758 definition.staticValues = Pointer_staticValues;
1759 definition.staticFunctions = Pointer_staticFunctions;
1760 definition.finalize = &CYData::Finalize;
1761 Pointer_ = JSClassCreate(&definition);
1763 definition = kJSClassDefinitionEmpty;
1764 definition.className = "Functor";
1765 definition.staticValues = Pointer_staticValues;
1766 definition.staticFunctions = Pointer_staticFunctions;
1767 definition.callAsFunction = &Functor_callAsFunction;
1768 definition.finalize = &CYData::Finalize;
1769 Functor_ = JSClassCreate(&definition);
1771 definition = kJSClassDefinitionEmpty;
1772 definition.className = "Struct";
1773 definition.getProperty = &Struct_getProperty;
1774 definition.setProperty = &Struct_setProperty;
1775 definition.finalize = &CYData::Finalize;
1776 Struct_ = JSClassCreate(&definition);
1778 definition = kJSClassDefinitionEmpty;
1779 definition.className = "Selector";
1780 definition.staticValues = Pointer_staticValues;
1781 //definition.staticValues = Selector_staticValues;
1782 definition.staticFunctions = Selector_staticFunctions;
1783 definition.callAsFunction = &Selector_callAsFunction;
1784 definition.finalize = &CYData::Finalize;
1785 Selector_ = JSClassCreate(&definition);
1787 definition = kJSClassDefinitionEmpty;
1788 definition.className = "Instance";
1789 definition.staticValues = Pointer_staticValues;
1790 definition.staticFunctions = Instance_staticFunctions;
1791 definition.getProperty = &Instance_getProperty;
1792 definition.setProperty = &Instance_setProperty;
1793 definition.deleteProperty = &Instance_deleteProperty;
1794 definition.callAsConstructor = &Instance_callAsConstructor;
1795 definition.finalize = &CYData::Finalize;
1796 Instance_ = JSClassCreate(&definition);
1798 definition = kJSClassDefinitionEmpty;
1799 definition.className = "Runtime";
1800 definition.getProperty = &Runtime_getProperty;
1801 Runtime_ = JSClassCreate(&definition);
1803 definition = kJSClassDefinitionEmpty;
1804 //definition.getProperty = &Global_getProperty;
1805 JSClassRef Global(JSClassCreate(&definition));
1807 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1810 JSObjectRef global(JSContextGetGlobalObject(context));
1812 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1813 CYSetProperty(context, global, CYJSString("obc"), JSObjectMake(context, Runtime_, NULL));
1815 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1816 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1818 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1819 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1821 System_ = JSObjectMake(context, NULL, NULL);
1822 CYSetProperty(context, global, CYJSString("system"), System_);
1823 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1824 CYSetProperty(context, System_, CYJSString("global"), global);
1826 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1828 name_ = JSStringCreateWithUTF8CString("name");
1829 message_ = JSStringCreateWithUTF8CString("message");
1830 length_ = JSStringCreateWithUTF8CString("length");
1832 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1833 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));