-/* Cyrker - Remove Execution Server and Disassembler
+/* Cycript - Remove Execution Server and Disassembler
* Copyright (C) 2009 Jay Freeman (saurik)
*/
#define _GNU_SOURCE
#include <substrate.h>
-#include "Struct.hpp"
+#include "cycript.hpp"
#include "sig/parse.hpp"
#include "sig/ffi_type.hpp"
-#include <apr-1/apr_pools.h>
-#include <apr-1/apr_strings.h>
+#include "Pooling.hpp"
+#include "Struct.hpp"
#include <unistd.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFLogUtilities.h>
-#include <CFNetwork/CFNetwork.h>
-#include <Foundation/Foundation.h>
-
-#include <JavaScriptCore/JSBase.h>
-#include <JavaScriptCore/JSValueRef.h>
-#include <JavaScriptCore/JSObjectRef.h>
-#include <JavaScriptCore/JSContextRef.h>
-#include <JavaScriptCore/JSStringRef.h>
-#include <JavaScriptCore/JSStringRefCF.h>
-
#include <WebKit/WebScriptObject.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
+#include <sys/un.h>
+
+#include <sys/mman.h>
#include <iostream>
#include <ext/stdio_filebuf.h>
#include <set>
#include <map>
+#include <sstream>
+#include <cmath>
+
#include "Parser.hpp"
#include "Cycript.tab.hh"
+#include <fcntl.h>
+
+#include <apr-1/apr_thread_proc.h>
+
#undef _assert
#undef _trace
CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
} while (false)
-/* APR Pool Helpers {{{ */
-void *operator new(size_t size, apr_pool_t *pool) {
- return apr_palloc(pool, size);
+#define CYPoolTry { \
+ id _saved(nil); \
+ NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
+ @try
+#define CYPoolCatch(value) \
+ @catch (NSException *error) { \
+ _saved = [error retain]; \
+ @throw; \
+ return value; \
+ } @finally { \
+ [_pool release]; \
+ if (_saved != nil) \
+ [_saved autorelease]; \
+ } \
+}
+
+static JSGlobalContextRef Context_;
+static JSObjectRef System_;
+
+static JSClassRef Functor_;
+static JSClassRef Instance_;
+static JSClassRef Pointer_;
+static JSClassRef Runtime_;
+static JSClassRef Selector_;
+static JSClassRef Struct_;
+static JSClassRef Type_;
+
+static JSObjectRef Array_;
+static JSObjectRef Function_;
+
+static JSStringRef Result_;
+
+static JSStringRef length_;
+static JSStringRef message_;
+static JSStringRef name_;
+static JSStringRef toCYON_;
+static JSStringRef toJSON_;
+
+static Class NSCFBoolean_;
+
+static NSArray *Bridge_;
+
+struct CYData {
+ apr_pool_t *pool_;
+
+ virtual ~CYData() {
+ }
+
+ static void *operator new(size_t size, apr_pool_t *pool) {
+ void *data(apr_palloc(pool, size));
+ reinterpret_cast<CYData *>(data)->pool_ = pool;
+ return data;
+ }
+
+ static void *operator new(size_t size) {
+ apr_pool_t *pool;
+ apr_pool_create(&pool, NULL);
+ return operator new(size, pool);
+ }
+
+ static void operator delete(void *data) {
+ apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
+ }
+
+ static void Finalize(JSObjectRef object) {
+ delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
+ }
+};
+
+struct CYValue :
+ CYData
+{
+ void *value_;
+
+ CYValue() {
+ }
+
+ CYValue(void *value) :
+ value_(value)
+ {
+ }
+};
+
+struct Selector_privateData :
+ CYValue
+{
+ Selector_privateData(SEL value) :
+ CYValue(value)
+ {
+ }
+
+ SEL GetValue() const {
+ return reinterpret_cast<SEL>(value_);
+ }
+};
+
+struct Instance :
+ CYValue
+{
+ enum Flags {
+ None = 0,
+ Transient = (1 << 0),
+ Uninitialized = (1 << 1),
+ };
+
+ Flags flags_;
+
+ Instance(id value, Flags flags) :
+ CYValue(value),
+ flags_(flags)
+ {
+ }
+
+ virtual ~Instance() {
+ if ((flags_ & Transient) == 0)
+ // XXX: does this handle background threads correctly?
+ [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
+ }
+
+ static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
+ return JSObjectMake(context, Instance_, new Instance(object, flags));
+ }
+
+ id GetValue() const {
+ return reinterpret_cast<id>(value_);
+ }
+
+ bool IsUninitialized() const {
+ return (flags_ & Uninitialized) != 0;
+ }
+};
+
+namespace sig {
+
+void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
+
+void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
+ lhs.name = apr_pstrdup(pool, rhs.name);
+ if (rhs.type == NULL)
+ lhs.type = NULL;
+ else {
+ lhs.type = new(pool) Type;
+ Copy(pool, *lhs.type, *rhs.type);
+ }
+ lhs.offset = rhs.offset;
}
-void *operator new [](size_t size, apr_pool_t *pool) {
- return apr_palloc(pool, size);
+void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
+ size_t count(rhs.count);
+ lhs.count = count;
+ lhs.elements = new(pool) Element[count];
+ for (size_t index(0); index != count; ++index)
+ Copy(pool, lhs.elements[index], rhs.elements[index]);
}
-class CYPool {
- private:
- apr_pool_t *pool_;
+void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
+ lhs.primitive = rhs.primitive;
+ lhs.name = apr_pstrdup(pool, rhs.name);
+ lhs.flags = rhs.flags;
- public:
- CYPool() {
- apr_pool_create(&pool_, NULL);
+ if (sig::IsAggregate(rhs.primitive))
+ Copy(pool, lhs.data.signature, rhs.data.signature);
+ else {
+ if (rhs.data.data.type != NULL) {
+ lhs.data.data.type = new(pool) Type;
+ Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
+ }
+
+ lhs.data.data.size = rhs.data.data.size;
+ }
+}
+
+void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
+ lhs.size = rhs.size;
+ lhs.alignment = rhs.alignment;
+ lhs.type = rhs.type;
+ if (rhs.elements == NULL)
+ lhs.elements = NULL;
+ else {
+ size_t count(0);
+ while (rhs.elements[count] != NULL)
+ ++count;
+
+ lhs.elements = new(pool) ffi_type *[count + 1];
+ lhs.elements[count] = NULL;
+
+ for (size_t index(0); index != count; ++index) {
+ // XXX: if these are libffi native then you can just take them
+ ffi_type *ffi(new(pool) ffi_type);
+ lhs.elements[index] = ffi;
+ sig::Copy(pool, *ffi, *rhs.elements[index]);
+ }
+ }
+}
+
+}
+
+struct CStringMapLess :
+ std::binary_function<const char *, const char *, bool>
+{
+ _finline bool operator ()(const char *lhs, const char *rhs) const {
+ return strcmp(lhs, rhs) < 0;
+ }
+};
+
+void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
+ if (name == NULL)
+ return;
+
+ CYPoolTry {
+ if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
+ switch ([[entry objectAtIndex:0] intValue]) {
+ case 0: {
+ sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+ } break;
+
+ case 1: {
+ sig::Signature signature;
+ sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
+ type = signature.elements[0].type;
+ } break;
+ }
+ } CYPoolCatch()
+}
+
+struct Type_privateData :
+ CYData
+{
+ ffi_type *ffi_;
+ sig::Type *type_;
+
+ void Set(sig::Type *type) {
+ type_ = new(pool_) sig::Type;
+ sig::Copy(pool_, *type_, *type);
}
- ~CYPool() {
- apr_pool_destroy(pool_);
+ Type_privateData(const char *type) :
+ ffi_(NULL)
+ {
+ sig::Signature signature;
+ sig::Parse(pool_, &signature, type, &Structor_);
+ type_ = signature.elements[0].type;
}
- operator apr_pool_t *() const {
- return pool_;
+ Type_privateData(sig::Type *type) :
+ ffi_(NULL)
+ {
+ if (type != NULL)
+ Set(type);
}
- char *operator ()(const char *data) const {
- return apr_pstrdup(pool_, data);
+ Type_privateData(sig::Type *type, ffi_type *ffi) {
+ ffi_ = new(pool_) ffi_type;
+ sig::Copy(pool_, *ffi_, *ffi);
+ Set(type);
}
- char *operator ()(const char *data, size_t size) const {
- return apr_pstrndup(pool_, data, size);
+ ffi_type *GetFFI() {
+ if (ffi_ == NULL) {
+ ffi_ = new(pool_) ffi_type;
+
+ sig::Element element;
+ element.name = NULL;
+ element.type = type_;
+ element.offset = 0;
+
+ sig::Signature signature;
+ signature.elements = &element;
+ signature.count = 1;
+
+ ffi_cif cif;
+ sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
+ *ffi_ = *cif.rtype;
+ }
+
+ return ffi_;
}
};
-/* }}} */
-#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
+struct Pointer :
+ CYValue
+{
+ JSObjectRef owner_;
+ Type_privateData *type_;
-static JSContextRef Context_;
+ Pointer(void *value, sig::Type *type, JSObjectRef owner) :
+ CYValue(value),
+ owner_(owner),
+ type_(new(pool_) Type_privateData(type))
+ {
+ }
+};
-static JSClassRef Functor_;
-static JSClassRef Instance_;
-static JSClassRef Pointer_;
-static JSClassRef Selector_;
+struct Struct_privateData :
+ CYValue
+{
+ JSObjectRef owner_;
+ Type_privateData *type_;
-static JSObjectRef Array_;
+ Struct_privateData(JSObjectRef owner) :
+ owner_(owner)
+ {
+ }
+};
-static JSStringRef name_;
-static JSStringRef message_;
-static JSStringRef length_;
+typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
+static TypeMap Types_;
+
+JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
+ Struct_privateData *internal(new Struct_privateData(owner));
+ apr_pool_t *pool(internal->pool_);
+ Type_privateData *typical(new(pool) Type_privateData(type, ffi));
+ internal->type_ = typical;
+
+ if (owner != NULL)
+ internal->value_ = data;
+ else {
+ size_t size(typical->GetFFI()->size);
+ void *copy(apr_palloc(internal->pool_, size));
+ memcpy(copy, data, size);
+ internal->value_ = copy;
+ }
-static Class NSCFBoolean_;
+ return JSObjectMake(context, Struct_, internal);
+}
+
+struct Functor_privateData :
+ CYValue
+{
+ sig::Signature signature_;
+ ffi_cif cif_;
+
+ Functor_privateData(const char *type, void (*value)()) :
+ CYValue(reinterpret_cast<void *>(value))
+ {
+ sig::Parse(pool_, &signature_, type, &Structor_);
+ sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
+ }
+};
-static NSMutableDictionary *Bridge_;
+struct ffoData :
+ Functor_privateData
+{
+ JSContextRef context_;
+ JSObjectRef function_;
-struct Client {
- CFHTTPMessageRef message_;
- CFSocketRef socket_;
+ ffoData(const char *type) :
+ Functor_privateData(type, NULL)
+ {
+ }
};
-JSObjectRef CYMakeObject(JSContextRef context, id object) {
- return JSObjectMake(context, Instance_, [object retain]);
+JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
+ Instance::Flags flags;
+
+ if (transient)
+ flags = Instance::Transient;
+ else {
+ flags = Instance::None;
+ object = [object retain];
+ }
+
+ return Instance::Make(context, object, flags);
+}
+
+const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
+ if (pool == NULL)
+ return [value UTF8String];
+ else {
+ size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
+ char *string(new(pool) char[size]);
+ if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
+ @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
+ return string;
+ }
+}
+
+JSValueRef CYCastJSValue(JSContextRef context, bool value) {
+ return JSValueMakeBoolean(context, value);
+}
+
+JSValueRef CYCastJSValue(JSContextRef context, double value) {
+ return JSValueMakeNumber(context, value);
+}
+
+#define CYCastJSValue_(Type_) \
+ JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
+ return JSValueMakeNumber(context, static_cast<double>(value)); \
+ }
+
+CYCastJSValue_(int)
+CYCastJSValue_(unsigned int)
+CYCastJSValue_(long int)
+CYCastJSValue_(long unsigned int)
+CYCastJSValue_(long long int)
+CYCastJSValue_(long long unsigned int)
+
+JSValueRef CYJSUndefined(JSContextRef context) {
+ return JSValueMakeUndefined(context);
+}
+
+bool CYGetIndex(const char *value, ssize_t &index) {
+ if (value[0] != '0') {
+ char *end;
+ index = strtol(value, &end, 10);
+ if (value + strlen(value) == end)
+ return true;
+ } else if (value[1] == '\0') {
+ index = 0;
+ return true;
+ }
+
+ return false;
+}
+
+bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
+ return CYGetIndex(CYPoolCString(pool, value), index);
}
@interface NSMethodSignature (Cycript)
@end
@interface NSObject (Cycript)
-- (NSString *) cy$toJSON;
+
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
+- (JSType) cy$JSType;
+
+- (NSObject *) cy$toJSON:(NSString *)key;
+- (NSString *) cy$toCYON;
+- (NSString *) cy$toKey;
+
+- (NSObject *) cy$getProperty:(NSString *)name;
+- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
+- (bool) cy$deleteProperty:(NSString *)name;
+
+@end
+
+@protocol Cycript
- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
@end
- (void *) cy$symbol;
@end
-@interface NSNumber (Cycript)
-- (void *) cy$symbol;
-@end
+struct PropertyAttributes {
+ CYPool pool_;
+
+ const char *name;
+
+ const char *variable;
+
+ const char *getter_;
+ const char *setter_;
+
+ bool readonly;
+ bool copy;
+ bool retain;
+ bool nonatomic;
+ bool dynamic;
+ bool weak;
+ bool garbage;
+
+ PropertyAttributes(objc_property_t property) :
+ variable(NULL),
+ getter_(NULL),
+ setter_(NULL),
+ readonly(false),
+ copy(false),
+ retain(false),
+ nonatomic(false),
+ dynamic(false),
+ weak(false),
+ garbage(false)
+ {
+ name = property_getName(property);
+ const char *attributes(property_getAttributes(property));
+
+ for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
+ switch (*token) {
+ case 'R': readonly = true; break;
+ case 'C': copy = true; break;
+ case '&': retain = true; break;
+ case 'N': nonatomic = true; break;
+ case 'G': getter_ = token + 1; break;
+ case 'S': setter_ = token + 1; break;
+ case 'V': variable = token + 1; break;
+ }
+ }
+
+ /*if (variable == NULL) {
+ variable = property_getName(property);
+ size_t size(strlen(variable));
+ char *name(new(pool_) char[size + 2]);
+ name[0] = '_';
+ memcpy(name + 1, variable, size);
+ name[size + 1] = '\0';
+ variable = name;
+ }*/
+ }
+
+ const char *Getter() {
+ if (getter_ == NULL)
+ getter_ = apr_pstrdup(pool_, name);
+ return getter_;
+ }
+
+ const char *Setter() {
+ if (setter_ == NULL && !readonly) {
+ size_t length(strlen(name));
+
+ char *temp(new(pool_) char[length + 5]);
+ temp[0] = 's';
+ temp[1] = 'e';
+ temp[2] = 't';
+
+ if (length != 0) {
+ temp[3] = toupper(name[0]);
+ memcpy(temp + 4, name + 1, length - 1);
+ }
+
+ temp[length + 3] = ':';
+ temp[length + 4] = '\0';
+ setter_ = temp;
+ }
+
+ return setter_;
+ }
+
+};
@implementation NSObject (Cycript)
-- (NSString *) cy$toJSON {
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
+ return CYMakeInstance(context, self, false);
+}
+
+- (JSType) cy$JSType {
+ return kJSTypeObject;
+}
+
+- (NSObject *) cy$toJSON:(NSString *)key {
return [self description];
}
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
- return CYMakeObject(context, self);
+- (NSString *) cy$toCYON {
+ return [[self cy$toJSON:@""] cy$toCYON];
+}
+
+- (NSString *) cy$toKey {
+ return [self cy$toCYON];
+}
+
+- (NSObject *) cy$getProperty:(NSString *)name {
+ /*if (![name isEqualToString:@"prototype"])
+ NSLog(@"get:%@", name);*/
+ return nil;
+}
+
+- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
+ //NSLog(@"set:%@", name);
+ return false;
+}
+
+- (bool) cy$deleteProperty:(NSString *)name {
+ //NSLog(@"delete:%@", name);
+ return false;
}
@end
@implementation WebUndefined (Cycript)
-- (NSString *) cy$toJSON {
+- (JSType) cy$JSType {
+ return kJSTypeUndefined;
+}
+
+- (NSObject *) cy$toJSON:(NSString *)key {
+ return self;
+}
+
+- (NSString *) cy$toCYON {
return @"undefined";
}
- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
- return JSValueMakeUndefined(context);
+ return CYJSUndefined(context);
+}
+
+@end
+
+@implementation NSNull (Cycript)
+
+- (JSType) cy$JSType {
+ return kJSTypeNull;
+}
+
+- (NSObject *) cy$toJSON:(NSString *)key {
+ return self;
+}
+
+- (NSString *) cy$toCYON {
+ return @"null";
}
@end
@implementation NSArray (Cycript)
-- (NSString *) cy$toJSON {
+- (NSString *) cy$toCYON {
NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
[json appendString:@"["];
[json appendString:@","];
else
comma = true;
- [json appendString:[object cy$toJSON]];
+ if ([object cy$JSType] != kJSTypeUndefined)
+ [json appendString:[object cy$toCYON]];
+ else {
+ [json appendString:@","];
+ comma = false;
+ }
}
[json appendString:@"]"];
return json;
}
+- (NSObject *) cy$getProperty:(NSString *)name {
+ if ([name isEqualToString:@"length"])
+ return [NSNumber numberWithUnsignedInteger:[self count]];
+
+ ssize_t index;
+ if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
+ return [super cy$getProperty:name];
+ else
+ return [self objectAtIndex:index];
+}
+
+@end
+
+@implementation NSMutableArray (Cycript)
+
+- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
+ ssize_t index;
+ if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
+ return [super cy$setProperty:name to:value];
+ else {
+ [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
+ return true;
+ }
+}
+
+- (bool) cy$deleteProperty:(NSString *)name {
+ ssize_t index;
+ if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
+ return [super cy$deleteProperty:name];
+ else {
+ [self removeObjectAtIndex:index];
+ return true;
+ }
+}
+
@end
@implementation NSDictionary (Cycript)
-- (NSString *) cy$toJSON {
+- (NSString *) cy$toCYON {
NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
- [json appendString:@"("];
[json appendString:@"{"];
bool comma(false);
[json appendString:@","];
else
comma = true;
- [json appendString:[key cy$toJSON]];
+ [json appendString:[key cy$toKey]];
[json appendString:@":"];
NSObject *object([self objectForKey:key]);
- [json appendString:[object cy$toJSON]];
+ [json appendString:[object cy$toCYON]];
}
- [json appendString:@"})"];
+ [json appendString:@"}"];
return json;
}
+- (NSObject *) cy$getProperty:(NSString *)name {
+ return [self objectForKey:name];
+}
+
+@end
+
+@implementation NSMutableDictionary (Cycript)
+
+- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
+ [self setObject:(value ?: [NSNull null]) forKey:name];
+ return true;
+}
+
+- (bool) cy$deleteProperty:(NSString *)name {
+ if ([self objectForKey:name] == nil)
+ return false;
+ else {
+ [self removeObjectForKey:name];
+ return true;
+ }
+}
+
@end
@implementation NSNumber (Cycript)
-- (NSString *) cy$toJSON {
- return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
+- (JSType) cy$JSType {
+ // XXX: this just seems stupid
+ return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
}
-- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
- return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
+- (NSObject *) cy$toJSON:(NSString *)key {
+ return self;
}
-- (void *) cy$symbol {
- return [self pointerValue];
+- (NSString *) cy$toCYON {
+ return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
+}
+
+- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
+ return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
}
@end
@implementation NSString (Cycript)
-- (NSString *) cy$toJSON {
+- (JSType) cy$JSType {
+ return kJSTypeString;
+}
+
+- (NSObject *) cy$toJSON:(NSString *)key {
+ return self;
+}
+
+- (NSString *) cy$toCYON {
+ // XXX: this should use the better code from Output.cpp
CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
return [reinterpret_cast<const NSString *>(json) autorelease];
}
+- (NSString *) cy$toKey {
+ const char *value([self UTF8String]);
+ size_t size(strlen(value));
+
+ if (size == 0)
+ goto cyon;
+
+ if (DigitRange_[value[0]]) {
+ ssize_t index;
+ if (!CYGetIndex(NULL, self, index) || index < 0)
+ goto cyon;
+ } else {
+ if (!WordStartRange_[value[0]])
+ goto cyon;
+ for (size_t i(1); i != size; ++i)
+ if (!WordEndRange_[value[i]])
+ goto cyon;
+ }
+
+ return self;
+
+ cyon:
+ return [self cy$toCYON];
+}
+
- (void *) cy$symbol {
- return dlsym(RTLD_DEFAULT, [self UTF8String]);
+ CYPool pool;
+ return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
}
@end
- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
+- (NSString *) cy$toJSON:(NSString *)key;
+
- (NSUInteger) count;
- (id) objectForKey:(id)key;
- (NSEnumerator *) keyEnumerator;
@end
-JSContextRef JSGetContext() {
- return Context_;
-}
+CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
+CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
+CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
+#define CYTry \
+ @try
#define CYCatch \
@catch (id error) { \
CYThrow(context, error, exception); \
void CYThrow(JSContextRef context, JSValueRef value);
-id CYCastNSObject(JSContextRef context, JSObjectRef object) {
- if (JSValueIsObjectOfClass(context, object, Instance_))
- return reinterpret_cast<id>(JSObjectGetPrivate(object));
- JSValueRef exception(NULL);
- bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
+apr_status_t CYPoolRelease_(void *data) {
+ id object(reinterpret_cast<id>(data));
+ [object release];
+ return APR_SUCCESS;
+}
+
+id CYPoolRelease(apr_pool_t *pool, id object) {
+ if (object == nil)
+ return nil;
+ else if (pool == NULL)
+ return [object autorelease];
+ else {
+ apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
+ return object;
+ }
+}
+
+CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
+ return (CFTypeRef) CYPoolRelease(pool, (id) object);
+}
+
+id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
+ JSValueRef exception(NULL);
+ bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
CYThrow(context, exception);
- if (array)
- return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
- return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
+ id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
+ return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
+}
+
+id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
+ if (!JSValueIsObjectOfClass(context, object, Instance_))
+ return CYCastNSObject_(pool, context, object);
+ else {
+ Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
+ return data->GetValue();
+ }
}
JSStringRef CYCopyJSString(id value) {
- return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
+ return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
}
JSStringRef CYCopyJSString(const char *value) {
- return JSStringCreateWithUTF8CString(value);
+ return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
}
JSStringRef CYCopyJSString(JSStringRef value) {
- return JSStringRetain(value);
+ return value == NULL ? NULL : JSStringRetain(value);
}
JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
+ if (JSValueIsNull(context, value))
+ return NULL;
JSValueRef exception(NULL);
JSStringRef string(JSValueToStringCopy(context, value, &exception));
CYThrow(context, exception);
return string;
}
-// XXX: this is not a safe handle
-class CYString {
+class CYJSString {
private:
JSStringRef string_;
+ void Clear_() {
+ if (string_ != NULL)
+ JSStringRelease(string_);
+ }
+
public:
+ CYJSString(const CYJSString &rhs) :
+ string_(CYCopyJSString(rhs.string_))
+ {
+ }
+
template <typename Arg0_>
- CYString(Arg0_ arg0) {
- string_ = CYCopyJSString(arg0);
+ CYJSString(Arg0_ arg0) :
+ string_(CYCopyJSString(arg0))
+ {
}
template <typename Arg0_, typename Arg1_>
- CYString(Arg0_ arg0, Arg1_ arg1) {
- string_ = CYCopyJSString(arg0, arg1);
+ CYJSString(Arg0_ arg0, Arg1_ arg1) :
+ string_(CYCopyJSString(arg0, arg1))
+ {
+ }
+
+ CYJSString &operator =(const CYJSString &rhs) {
+ Clear_();
+ string_ = CYCopyJSString(rhs.string_);
+ return *this;
+ }
+
+ ~CYJSString() {
+ Clear_();
}
- ~CYString() {
- JSStringRelease(string_);
+ void Clear() {
+ Clear_();
+ string_ = NULL;
}
operator JSStringRef() const {
}
CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
- return CYCopyCFString(CYString(context, value));
+ return CYCopyCFString(CYJSString(context, value));
+}
+
+double CYCastDouble(const char *value, size_t size) {
+ char *end;
+ double number(strtod(value, &end));
+ if (end != value + size)
+ return NAN;
+ return number;
+}
+
+double CYCastDouble(const char *value) {
+ return CYCastDouble(value, strlen(value));
}
double CYCastDouble(JSContextRef context, JSValueRef value) {
return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
}
-NSString *CYCastNSString(JSStringRef value) {
- return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
+CFStringRef CYCopyCFString(const char *value) {
+ return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
+}
+
+NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
+ return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
+}
+
+NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
+ return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
+}
+
+bool CYCastBool(JSContextRef context, JSValueRef value) {
+ return JSValueToBoolean(context, value);
}
-CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
+CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
+ CFTypeRef object;
+ bool copy;
+
switch (JSType type = JSValueGetType(context, value)) {
case kJSTypeUndefined:
- return CFRetain([WebUndefined undefined]);
+ object = [WebUndefined undefined];
+ copy = false;
+ break;
+
case kJSTypeNull:
- return nil;
+ return NULL;
+ break;
+
case kJSTypeBoolean:
- return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
+ object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
+ copy = false;
+ break;
+
case kJSTypeNumber:
- return CYCopyCFNumber(context, value);
+ object = CYCopyCFNumber(context, value);
+ copy = true;
+ break;
+
case kJSTypeString:
- return CYCopyCFString(context, value);
+ object = CYCopyCFString(context, value);
+ copy = true;
+ break;
+
case kJSTypeObject:
- return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
+ // XXX: this might could be more efficient
+ object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
+ copy = false;
+ break;
+
default:
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
+ break;
}
+
+ if (cast != copy)
+ return object;
+ else if (copy)
+ return CYPoolRelease(pool, object);
+ else
+ return CFRetain(object);
+}
+
+CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+ return CYCFType(pool, context, value, true);
+}
+
+CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+ return CYCFType(pool, context, value, false);
}
NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
+ CYPool pool;
size_t size(JSPropertyNameArrayGetCount(names));
NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
for (size_t index(0); index != size; ++index)
- [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
+ [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
return array;
}
-id CYCastNSObject(JSContextRef context, JSValueRef value) {
- const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
- return object == nil ? nil : [object autorelease];
+id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+ return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
}
void CYThrow(JSContextRef context, JSValueRef value) {
if (value == NULL)
return;
- @throw CYCastNSObject(context, value);
+ @throw CYCastNSObject(NULL, context, value);
+}
+
+JSValueRef CYJSNull(JSContextRef context) {
+ return JSValueMakeNull(context);
+}
+
+JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
+ return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
+}
+
+JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
+ return CYCastJSValue(context, CYJSString(value));
}
JSValueRef CYCastJSValue(JSContextRef context, id value) {
- return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
+ if (value == nil)
+ return CYJSNull(context);
+ else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
+ return [value cy$JSValueInContext:context];
+ else
+ return CYMakeInstance(context, value, false);
+}
+
+JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
+ JSValueRef exception(NULL);
+ JSObjectRef object(JSValueToObject(context, value, &exception));
+ CYThrow(context, exception);
+ return object;
+}
+
+JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
+ JSValueRef exception(NULL);
+ JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
+ CYThrow(context, exception);
+ return value;
+}
+
+JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
+ JSValueRef exception(NULL);
+ JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
+ CYThrow(context, exception);
+ return value;
+}
+
+void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
+ JSValueRef exception(NULL);
+ JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
+ CYThrow(context, exception);
}
void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
+ if (exception == NULL)
+ throw error;
*exception = CYCastJSValue(context, error);
}
+JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
+ JSValueRef exception(NULL);
+ JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
+ CYThrow(context, exception);
+ return value;
+}
+
+bool CYIsCallable(JSContextRef context, JSValueRef value) {
+ // XXX: this isn't actually correct
+ return value != NULL && JSValueIsObject(context, value);
+}
+
@implementation CYJSObject
- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
} return self;
}
+- (NSObject *) cy$toJSON:(NSString *)key {
+ JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
+ if (!CYIsCallable(context_, toJSON))
+ return [super cy$toJSON:key];
+ else {
+ JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
+ JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
+ // XXX: do I really want an NSNull here?!
+ return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
+ }
+}
+
+- (NSString *) cy$toCYON {
+ JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
+ if (!CYIsCallable(context_, toCYON))
+ return [super cy$toCYON];
+ else {
+ JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
+ return CYCastNSString(NULL, CYJSString(context_, value));
+ }
+}
+
- (NSUInteger) count {
JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
size_t size(JSPropertyNameArrayGetCount(names));
}
- (id) objectForKey:(id)key {
- JSValueRef exception(NULL);
- JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
- CYThrow(context_, exception);
- return CYCastNSObject(context_, value);
+ return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
}
- (NSEnumerator *) keyEnumerator {
}
- (void) setObject:(id)object forKey:(id)key {
- JSValueRef exception(NULL);
- JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
- CYThrow(context_, exception);
+ CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
}
- (void) removeObjectForKey:(id)key {
JSValueRef exception(NULL);
- // XXX: this returns a bool... throw exception, or ignore?
- JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
+ (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
CYThrow(context_, exception);
}
}
- (NSUInteger) count {
- JSValueRef exception(NULL);
- JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
- CYThrow(context_, exception);
- return CYCastDouble(context_, value);
+ return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
}
- (id) objectAtIndex:(NSUInteger)index {
JSValueRef exception(NULL);
JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
CYThrow(context_, exception);
- id object(CYCastNSObject(context_, value));
- return object == nil ? [NSNull null] : object;
+ return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
}
@end
-CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
- id object(CYCastNSObject(context, value));
- return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
+CFStringRef CYCopyCYONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
+ CYTry {
+ CYPoolTry {
+ id object(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
+ return reinterpret_cast<CFStringRef>([[object cy$toCYON] retain]);
+ } CYPoolCatch(NULL)
+ } CYCatch
}
-static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
- switch (type) {
- case kCFSocketDataCallBack:
- CFDataRef data(reinterpret_cast<CFDataRef>(value));
- Client *client(reinterpret_cast<Client *>(info));
-
- if (client->message_ == NULL)
- client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
-
- if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
- CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
- else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
- CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
- Boolean absolute;
- CFStringRef path(CFURLCopyStrictPath(url, &absolute));
- CFRelease(client->message_);
-
- CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
- CFRelease(path);
+const char *CYPoolCYONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
+ if (NSString *json = (NSString *) CYCopyCYONString(context, value, exception)) {
+ const char *string(CYPoolCString(pool, json));
+ [json release];
+ return string;
+ } else return NULL;
+}
- JSStringRef script(JSStringCreateWithCFString(code));
- CFRelease(code);
+// XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
+struct CYInternal :
+ CYData
+{
+ JSObjectRef object_;
- JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
- JSStringRelease(script);
+ CYInternal() :
+ object_(NULL)
+ {
+ }
- CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
- CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
+ ~CYInternal() {
+ // XXX: delete object_? ;(
+ }
- CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
- CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
- CFRelease(json);
+ static CYInternal *Get(id self) {
+ CYInternal *internal(NULL);
+ if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
+ // XXX: do something epic? ;P
+ }
- CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
- CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
- CFRelease(length);
+ return internal;
+ }
- CFHTTPMessageSetBody(response, body);
- CFRelease(body);
+ static CYInternal *Set(id self) {
+ CYInternal *internal(NULL);
+ if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
+ if (internal == NULL) {
+ internal = new CYInternal();
+ object_setIvar(self, ivar, reinterpret_cast<id>(internal));
+ }
+ } else {
+ // XXX: do something epic? ;P
+ }
- CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
- CFRelease(response);
+ return internal;
+ }
- CFSocketSendData(socket, NULL, serialized, 0);
- CFRelease(serialized);
+ JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
+ if (object_ == NULL)
+ return NULL;
+ return CYGetProperty(context, object_, name);
+ }
- CFRelease(url);
- }
- break;
+ void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
+ if (object_ == NULL)
+ object_ = JSObjectMake(context, NULL, NULL);
+ CYSetProperty(context, object_, name, value);
}
-}
+};
-static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
- switch (type) {
- case kCFSocketAcceptCallBack:
- Client *client(new Client());
+static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYPool pool;
- client->message_ = NULL;
+ CYTry {
+ NSString *self(CYCastNSObject(pool, context, object));
+ NSString *name(CYCastNSString(pool, property));
- CFSocketContext context;
- context.version = 0;
- context.info = client;
- context.retain = NULL;
- context.release = NULL;
- context.copyDescription = NULL;
+ if (CYInternal *internal = CYInternal::Get(self))
+ if (JSValueRef value = internal->GetProperty(context, property))
+ return value;
- client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
+ CYPoolTry {
+ if (NSObject *data = [self cy$getProperty:name])
+ return CYCastJSValue(context, data);
+ } CYPoolCatch(NULL)
- CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
- break;
- }
-}
+ if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
+ PropertyAttributes attributes(property);
+ SEL sel(sel_registerName(attributes.Getter()));
+ return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
+ }
-static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
- @try {
- NSString *name(CYCastNSString(property));
- NSLog(@"%@", name);
return NULL;
} CYCatch
}
-typedef id jocData;
-
-static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
- @try {
- id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
- return CYMakeObject(context, [[data alloc] autorelease]);
- } CYCatch
-}
-
-struct ptrData {
- apr_pool_t *pool_;
- void *value_;
- sig::Type type_;
-
- void *operator new(size_t size) {
- apr_pool_t *pool;
- apr_pool_create(&pool, NULL);
- void *data(apr_palloc(pool, size));
- reinterpret_cast<ptrData *>(data)->pool_ = pool;
- return data;;
- }
-
- ptrData(void *value) :
- value_(value)
- {
- }
-};
+static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+ CYPool pool;
-struct ffiData : ptrData {
- sig::Signature signature_;
- ffi_cif cif_;
+ CYTry {
+ NSString *self(CYCastNSObject(pool, context, object));
+ NSString *name(CYCastNSString(pool, property));
+ NSString *data(CYCastNSObject(pool, context, value));
+
+ CYPoolTry {
+ if ([self cy$setProperty:name to:data])
+ return true;
+ } CYPoolCatch(NULL)
+
+ if (objc_property_t property = class_getProperty(object_getClass(self), [name UTF8String])) {
+ PropertyAttributes attributes(property);
+ if (const char *setter = attributes.Setter()) {
+ SEL sel(sel_registerName(setter));
+ JSValueRef arguments[1] = {value};
+ CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
+ return true;
+ }
+ }
- ffiData(void (*value)(), const char *type) :
- ptrData(reinterpret_cast<void *>(value))
- {
- sig::Parse(pool_, &signature_, type);
- sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
- }
-};
+ if (CYInternal *internal = CYInternal::Set(self)) {
+ internal->SetProperty(context, property, value);
+ return true;
+ }
-struct selData : ptrData {
- selData(SEL value) :
- ptrData(value)
- {
- }
-};
+ return false;
+ } CYCatch
+}
-static void Pointer_finalize(JSObjectRef object) {
- ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
- apr_pool_destroy(data->pool_);
+static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYTry {
+ CYPoolTry {
+ NSString *self(CYCastNSObject(NULL, context, object));
+ NSString *name(CYCastNSString(NULL, property));
+ return [self cy$deleteProperty:name];
+ } CYPoolCatch(NULL)
+ } CYCatch
}
-static void Instance_finalize(JSObjectRef object) {
- id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
- [data release];
+static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
+ JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
+ return value;
+ } CYCatch
}
-JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
- ffiData *data(new ffiData(function, type));
- return JSObjectMake(context, Functor_, data);
+JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
+ Selector_privateData *data(new Selector_privateData(sel));
+ return JSObjectMake(context, Selector_, data);
}
+JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
+ Pointer *data(new Pointer(pointer, type, owner));
+ return JSObjectMake(context, Pointer_, data);
+}
-JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
- return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
+JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
+ Functor_privateData *data(new Functor_privateData(type, function));
+ return JSObjectMake(context, Functor_, data);
}
-void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
- JSValueRef exception(NULL);
- JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
- CYThrow(context, exception);
+const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
+ if (pool == NULL) {
+ const char *string([CYCastNSString(NULL, value) UTF8String]);
+ return string;
+ } else {
+ size_t size(JSStringGetMaximumUTF8CStringSize(value));
+ char *string(new(pool) char[size]);
+ JSStringGetUTF8CString(value, string, size);
+ return string;
+ }
}
-char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
- size_t size(JSStringGetMaximumUTF8CStringSize(value));
- char *string(new(pool) char[size]);
- JSStringGetUTF8CString(value, string, size);
- JSStringRelease(value);
- return string;
+const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
+ return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
}
-char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
- return CYPoolCString(pool, CYString(context, value));
+bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
+ return CYGetIndex(CYPoolCString(pool, value), index);
}
// XXX: this macro is unhygenic
#define CYCastCString(context, value) ({ \
- JSValueRef exception(NULL); \
- JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
- CYThrow(context, exception); \
- size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
- char *utf8(reinterpret_cast<char *>(alloca(size))); \
- JSStringGetUTF8CString(string, utf8, size); \
- JSStringRelease(string); \
+ char *utf8; \
+ if (value == NULL) \
+ utf8 = NULL; \
+ else if (JSStringRef string = CYCopyJSString(context, value)) { \
+ size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
+ utf8 = reinterpret_cast<char *>(alloca(size)); \
+ JSStringGetUTF8CString(string, utf8, size); \
+ JSStringRelease(string); \
+ } else \
+ utf8 = NULL; \
utf8; \
})
-SEL CYCastSEL(JSContextRef context, JSValueRef value) {
- if (JSValueIsNull(context, value))
- return NULL;
- else if (JSValueIsObjectOfClass(context, value, Selector_)) {
- selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
- return reinterpret_cast<SEL>(data->value_);
- } else
- return sel_registerName(CYCastCString(context, value));
-}
-
-void *CYCastPointer(JSContextRef context, JSValueRef value) {
+void *CYCastPointer_(JSContextRef context, JSValueRef value) {
switch (JSValueGetType(context, value)) {
case kJSTypeNull:
return NULL;
- case kJSTypeString:
+ /*case kJSTypeString:
return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
case kJSTypeObject:
if (JSValueIsObjectOfClass(context, value, Pointer_)) {
- ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
+ Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
return data->value_;
- }
+ }*/
default:
- return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
+ double number(CYCastDouble(context, value));
+ if (std::isnan(number))
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
+ return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
}
}
-void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
+template <typename Type_>
+_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
+ return reinterpret_cast<Type_>(CYCastPointer_(context, value));
+}
+
+SEL CYCastSEL(JSContextRef context, JSValueRef value) {
+ if (JSValueIsObjectOfClass(context, value, Selector_)) {
+ Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
+ return reinterpret_cast<SEL>(data->value_);
+ } else
+ return CYCastPointer<SEL>(context, value);
+}
+
+void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
switch (type->primitive) {
case sig::boolean_P:
*reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
case sig::object_P:
case sig::typename_P:
- *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
+ *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
break;
case sig::selector_P:
break;
case sig::pointer_P:
- *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
+ *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
break;
case sig::string_P:
- *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
+ *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
break;
- case sig::struct_P:
- goto fail;
+ case sig::struct_P: {
+ uint8_t *base(reinterpret_cast<uint8_t *>(data));
+ JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
+ for (size_t index(0); index != type->data.signature.count; ++index) {
+ sig::Element *element(&type->data.signature.elements[index]);
+ ffi_type *field(ffi->elements[index]);
+
+ JSValueRef rhs;
+ if (aggregate == NULL)
+ rhs = value;
+ else {
+ rhs = CYGetProperty(context, aggregate, index);
+ if (JSValueIsUndefined(context, rhs)) {
+ if (element->name != NULL)
+ rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
+ else
+ goto undefined;
+ if (JSValueIsUndefined(context, rhs)) undefined:
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
+ }
+ }
+
+ CYPoolFFI(pool, context, element->type, field, base, rhs);
+ // XXX: alignment?
+ base += field->size;
+ }
+ } break;
case sig::void_P:
break;
- default: fail:
+ default:
NSLog(@"CYPoolFFI(%c)\n", type->primitive);
_assert(false);
}
}
-JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
+JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner = NULL) {
JSValueRef value;
switch (type->primitive) {
case sig::boolean_P:
- value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
+ value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
break;
#define CYFromFFI_(primitive, native) \
case sig::primitive ## _P: \
- value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
+ value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
break;
CYFromFFI_(uchar, unsigned char)
CYFromFFI_(float, float)
CYFromFFI_(double, double)
- case sig::object_P:
- case sig::typename_P: {
- value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
- } break;
-
- case sig::selector_P: {
- if (SEL sel = *reinterpret_cast<SEL *>(data)) {
- selData *data(new selData(sel));
- value = JSObjectMake(context, Selector_, data);
+ case sig::object_P: {
+ if (id object = *reinterpret_cast<id *>(data)) {
+ value = CYCastJSValue(context, object);
+ if (initialize)
+ [object release];
} else goto null;
} break;
- case sig::pointer_P: {
- if (void *pointer = *reinterpret_cast<void **>(data)) {
- ptrData *data(new ptrData(pointer));
- value = JSObjectMake(context, Pointer_, data);
- } else goto null;
- } break;
+ case sig::typename_P:
+ value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
+ break;
+
+ case sig::selector_P:
+ if (SEL sel = *reinterpret_cast<SEL *>(data))
+ value = CYMakeSelector(context, sel);
+ else goto null;
+ break;
+
+ case sig::pointer_P:
+ if (void *pointer = *reinterpret_cast<void **>(data))
+ value = CYMakePointer(context, pointer, type->data.data.type, owner);
+ else goto null;
+ break;
- case sig::string_P: {
+ case sig::string_P:
if (char *utf8 = *reinterpret_cast<char **>(data))
- value = JSValueMakeString(context, CYString(utf8));
+ value = CYCastJSValue(context, utf8);
else goto null;
- } break;
+ break;
case sig::struct_P:
- goto fail;
+ value = CYMakeStruct(context, data, type, ffi, owner);
+ break;
case sig::void_P:
- value = JSValueMakeUndefined(context);
+ value = CYJSUndefined(context);
break;
null:
- value = JSValueMakeNull(context);
+ value = CYJSNull(context);
break;
- default: fail:
+ default:
NSLog(@"CYFromFFI(%c)\n", type->primitive);
_assert(false);
}
return value;
}
-static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
- @try {
- if (count != signature->count - 1)
+bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
+ Type_privateData *typical(internal->type_);
+ sig::Type *type(typical->type_);
+ if (type == NULL)
+ return false;
+
+ const char *name(CYPoolCString(pool, property));
+ size_t length(strlen(name));
+ double number(CYCastDouble(name, length));
+
+ size_t count(type->data.signature.count);
+
+ if (std::isnan(number)) {
+ if (property == NULL)
+ return false;
+
+ sig::Element *elements(type->data.signature.elements);
+
+ for (size_t local(0); local != count; ++local) {
+ sig::Element *element(&elements[local]);
+ if (element->name != NULL && strcmp(name, element->name) == 0) {
+ index = local;
+ goto base;
+ }
+ }
+
+ return false;
+ } else {
+ index = static_cast<ssize_t>(number);
+ if (index != number || index < 0 || static_cast<size_t>(index) >= count)
+ return false;
+ }
+
+ base:
+ ffi_type **elements(typical->GetFFI()->elements);
+
+ base = reinterpret_cast<uint8_t *>(internal->value_);
+ for (ssize_t local(0); local != index; ++local)
+ base += elements[local]->size;
+
+ return true;
+}
+
+static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYPool pool;
+ Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+ Type_privateData *typical(internal->type_);
+
+ if (typical->type_ == NULL)
+ return NULL;
+
+ ssize_t index;
+ if (!CYGetIndex(pool, property, index))
+ return NULL;
+
+ ffi_type *ffi(typical->GetFFI());
+
+ uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
+ base += ffi->size * index;
+
+ JSObjectRef owner(internal->owner_ ?: object);
+
+ CYTry {
+ return CYFromFFI(context, typical->type_, ffi, base, false, owner);
+ } CYCatch
+}
+
+static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+ CYPool pool;
+ Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
+ Type_privateData *typical(internal->type_);
+
+ if (typical->type_ == NULL)
+ return NULL;
+
+ ssize_t index;
+ if (!CYGetIndex(pool, property, index))
+ return NULL;
+
+ ffi_type *ffi(typical->GetFFI());
+
+ uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
+ base += ffi->size * index;
+
+ CYTry {
+ CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
+ return true;
+ } CYCatch
+}
+
+static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYPool pool;
+ Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
+ Type_privateData *typical(internal->type_);
+
+ ssize_t index;
+ uint8_t *base;
+
+ if (!Index_(pool, internal, property, index, base))
+ return NULL;
+
+ JSObjectRef owner(internal->owner_ ?: object);
+
+ CYTry {
+ return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
+ } CYCatch
+}
+
+static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
+ CYPool pool;
+ Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
+ Type_privateData *typical(internal->type_);
+
+ ssize_t index;
+ uint8_t *base;
+
+ if (!Index_(pool, internal, property, index, base))
+ return false;
+
+ CYTry {
+ CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
+ return true;
+ } CYCatch
+}
+
+static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
+ Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
+ Type_privateData *typical(internal->type_);
+ sig::Type *type(typical->type_);
+
+ if (type == NULL)
+ return;
+
+ size_t count(type->data.signature.count);
+ sig::Element *elements(type->data.signature.elements);
+
+ char number[32];
+
+ for (size_t index(0); index != count; ++index) {
+ const char *name;
+ name = elements[index].name;
+
+ if (name == NULL) {
+ sprintf(number, "%lu", index);
+ name = number;
+ }
+
+ JSPropertyNameAccumulatorAddName(names, CYJSString(name));
+ }
+}
+
+JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
+ CYTry {
+ if (setups + count != signature->count - 1)
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
- CYPool pool;
- void *values[count];
+ size_t size(setups + count);
+ void *values[size];
+ memcpy(values, setup, sizeof(void *) * setups);
- for (unsigned index(0); index != count; ++index) {
+ for (size_t index(setups); index != size; ++index) {
sig::Element *element(&signature->elements[index + 1]);
+ ffi_type *ffi(cif->arg_types[index]);
// XXX: alignment?
- values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
- CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
+ values[index] = new(pool) uint8_t[ffi->size];
+ CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
}
uint8_t value[cif->rtype->size];
ffi_call(cif, function, value, values);
- return CYFromFFI(context, signature->elements[0].type, value);
+ return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
} CYCatch
}
-static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
- @try {
- NSString *name(CYCastNSString(property));
+void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
+ ffoData *data(reinterpret_cast<ffoData *>(arg));
+
+ JSContextRef context(data->context_);
+
+ size_t count(data->cif_.nargs);
+ JSValueRef values[count];
+
+ for (size_t index(0); index != count; ++index)
+ values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index], false);
+
+ JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
+ CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
+}
+
+JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
+ // XXX: in case of exceptions this will leak
+ ffoData *data(new ffoData(type));
+
+ ffi_closure *closure((ffi_closure *) _syscall(mmap(
+ NULL, sizeof(ffi_closure),
+ PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
+ -1, 0
+ )));
+
+ ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
+ _assert(status == FFI_OK);
+
+ _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
+
+ data->value_ = closure;
+
+ data->context_ = CYGetJSContext();
+ data->function_ = function;
+
+ return JSObjectMake(context, Functor_, data);
+}
+
+static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYTry {
+ CYPool pool;
+ NSString *name(CYCastNSString(pool, property));
if (Class _class = NSClassFromString(name))
- return CYMakeObject(context, _class);
- if (NSMutableArray *entry = [Bridge_ objectForKey:name])
+ return CYMakeInstance(context, _class, true);
+ if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
switch ([[entry objectAtIndex:0] intValue]) {
case 0:
- return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
+ return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
case 1:
- return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
+ return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
case 2:
- CYPool pool;
+ // XXX: this is horrendously inefficient
sig::Signature signature;
- sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
- return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
+ sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
+ ffi_cif cif;
+ sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
+ return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol], false);
}
return NULL;
} CYCatch
);
}
-static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
+extern "C" {
+ int *_NSGetArgc(void);
+ char ***_NSGetArgv(void);
+ int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
+}
+
+static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ NSLog(@"%s", CYCastCString(context, arguments[0]));
+ return CYJSUndefined(context);
+ } CYCatch
+}
+
+JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
const char *type;
- @try {
+ Class _class(object_getClass(self));
+ if (Method method = class_getInstanceMethod(_class, _cmd))
+ type = method_getTypeEncoding(method);
+ else {
+ CYTry {
+ CYPoolTry {
+ NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
+ if (method == nil)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
+ type = CYPoolCString(pool, [method _typeString]);
+ } CYPoolCatch(NULL)
+ } CYCatch
+ }
+
+ void *setup[2];
+ setup[0] = &self;
+ setup[1] = &_cmd;
+
+ sig::Signature signature;
+ sig::Parse(pool, &signature, type, &Structor_);
+
+ ffi_cif cif;
+ sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
+
+ void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
+ return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
+}
+
+static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYPool pool;
+
+ bool uninitialized;
+
+ id self;
+ SEL _cmd;
+
+ CYTry {
if (count < 2)
@throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
- id self(CYCastNSObject(context, arguments[0]));
+ if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
+ Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
+ self = data->GetValue();
+ uninitialized = data->IsUninitialized();
+ if (uninitialized)
+ data->value_ = nil;
+ } else {
+ self = CYCastNSObject(pool, context, arguments[0]);
+ uninitialized = false;
+ }
+
if (self == nil)
- return JSValueMakeNull(context);
+ return CYJSNull(context);
+
+ _cmd = CYCastSEL(context, arguments[1]);
+ } CYCatch
+
+ return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
+}
- SEL _cmd(CYCastSEL(context, arguments[1]));
- NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
- if (method == nil)
- @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
+MSHook(void, CYDealloc, id self, SEL sel) {
+ CYInternal *internal;
+ object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
+ if (internal != NULL)
+ delete internal;
+ _CYDealloc(self, sel);
+}
+
+MSHook(void, objc_registerClassPair, Class _class) {
+ Class super(class_getSuperclass(_class));
+ if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
+ class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
+ MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
+ }
- type = [[method _typeString] UTF8String];
+ _objc_registerClassPair(_class);
+}
+
+static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 1)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
+ CYPool pool;
+ Class _class(CYCastNSObject(pool, context, arguments[0]));
+ $objc_registerClassPair(_class);
+ return CYJSUndefined(context);
} CYCatch
+}
+static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ JSValueRef setup[count + 2];
+ setup[0] = _this;
+ setup[1] = object;
+ memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
+ return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
+}
+
+static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
CYPool pool;
+ Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
+ return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
+}
- sig::Signature signature;
- sig::Parse(pool, &signature, type);
+JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 1)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
+ const char *name(CYCastCString(context, arguments[0]));
+ return CYMakeSelector(context, sel_registerName(name));
+ } CYCatch
+}
- ffi_cif cif;
- sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
+JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 2)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
- void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
- return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
+ void *value(CYCastPointer<void *>(context, arguments[0]));
+ const char *type(CYCastCString(context, arguments[1]));
+
+ CYPool pool;
+
+ sig::Signature signature;
+ sig::Parse(pool, &signature, type, &Structor_);
+
+ return CYMakePointer(context, value, signature.elements[0].type, NULL);
+ } CYCatch
+}
+
+JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
+ Type_privateData *internal(new Type_privateData(type));
+ return JSObjectMake(context, Type_, internal);
+}
+
+JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 1)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
+ const char *type(CYCastCString(context, arguments[0]));
+ return CYMakeType(context, object, type);
+ } CYCatch
}
-static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
- ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
- return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
+static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 1)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+ Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+ sig::Type *type(internal->type_);
+ ffi_type *ffi(internal->GetFFI());
+ // XXX: alignment?
+ uint8_t value[ffi->size];
+ CYPool pool;
+ CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
+ return CYFromFFI(context, type, ffi, value, false);
+ } CYCatch
+}
+
+static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count > 1)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
+ Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
+ // XXX: alignment?
+ void *value(malloc(internal->GetFFI()->size));
+ return CYMakePointer(context, value, internal->type_, NULL);
+ } CYCatch
}
-JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
- @try {
+JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
if (count != 2)
- @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
- void *function(CYCastPointer(context, arguments[0]));
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
const char *type(CYCastCString(context, arguments[1]));
- return CYMakeFunction(context, function, type);
+ JSValueRef exception(NULL);
+ if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
+ JSObjectRef function(CYCastJSObject(context, arguments[0]));
+ return CYMakeFunctor(context, function, type);
+ } else if (exception != NULL) {
+ return NULL;
+ } else {
+ void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
+ return CYMakeFunctor(context, function, type);
+ }
} CYCatch
}
-JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
- ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
- return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
+JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
+ return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
+}
+
+JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
+ return Function_;
+}
+
+static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
+ return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
+ } CYCatch
+}
+
+static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
+}
+
+static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
+ char string[32];
+ sprintf(string, "%p", internal->value_);
+ return CYCastJSValue(context, string);
+ } CYCatch
+}
+
+static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
+ CYPoolTry {
+ return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
+ } CYPoolCatch(NULL)
+ } CYCatch
+}
+
+static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
+ CYPoolTry {
+ NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
+ return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
+ } CYPoolCatch(NULL)
+ } CYCatch
+}
+
+static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
+ CYPoolTry {
+ return CYCastJSValue(context, CYJSString([data->GetValue() description]));
+ } CYPoolCatch(NULL)
+ } CYCatch
+}
+
+static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
+ return CYCastJSValue(context, sel_getName(data->GetValue()));
+ } CYCatch
}
-static JSStaticValue Pointer_staticValues[2] = {
- {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
+}
+
+static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
+ const char *name(sel_getName(data->GetValue()));
+ CYPoolTry {
+ return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
+ } CYPoolCatch(NULL)
+ } CYCatch
+}
+
+static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
+ CYTry {
+ if (count != 2)
+ @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
+ CYPool pool;
+ Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
+ Class _class(CYCastNSObject(pool, context, arguments[0]));
+ bool instance(CYCastBool(context, arguments[1]));
+ SEL sel(data->GetValue());
+ if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
+ return CYCastJSValue(context, method_getTypeEncoding(method));
+ else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
+ return CYCastJSValue(context, CYJSString(type));
+ else
+ return CYJSNull(context);
+ } CYCatch
+}
+
+static JSStaticValue CYValue_staticValues[2] = {
+ {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
+ {NULL, NULL, NULL, 0}
+};
+
+static JSStaticFunction Pointer_staticFunctions[4] = {
+ {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {NULL, NULL, 0}
+};
+
+static JSStaticFunction Functor_staticFunctions[4] = {
+ {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {NULL, NULL, 0}
+};
+
+/*static JSStaticValue Selector_staticValues[2] = {
+ {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
{NULL, NULL, NULL, 0}
+};*/
+
+static JSStaticFunction Instance_staticFunctions[4] = {
+ {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {NULL, NULL, 0}
};
-extern int cydebug;
+static JSStaticFunction Selector_staticFunctions[5] = {
+ {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
+ {NULL, NULL, 0}
+};
-void cy::parser::error(const cy::parser::location_type &loc, const std::string &msg) {
- std::cerr << loc << ": " << msg << std::endl;
+CYDriver::CYDriver(const std::string &filename) :
+ state_(CYClear),
+ data_(NULL),
+ size_(0),
+ filename_(filename),
+ source_(NULL)
+{
+ ScannerInit();
}
-void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
- cydebug = 1;
- CYParser context;
- cy::parser parser(&context);
- parser.parse();
+CYDriver::~CYDriver() {
+ ScannerDestroy();
}
-MSInitialize { _pooled
- apr_initialize();
+void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
+ CYDriver::Error error;
+ error.location_ = location;
+ error.message_ = message;
+ driver.errors_.push_back(error);
+}
- NSCFBoolean_ = objc_getClass("NSCFBoolean");
+void CYSetArgs(int argc, const char *argv[]) {
+ JSContextRef context(CYGetJSContext());
+ JSValueRef args[argc];
+ for (int i(0); i != argc; ++i)
+ args[i] = CYCastJSValue(context, argv[i]);
+ JSValueRef exception(NULL);
+ JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
+ CYThrow(context, exception);
+ CYSetProperty(context, System_, CYJSString("args"), array);
+}
- pid_t pid(getpid());
+JSObjectRef CYGetGlobalObject(JSContextRef context) {
+ return JSContextGetGlobalObject(context);
+}
- struct sockaddr_in address;
- address.sin_len = sizeof(address);
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(10000 + pid);
+const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
+ JSStringRef script(JSStringCreateWithUTF8CString(code));
- CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
+ JSContextRef context(CYGetJSContext());
- CFSocketSignature signature;
- signature.protocolFamily = AF_INET;
- signature.socketType = SOCK_STREAM;
- signature.protocol = IPPROTO_TCP;
- signature.address = data;
+ JSValueRef exception(NULL);
+ JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
+ JSStringRelease(script);
+
+ if (exception != NULL) { error:
+ result = exception;
+ exception = NULL;
+ }
+
+ if (JSValueIsUndefined(context, result))
+ return NULL;
+
+ const char *json(CYPoolCYONString(pool, context, result, &exception));
+ if (exception != NULL)
+ goto error;
+
+ CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
+ return json;
+}
- CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
- CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
+bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
+ while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
+ data += writ;
+ size -= writ;
+ } else
+ return false;
+ return true;
+}
+
+bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
+ while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
+ data += writ;
+ size -= writ;
+ } else
+ return false;
+ return true;
+}
- JSClassDefinition definition;
+static int Socket_;
+apr_pool_t *Pool_;
- definition = kJSClassDefinitionEmpty;
- definition.className = "Pointer";
- definition.staticValues = Pointer_staticValues;
- definition.finalize = &Pointer_finalize;
- Pointer_ = JSClassCreate(&definition);
+struct CYExecute_ {
+ apr_pool_t *pool_;
+ const char * volatile data_;
+};
- definition = kJSClassDefinitionEmpty;
- definition.className = "Functor";
- definition.parentClass = Pointer_;
- definition.callAsFunction = &ffi_callAsFunction;
- Functor_ = JSClassCreate(&definition);
+// XXX: this is "tre lame"
+@interface CYClient_ : NSObject {
+}
- definition = kJSClassDefinitionEmpty;
- definition.className = "Selector";
- definition.parentClass = Pointer_;
- Selector_ = JSClassCreate(&definition);
+- (void) execute:(NSValue *)value;
- definition = kJSClassDefinitionEmpty;
- definition.className = "Instance_";
- definition.getProperty = &Instance_getProperty;
- definition.callAsConstructor = &Instance_callAsConstructor;
- definition.finalize = &Instance_finalize;
- Instance_ = JSClassCreate(&definition);
+@end
- definition = kJSClassDefinitionEmpty;
- definition.getProperty = &Global_getProperty;
- JSClassRef Global(JSClassCreate(&definition));
+@implementation CYClient_
- JSContextRef context(JSGlobalContextCreate(Global));
- Context_ = context;
+- (void) execute:(NSValue *)value {
+ CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
+ NSLog(@"b:%p", execute->data_);
+ NSLog(@"s:%s", execute->data_);
+ execute->data_ = CYExecute(execute->pool_, execute->data_);
+ NSLog(@"a:%p", execute->data_);
+}
- JSObjectRef global(JSContextGetGlobalObject(context));
+@end
- CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
+struct CYClient :
+ CYData
+{
+ int socket_;
+ apr_thread_t *thread_;
- CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
+ CYClient(int socket) :
+ socket_(socket)
+ {
+ }
- Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
+ ~CYClient() {
+ _syscall(close(socket_));
+ }
- name_ = JSStringCreateWithUTF8CString("name");
- message_ = JSStringCreateWithUTF8CString("message");
- length_ = JSStringCreateWithUTF8CString("length");
+ void Handle() { _pooled
+ CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
+
+ for (;;) {
+ size_t size;
+ if (!CYRecvAll(socket_, &size, sizeof(size)))
+ return;
+
+ CYPool pool;
+ char *data(new(pool) char[size + 1]);
+ if (!CYRecvAll(socket_, data, size))
+ return;
+ data[size] = '\0';
+
+ CYDriver driver("");
+ cy::parser parser(driver);
+
+ driver.data_ = data;
+ driver.size_ = size;
+
+ const char *json;
+ if (parser.parse() != 0 || !driver.errors_.empty()) {
+ json = NULL;
+ size = _not(size_t);
+ } else {
+ std::ostringstream str;
+ driver.source_->Show(str);
+ std::string code(str.str());
+ CYExecute_ execute = {pool, code.c_str()};
+ [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
+ json = execute.data_;
+ size = json == NULL ? _not(size_t) : strlen(json);
+ }
- JSValueRef exception(NULL);
- JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
- CYThrow(context, exception);
- Array_ = JSValueToObject(JSGetContext(), value, &exception);
- CYThrow(context, exception);
+ if (!CYSendAll(socket_, &size, sizeof(size)))
+ return;
+ if (json != NULL)
+ if (!CYSendAll(socket_, json, size))
+ return;
+ }
+ }
+};
+
+static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
+ CYClient *client(reinterpret_cast<CYClient *>(data));
+ client->Handle();
+ delete client;
+ return NULL;
+}
+
+static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
+ for (;;) {
+ int socket(_syscall(accept(Socket_, NULL, NULL)));
+ CYClient *client(new CYClient(socket));
+ apr_threadattr_t *attr;
+ _aprcall(apr_threadattr_create(&attr, Pool_));
+ _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
+ }
+
+ return NULL;
+}
+
+void Unlink() {
+ pid_t pid(getpid());
+ char path[104];
+ sprintf(path, "/tmp/.s.cy.%u", pid);
+ unlink(path);
+}
+
+MSInitialize { _pooled
+ _aprcall(apr_initialize());
+ _aprcall(apr_pool_create(&Pool_, NULL));
+
+ Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
+ NSCFBoolean_ = objc_getClass("NSCFBoolean");
+
+ Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
+
+ struct sockaddr_un address;
+ memset(&address, 0, sizeof(address));
+ address.sun_family = AF_UNIX;
+
+ pid_t pid(getpid());
+ sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
+
+ try {
+ _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
+ atexit(&Unlink);
+ _syscall(listen(Socket_, 0));
+
+ apr_threadattr_t *attr;
+ _aprcall(apr_threadattr_create(&attr, Pool_));
+
+ apr_thread_t *thread;
+ _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
+ } catch (...) {
+ NSLog(@"failed to setup Cyrver");
+ }
+}
+
+JSGlobalContextRef CYGetJSContext() {
+ if (Context_ == NULL) {
+ JSClassDefinition definition;
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Functor";
+ definition.staticFunctions = Functor_staticFunctions;
+ definition.callAsFunction = &Functor_callAsFunction;
+ definition.finalize = &CYData::Finalize;
+ Functor_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Instance";
+ definition.staticValues = CYValue_staticValues;
+ definition.staticFunctions = Instance_staticFunctions;
+ definition.getProperty = &Instance_getProperty;
+ definition.setProperty = &Instance_setProperty;
+ definition.deleteProperty = &Instance_deleteProperty;
+ definition.callAsConstructor = &Instance_callAsConstructor;
+ definition.finalize = &CYData::Finalize;
+ Instance_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Pointer";
+ definition.staticFunctions = Pointer_staticFunctions;
+ definition.getProperty = &Pointer_getProperty;
+ definition.setProperty = &Pointer_setProperty;
+ definition.finalize = &CYData::Finalize;
+ Pointer_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Selector";
+ definition.staticValues = CYValue_staticValues;
+ //definition.staticValues = Selector_staticValues;
+ definition.staticFunctions = Selector_staticFunctions;
+ definition.callAsFunction = &Selector_callAsFunction;
+ definition.finalize = &CYData::Finalize;
+ Selector_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Struct";
+ definition.getProperty = &Struct_getProperty;
+ definition.setProperty = &Struct_setProperty;
+ definition.getPropertyNames = &Struct_getPropertyNames;
+ definition.finalize = &CYData::Finalize;
+ Struct_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Type";
+ definition.callAsFunction = &Type_callAsFunction;
+ definition.callAsConstructor = &Type_callAsConstructor;
+ definition.finalize = &CYData::Finalize;
+ Type_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ definition.className = "Runtime";
+ definition.getProperty = &Runtime_getProperty;
+ Runtime_ = JSClassCreate(&definition);
+
+ definition = kJSClassDefinitionEmpty;
+ //definition.getProperty = &Global_getProperty;
+ JSClassRef Global(JSClassCreate(&definition));
+
+ JSGlobalContextRef context(JSGlobalContextCreate(Global));
+ Context_ = context;
+
+ JSObjectRef global(CYGetGlobalObject(context));
+
+ JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
+ CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
+
+ CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
+ CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
+ CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
+ CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
+ CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
+
+ MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
+
+ CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
+ CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
+
+ System_ = JSObjectMake(context, NULL, NULL);
+ CYSetProperty(context, global, CYJSString("system"), System_);
+ CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
+ //CYSetProperty(context, System_, CYJSString("global"), global);
+
+ CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
+
+ Result_ = JSStringCreateWithUTF8CString("_");
+
+ length_ = JSStringCreateWithUTF8CString("length");
+ message_ = JSStringCreateWithUTF8CString("message");
+ name_ = JSStringCreateWithUTF8CString("name");
+ toCYON_ = JSStringCreateWithUTF8CString("toCYON");
+ toJSON_ = JSStringCreateWithUTF8CString("toJSON");
+
+ Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
+ Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
+ }
+
+ return Context_;
}