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.
40 #include <substrate.h>
42 #include "sig/parse.hpp"
43 #include "sig/ffi_type.hpp"
45 #include <apr-1/apr_pools.h>
46 #include <apr-1/apr_strings.h>
50 #include <CoreFoundation/CoreFoundation.h>
51 #include <CoreFoundation/CFLogUtilities.h>
53 #include <CFNetwork/CFNetwork.h>
54 #include <Foundation/Foundation.h>
56 #include <JavaScriptCore/JSBase.h>
57 #include <JavaScriptCore/JSValueRef.h>
58 #include <JavaScriptCore/JSObjectRef.h>
59 #include <JavaScriptCore/JSContextRef.h>
60 #include <JavaScriptCore/JSStringRef.h>
61 #include <JavaScriptCore/JSStringRefCF.h>
63 #include <WebKit/WebScriptObject.h>
65 #include <sys/types.h>
66 #include <sys/socket.h>
67 #include <netinet/in.h>
72 /* XXX: bad _assert */
73 #define _assert(test) do { \
75 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
83 static JSContextRef Context_;
85 static JSClassRef ffi_;
86 static JSClassRef joc_;
88 static JSObjectRef Array_;
90 static JSStringRef name_;
91 static JSStringRef message_;
92 static JSStringRef length_;
94 static Class NSCFBoolean_;
97 CFHTTPMessageRef message_;
101 @interface NSObject (Cyrver)
102 - (NSString *) cy$toJSON;
103 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
106 @implementation NSObject (Cyrver)
108 - (NSString *) cy$toJSON {
109 return [self description];
112 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
113 return JSObjectMake(context, joc_, [self retain]);
118 @implementation WebUndefined (Cyrver)
120 - (NSString *) cy$toJSON {
124 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
125 return JSValueMakeUndefined(context);
130 @implementation NSArray (Cyrver)
132 - (NSString *) cy$toJSON {
133 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
134 [json appendString:@"["];
137 for (id object in self) {
139 [json appendString:@","];
142 [json appendString:[object cy$toJSON]];
145 [json appendString:@"]"];
151 @implementation NSDictionary (Cyrver)
153 - (NSString *) cy$toJSON {
154 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
155 [json appendString:@"({"];
158 for (id key in self) {
160 [json appendString:@","];
163 [json appendString:[key cy$toJSON]];
164 [json appendString:@":"];
165 NSObject *object([self objectForKey:key]);
166 [json appendString:[object cy$toJSON]];
169 [json appendString:@"})"];
175 @implementation NSNumber (Cyrver)
177 - (NSString *) cy$toJSON {
178 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
181 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
182 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
187 @implementation NSString (Cyrver)
189 - (NSString *) cy$toJSON {
190 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
192 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
193 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
194 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
195 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
196 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
198 CFStringInsert(json, 0, CFSTR("\""));
199 CFStringAppend(json, CFSTR("\""));
201 return [reinterpret_cast<const NSString *>(json) autorelease];
206 @interface CY$JSObject : NSDictionary {
208 JSContextRef context_;
211 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
213 - (NSUInteger) count;
214 - (id) objectForKey:(id)key;
215 - (NSEnumerator *) keyEnumerator;
216 - (void) setObject:(id)object forKey:(id)key;
217 - (void) removeObjectForKey:(id)key;
221 @interface CY$JSArray : NSArray {
223 JSContextRef context_;
226 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
228 - (NSUInteger) count;
229 - (id) objectAtIndex:(NSUInteger)index;
233 JSContextRef JSGetContext() {
237 void CYThrow(JSContextRef context, JSValueRef value);
239 id JSObjectToNSObject(JSContextRef context, JSObjectRef object) {
240 if (JSValueIsObjectOfClass(context, object, joc_))
241 return reinterpret_cast<id>(JSObjectGetPrivate(object));
242 JSValueRef exception(NULL);
243 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
244 CYThrow(context, exception);
246 return [[[CY$JSArray alloc] initWithJSObject:object inContext:context] autorelease];
247 return [[[CY$JSObject alloc] initWithJSObject:object inContext:context] autorelease];
250 CFStringRef CYCopyCFString(JSStringRef value) {
251 return JSStringCopyCFString(kCFAllocatorDefault, value);
254 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
255 JSValueRef exception(NULL);
256 JSStringRef string(JSValueToStringCopy(context, value, &exception));
257 CYThrow(context, exception);
258 CFStringRef object(CYCopyCFString(string));
259 JSStringRelease(string);
263 NSString *CYCastNSString(JSStringRef value) {
264 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
267 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
268 JSType type(JSValueGetType(context, value));
271 case kJSTypeUndefined:
272 return CFRetain([WebUndefined undefined]);
280 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
283 case kJSTypeNumber: {
284 JSValueRef exception(NULL);
285 double number(JSValueToNumber(context, value, &exception));
286 CYThrow(context, exception);
287 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
291 return CYCopyCFString(context, value);
295 return CFRetain((CFTypeRef) JSObjectToNSObject(context, (JSObjectRef) value));
304 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
305 size_t size(JSPropertyNameArrayGetCount(names));
306 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
307 for (size_t index(0); index != size; ++index)
308 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
312 id CYCastNSObject(JSContextRef context, JSValueRef value) {
313 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
314 return object == nil ? nil : [object autorelease];
317 void CYThrow(JSContextRef context, JSValueRef value) {
320 @throw CYCastNSObject(context, value);
323 JSValueRef CYCastJSValue(JSContextRef context, id value) {
324 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
327 JSStringRef CYCopyJSString(id value) {
328 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
331 JSStringRef CYCopyJSString(const char *value) {
332 return JSStringCreateWithUTF8CString(value);
335 @implementation CY$JSObject
337 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
338 if ((self = [super init]) != nil) {
344 - (NSUInteger) count {
345 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
346 size_t size(JSPropertyNameArrayGetCount(names));
347 JSPropertyNameArrayRelease(names);
351 - (id) objectForKey:(id)key {
352 JSValueRef exception(NULL);
353 JSStringRef string(CYCopyJSString(key));
354 JSValueRef value(JSObjectGetProperty(context_, object_, string, &exception));
355 JSStringRelease(string);
356 CYThrow(context_, exception);
357 return CYCastNSObject(context_, value);
360 - (NSEnumerator *) keyEnumerator {
361 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
362 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
363 JSPropertyNameArrayRelease(names);
367 - (void) setObject:(id)object forKey:(id)key {
368 JSValueRef exception(NULL);
369 JSStringRef string(CYCopyJSString(key));
370 JSObjectSetProperty(context_, object_, string, CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
371 JSStringRelease(string);
372 CYThrow(context_, exception);
375 - (void) removeObjectForKey:(id)key {
376 JSValueRef exception(NULL);
377 JSStringRef string(CYCopyJSString(key));
378 // XXX: this returns a bool
379 JSObjectDeleteProperty(context_, object_, string, &exception);
380 JSStringRelease(string);
381 CYThrow(context_, exception);
386 @implementation CY$JSArray
388 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
389 if ((self = [super init]) != nil) {
395 - (NSUInteger) count {
396 JSValueRef exception(NULL);
397 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
398 CYThrow(context_, exception);
399 double number(JSValueToNumber(context_, value, &exception));
400 CYThrow(context_, exception);
404 - (id) objectAtIndex:(NSUInteger)index {
405 JSValueRef exception(NULL);
406 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
407 CYThrow(context_, exception);
408 id object(CYCastNSObject(context_, value));
409 return object == nil ? [NSNull null] : object;
414 CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
415 id object(CYCastNSObject(context, value));
416 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
419 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
421 case kCFSocketDataCallBack:
422 CFDataRef data(reinterpret_cast<CFDataRef>(value));
423 Client *client(reinterpret_cast<Client *>(info));
425 if (client->message_ == NULL)
426 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
428 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
429 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
430 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
431 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
433 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
434 CFRelease(client->message_);
436 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
439 JSStringRef script(JSStringCreateWithCFString(code));
442 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
443 JSStringRelease(script);
445 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
446 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
448 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
449 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
452 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
453 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
456 CFHTTPMessageSetBody(response, body);
459 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
462 CFSocketSendData(socket, NULL, serialized, 0);
463 CFRelease(serialized);
471 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
473 case kCFSocketAcceptCallBack:
474 Client *client(new Client());
476 client->message_ = NULL;
478 CFSocketContext context;
480 context.info = client;
481 context.retain = NULL;
482 context.release = NULL;
483 context.copyDescription = NULL;
485 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
487 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
492 static JSValueRef joc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
498 static void joc_finalize(JSObjectRef object) {
499 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
503 static JSValueRef obc_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
504 NSString *name([(NSString *) JSStringCopyCFString(kCFAllocatorDefault, propertyName) autorelease]);
505 if (Class _class = NSClassFromString(name))
506 return JSObjectMake(context, joc_, [_class retain]);
510 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
511 JSValueRef exception(NULL);
512 JSStringRef string(CYCopyJSString(name));
513 JSObjectSetProperty(context, object, string, value, kJSPropertyAttributeNone, &exception);
514 JSStringRelease(string);
515 CYThrow(context, exception);
522 sig::Signature signature_;
526 void CYToFFI(apr_pool_t *pool, JSContextRef context, JSValueRef *exception, sig::Type *type, void *data, JSValueRef value) {
527 switch (type->primitive) {
529 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
532 #define CYToFFI_(primitive, native) \
533 case sig::primitive ## _P: { \
534 double number(JSValueToNumber(context, value, exception)); \
535 if (exception == NULL) \
536 *reinterpret_cast<native *>(data) = number; \
539 CYToFFI_(uchar, unsigned char)
541 CYToFFI_(ushort, unsigned short)
542 CYToFFI_(short, short)
543 CYToFFI_(ulong, unsigned long)
545 CYToFFI_(uint, unsigned int)
547 CYToFFI_(ulonglong, unsigned long long)
548 CYToFFI_(longlong, long long)
549 CYToFFI_(float, float)
550 CYToFFI_(double, double)
553 case sig::typename_P:
554 case sig::selector_P:
558 case sig::string_P: {
559 JSStringRef string(JSValueToStringCopy(context, value, exception));
560 if (exception != NULL) {
561 size_t size(JSStringGetMaximumUTF8CStringSize(string));
562 char *utf8(reinterpret_cast<char *>(apr_palloc(pool, size)));
563 JSStringGetUTF8CString(string, utf8, size);
564 JSStringRelease(string);
565 *reinterpret_cast<char **>(data) = utf8;
576 NSLog(@"CYToFFI(%c)\n", type->primitive);
581 JSValueRef CYFromFFI(apr_pool_t *pool, JSContextRef context, JSValueRef *exception, sig::Type *type, void *data) {
584 switch (type->primitive) {
586 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
589 #define CYFromFFI_(primitive, native) \
590 case sig::primitive ## _P: \
591 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
594 CYFromFFI_(uchar, unsigned char)
595 CYFromFFI_(char, char)
596 CYFromFFI_(ushort, unsigned short)
597 CYFromFFI_(short, short)
598 CYFromFFI_(ulong, unsigned long)
599 CYFromFFI_(long, long)
600 CYFromFFI_(uint, unsigned int)
602 CYFromFFI_(ulonglong, unsigned long long)
603 CYFromFFI_(longlong, long long)
604 CYFromFFI_(float, float)
605 CYFromFFI_(double, double)
608 case sig::typename_P: {
609 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
612 case sig::selector_P:
616 case sig::string_P: {
617 char *utf8(*reinterpret_cast<char **>(data));
618 JSStringRef string(JSStringCreateWithUTF8CString(utf8));
619 value = JSValueMakeString(context, string);
620 JSStringRelease(string);
631 NSLog(@"CYFromFFI(%c)\n", type->primitive);
638 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
639 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
641 if (count != data->signature_.count - 1)
644 JSValueRef result(NULL);
647 apr_pool_create(&pool, NULL);
651 for (unsigned index(0); index != count; ++index) {
652 sig::Element *element(&data->signature_.elements[index + 1]);
653 values[index] = apr_palloc(pool, data->cif_.arg_types[index]->size);
654 CYToFFI(pool, context, exception, element->type, values[index], arguments[index]);
655 if (*exception != NULL)
659 uint8_t value[data->cif_.rtype->size];
662 ffi_call(&data->cif_, data->function_, value, values);
663 } @catch (id error) {
667 result = CYFromFFI(pool, context, exception, data->signature_.elements[0].type, value);
670 apr_pool_destroy(pool);
674 static void ffi_finalize(JSObjectRef object) {
675 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
676 apr_pool_destroy(data->pool_);
679 void CYSetFunction(JSContextRef context, JSObjectRef object, const char *name, void (*function)(), const char *type) {
681 apr_pool_create(&pool, NULL);
683 ffiData *data(reinterpret_cast<ffiData *>(apr_palloc(pool, sizeof(ffiData))));
686 data->function_ = function;
687 data->type_ = apr_pstrdup(pool, type);
689 sig::Parse(pool, &data->signature_, type);
690 sig::sig_ffi_cif(pool, &sig::sig_objc_ffi_type, &data->signature_, &data->cif_);
692 JSObjectRef value(JSObjectMake(context, ffi_, data));
693 CYSetProperty(context, object, name, value);
699 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
701 NSCFBoolean_ = objc_getClass("NSCFBoolean");
705 struct sockaddr_in address;
706 address.sin_len = sizeof(address);
707 address.sin_family = AF_INET;
708 address.sin_addr.s_addr = INADDR_ANY;
709 address.sin_port = htons(10000 + pid);
711 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
713 CFSocketSignature signature;
714 signature.protocolFamily = AF_INET;
715 signature.socketType = SOCK_STREAM;
716 signature.protocol = IPPROTO_TCP;
717 signature.address = data;
719 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
720 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
722 JSClassDefinition definition;
724 definition = kJSClassDefinitionEmpty;
725 definition.getProperty = &obc_getProperty;
726 JSClassRef obc(JSClassCreate(&definition));
728 definition = kJSClassDefinitionEmpty;
729 definition.callAsFunction = &ffi_callAsFunction;
730 definition.finalize = &ffi_finalize;
731 ffi_ = JSClassCreate(&definition);
733 definition = kJSClassDefinitionEmpty;
734 definition.getProperty = &joc_getProperty;
735 definition.finalize = &joc_finalize;
736 joc_ = JSClassCreate(&definition);
738 JSContextRef context(JSGlobalContextCreate(obc));
741 JSObjectRef global(JSContextGetGlobalObject(context));
743 CYSetFunction(context, global, "objc_getClass", reinterpret_cast<void (*)()>(&objc_getClass), "#*");
745 name_ = JSStringCreateWithUTF8CString("name");
746 message_ = JSStringCreateWithUTF8CString("message");
747 length_ = JSStringCreateWithUTF8CString("length");
749 JSStringRef name(JSStringCreateWithUTF8CString("Array"));
750 JSValueRef exception(NULL);
751 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, name, &exception));
752 CYThrow(context, exception);
753 JSStringRelease(name);
754 Array_ = JSValueToObject(JSGetContext(), value, &exception);
755 CYThrow(context, exception);