]> git.saurik.com Git - cycript.git/blame - Tweak.mm
Support bridge support variables.
[cycript.git] / Tweak.mm
CommitLineData
62ca2b82 1/* Cyrker - Remove Execution Server and Disassembler
c1582939
JF
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
62ca2b82 5/* Modified BSD License {{{ */
c1582939
JF
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
62ca2b82 38/* }}} */
c1582939
JF
39
40#include <substrate.h>
04450da0 41#include "Struct.hpp"
c1582939 42
ea2d184c
JF
43#include "sig/parse.hpp"
44#include "sig/ffi_type.hpp"
45
46#include <apr-1/apr_pools.h>
47#include <apr-1/apr_strings.h>
48
c1582939
JF
49#include <unistd.h>
50
51#include <CoreFoundation/CoreFoundation.h>
52#include <CoreFoundation/CFLogUtilities.h>
53
54#include <CFNetwork/CFNetwork.h>
55#include <Foundation/Foundation.h>
56
57#include <JavaScriptCore/JSBase.h>
58#include <JavaScriptCore/JSValueRef.h>
59#include <JavaScriptCore/JSObjectRef.h>
60#include <JavaScriptCore/JSContextRef.h>
61#include <JavaScriptCore/JSStringRef.h>
62#include <JavaScriptCore/JSStringRefCF.h>
63
64#include <WebKit/WebScriptObject.h>
65
66#include <sys/types.h>
67#include <sys/socket.h>
68#include <netinet/in.h>
69
ea2d184c
JF
70#undef _assert
71#undef _trace
72
c1582939
JF
73/* XXX: bad _assert */
74#define _assert(test) do { \
75 if ((test)) break; \
62ca2b82
JF
76 CFLog(kCFLogLevelNotice, CFSTR("_assert(%s):%u"), #test, __LINE__); \
77 throw; \
c1582939
JF
78} while (false)
79
80#define _trace() do { \
62ca2b82 81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
82} while (false)
83
7ba62cfd
JF
84/* Objective-C Handle<> {{{ */
85template <typename Type_>
86class _H {
87 typedef _H<Type_> This_;
88
89 private:
90 Type_ *value_;
91
92 _finline void Retain_() {
93 if (value_ != nil)
94 [value_ retain];
95 }
96
97 _finline void Clear_() {
98 if (value_ != nil)
99 [value_ release];
100 }
101
102 public:
103 _finline _H(const This_ &rhs) :
104 value_(rhs.value_ == nil ? nil : [rhs.value_ retain])
105 {
106 }
107
108 _finline _H(Type_ *value = NULL, bool mended = false) :
109 value_(value)
110 {
111 if (!mended)
112 Retain_();
113 }
114
115 _finline ~_H() {
116 Clear_();
117 }
118
119 _finline operator Type_ *() const {
120 return value_;
121 }
122
123 _finline This_ &operator =(Type_ *value) {
124 if (value_ != value) {
125 Type_ *old(value_);
126 value_ = value;
127 Retain_();
128 if (old != nil)
129 [old release];
130 } return *this;
131 }
132};
133/* }}} */
707bcb93 134/* APR Pool Helpers {{{ */
b21525c7
JF
135void *operator new(size_t size, apr_pool_t *pool) {
136 return apr_palloc(pool, size);
137}
138
139void *operator new [](size_t size, apr_pool_t *pool) {
140 return apr_palloc(pool, size);
141}
142
707bcb93
JF
143class CYPool {
144 private:
145 apr_pool_t *pool_;
146
147 public:
148 CYPool() {
149 apr_pool_create(&pool_, NULL);
150 }
151
152 ~CYPool() {
153 apr_pool_destroy(pool_);
154 }
155
156 operator apr_pool_t *() const {
157 return pool_;
158 }
159};
160/* }}} */
161
162#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
163
ea2d184c
JF
164static JSContextRef Context_;
165
88c977fa
JF
166static JSClassRef Functor_;
167static JSClassRef Instance_;
168static JSClassRef Pointer_;
169static JSClassRef Selector_;
ea2d184c 170
c1582939 171static JSObjectRef Array_;
ea2d184c 172
62ca2b82
JF
173static JSStringRef name_;
174static JSStringRef message_;
c1582939 175static JSStringRef length_;
ea2d184c 176
c1582939
JF
177static Class NSCFBoolean_;
178
88c977fa
JF
179static NSMutableDictionary *Bridge_;
180
c1582939
JF
181struct Client {
182 CFHTTPMessageRef message_;
183 CFSocketRef socket_;
184};
185
0c862573 186JSObjectRef CYMakeObject(JSContextRef context, id object) {
88c977fa 187 return JSObjectMake(context, Instance_, [object retain]);
0c862573
JF
188}
189
7ba62cfd
JF
190@interface NSMethodSignature (Cyrver)
191- (NSString *) _typeString;
192@end
193
c1582939
JF
194@interface NSObject (Cyrver)
195- (NSString *) cy$toJSON;
ea2d184c 196- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
c1582939
JF
197@end
198
88c977fa
JF
199@interface NSString (Cyrver)
200- (void *) cy$symbol;
201@end
202
203@interface NSNumber (Cyrver)
204- (void *) cy$symbol;
205@end
206
c1582939 207@implementation NSObject (Cyrver)
62ca2b82 208
c1582939 209- (NSString *) cy$toJSON {
62ca2b82
JF
210 return [self description];
211}
212
ea2d184c 213- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
0c862573 214 return CYMakeObject(context, self);
ea2d184c
JF
215}
216
62ca2b82 217@end
c1582939
JF
218
219@implementation WebUndefined (Cyrver)
62ca2b82 220
c1582939
JF
221- (NSString *) cy$toJSON {
222 return @"undefined";
62ca2b82
JF
223}
224
225- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
226 return JSValueMakeUndefined(context);
227}
228
229@end
c1582939
JF
230
231@implementation NSArray (Cyrver)
62ca2b82 232
c1582939
JF
233- (NSString *) cy$toJSON {
234 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
235 [json appendString:@"["];
236
237 bool comma(false);
62ca2b82 238 for (id object in self) {
c1582939
JF
239 if (comma)
240 [json appendString:@","];
241 else
242 comma = true;
243 [json appendString:[object cy$toJSON]];
244 }
245
246 [json appendString:@"]"];
247 return json;
62ca2b82
JF
248}
249
250@end
251
252@implementation NSDictionary (Cyrver)
253
254- (NSString *) cy$toJSON {
255 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
7ba62cfd
JF
256 [json appendString:@"("];
257 [json appendString:@"{"];
62ca2b82
JF
258
259 bool comma(false);
260 for (id key in self) {
261 if (comma)
262 [json appendString:@","];
263 else
264 comma = true;
265 [json appendString:[key cy$toJSON]];
266 [json appendString:@":"];
267 NSObject *object([self objectForKey:key]);
268 [json appendString:[object cy$toJSON]];
269 }
270
271 [json appendString:@"})"];
272 return json;
273}
274
275@end
c1582939
JF
276
277@implementation NSNumber (Cyrver)
62ca2b82 278
c1582939
JF
279- (NSString *) cy$toJSON {
280 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
281}
282
283- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
284 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
285}
286
88c977fa
JF
287- (void *) cy$symbol {
288 return [self pointerValue];
289}
290
62ca2b82 291@end
c1582939
JF
292
293@implementation NSString (Cyrver)
62ca2b82 294
c1582939
JF
295- (NSString *) cy$toJSON {
296 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
297
c1582939
JF
298 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
299 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
300 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
301 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
302 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
303
304 CFStringInsert(json, 0, CFSTR("\""));
305 CFStringAppend(json, CFSTR("\""));
306
62ca2b82
JF
307 return [reinterpret_cast<const NSString *>(json) autorelease];
308}
309
88c977fa
JF
310- (void *) cy$symbol {
311 return dlsym(RTLD_DEFAULT, [self UTF8String]);
312}
313
62ca2b82
JF
314@end
315
b21525c7 316@interface CYJSObject : NSDictionary {
62ca2b82
JF
317 JSObjectRef object_;
318 JSContextRef context_;
319}
320
321- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
322
323- (NSUInteger) count;
324- (id) objectForKey:(id)key;
325- (NSEnumerator *) keyEnumerator;
326- (void) setObject:(id)object forKey:(id)key;
327- (void) removeObjectForKey:(id)key;
328
329@end
c1582939 330
b21525c7 331@interface CYJSArray : NSArray {
c1582939
JF
332 JSObjectRef object_;
333 JSContextRef context_;
334}
335
336- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
337
338- (NSUInteger) count;
339- (id) objectAtIndex:(NSUInteger)index;
340
341@end
342
62ca2b82 343JSContextRef JSGetContext() {
ea2d184c 344 return Context_;
62ca2b82
JF
345}
346
0c862573
JF
347#define CYCatch \
348 @catch (id error) { \
349 CYThrow(context, error, exception); \
350 return NULL; \
351 }
352
ea2d184c
JF
353void CYThrow(JSContextRef context, JSValueRef value);
354
b21525c7 355id CYCastNSObject(JSContextRef context, JSObjectRef object) {
88c977fa 356 if (JSValueIsObjectOfClass(context, object, Instance_))
c1582939 357 return reinterpret_cast<id>(JSObjectGetPrivate(object));
ea2d184c
JF
358 JSValueRef exception(NULL);
359 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
360 CYThrow(context, exception);
361 if (array)
b21525c7
JF
362 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
363 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
62ca2b82
JF
364}
365
77e87a6c
JF
366JSStringRef CYCopyJSString(id value) {
367 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
62ca2b82
JF
368}
369
77e87a6c
JF
370JSStringRef CYCopyJSString(const char *value) {
371 return JSStringCreateWithUTF8CString(value);
372}
373
374JSStringRef CYCopyJSString(JSStringRef value) {
375 return JSStringRetain(value);
376}
377
378JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
62ca2b82 379 JSValueRef exception(NULL);
ea2d184c
JF
380 JSStringRef string(JSValueToStringCopy(context, value, &exception));
381 CYThrow(context, exception);
77e87a6c
JF
382 return string;
383}
384
385// XXX: this is not a safe handle
386class CYString {
387 private:
388 JSStringRef string_;
389
390 public:
391 template <typename Arg0_>
392 CYString(Arg0_ arg0) {
393 string_ = CYCopyJSString(arg0);
394 }
395
396 template <typename Arg0_, typename Arg1_>
397 CYString(Arg0_ arg0, Arg1_ arg1) {
398 string_ = CYCopyJSString(arg0, arg1);
399 }
400
401 ~CYString() {
402 JSStringRelease(string_);
403 }
404
405 operator JSStringRef() const {
406 return string_;
407 }
408};
409
410CFStringRef CYCopyCFString(JSStringRef value) {
411 return JSStringCopyCFString(kCFAllocatorDefault, value);
412}
413
414CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
415 return CYCopyCFString(CYString(context, value));
c1582939
JF
416}
417
0c862573
JF
418CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
419 JSValueRef exception(NULL);
420 double number(JSValueToNumber(context, value, &exception));
421 CYThrow(context, exception);
422 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
423}
424
62ca2b82
JF
425NSString *CYCastNSString(JSStringRef value) {
426 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
427}
428
ea2d184c 429CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
0c862573 430 switch (JSValueGetType(context, value)) {
c1582939 431 case kJSTypeUndefined:
62ca2b82 432 return CFRetain([WebUndefined undefined]);
c1582939
JF
433 case kJSTypeNull:
434 return nil;
c1582939 435 case kJSTypeBoolean:
ea2d184c 436 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
0c862573
JF
437 case kJSTypeNumber:
438 return CYCopyCFNumber(context, value);
62ca2b82 439 case kJSTypeString:
ea2d184c 440 return CYCopyCFString(context, value);
c1582939 441 case kJSTypeObject:
b21525c7 442 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
c1582939
JF
443 default:
444 _assert(false);
c1582939
JF
445 }
446}
447
62ca2b82
JF
448NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
449 size_t size(JSPropertyNameArrayGetCount(names));
450 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
451 for (size_t index(0); index != size; ++index)
452 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
453 return array;
454}
455
ea2d184c
JF
456id CYCastNSObject(JSContextRef context, JSValueRef value) {
457 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
c1582939
JF
458 return object == nil ? nil : [object autorelease];
459}
460
ea2d184c 461void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
462 if (value == NULL)
463 return;
ea2d184c 464 @throw CYCastNSObject(context, value);
62ca2b82
JF
465}
466
ea2d184c
JF
467JSValueRef CYCastJSValue(JSContextRef context, id value) {
468 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
62ca2b82
JF
469}
470
7ba62cfd
JF
471void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
472 *exception = CYCastJSValue(context, error);
473}
474
b21525c7 475@implementation CYJSObject
62ca2b82
JF
476
477- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
478 if ((self = [super init]) != nil) {
479 object_ = object;
480 context_ = context;
481 } return self;
482}
483
484- (NSUInteger) count {
485 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
486 size_t size(JSPropertyNameArrayGetCount(names));
487 JSPropertyNameArrayRelease(names);
488 return size;
489}
490
491- (id) objectForKey:(id)key {
492 JSValueRef exception(NULL);
7ba62cfd 493 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
62ca2b82
JF
494 CYThrow(context_, exception);
495 return CYCastNSObject(context_, value);
496}
497
498- (NSEnumerator *) keyEnumerator {
499 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
500 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
501 JSPropertyNameArrayRelease(names);
502 return enumerator;
503}
504
505- (void) setObject:(id)object forKey:(id)key {
506 JSValueRef exception(NULL);
7ba62cfd 507 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
62ca2b82
JF
508 CYThrow(context_, exception);
509}
510
511- (void) removeObjectForKey:(id)key {
512 JSValueRef exception(NULL);
62ca2b82 513 // XXX: this returns a bool
7ba62cfd 514 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
62ca2b82
JF
515 CYThrow(context_, exception);
516}
517
518@end
519
b21525c7 520@implementation CYJSArray
c1582939
JF
521
522- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
523 if ((self = [super init]) != nil) {
524 object_ = object;
525 context_ = context;
526 } return self;
527}
528
529- (NSUInteger) count {
62ca2b82
JF
530 JSValueRef exception(NULL);
531 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
532 CYThrow(context_, exception);
533 double number(JSValueToNumber(context_, value, &exception));
534 CYThrow(context_, exception);
535 return number;
c1582939
JF
536}
537
538- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
539 JSValueRef exception(NULL);
540 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
541 CYThrow(context_, exception);
542 id object(CYCastNSObject(context_, value));
c1582939
JF
543 return object == nil ? [NSNull null] : object;
544}
545
546@end
547
ea2d184c
JF
548CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
549 id object(CYCastNSObject(context, value));
62ca2b82 550 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
c1582939
JF
551}
552
553static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
554 switch (type) {
555 case kCFSocketDataCallBack:
556 CFDataRef data(reinterpret_cast<CFDataRef>(value));
557 Client *client(reinterpret_cast<Client *>(info));
558
559 if (client->message_ == NULL)
560 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
561
562 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
563 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
564 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
565 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
566 Boolean absolute;
567 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
568 CFRelease(client->message_);
569
570 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
571 CFRelease(path);
572
573 JSStringRef script(JSStringCreateWithCFString(code));
574 CFRelease(code);
575
62ca2b82 576 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
c1582939
JF
577 JSStringRelease(script);
578
579 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
580 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
581
62ca2b82 582 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
c1582939
JF
583 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
584 CFRelease(json);
585
586 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
587 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
588 CFRelease(length);
589
590 CFHTTPMessageSetBody(response, body);
591 CFRelease(body);
592
593 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
594 CFRelease(response);
595
596 CFSocketSendData(socket, NULL, serialized, 0);
597 CFRelease(serialized);
598
599 CFRelease(url);
600 }
601 break;
602 }
603}
604
605static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
606 switch (type) {
607 case kCFSocketAcceptCallBack:
608 Client *client(new Client());
609
610 client->message_ = NULL;
611
612 CFSocketContext context;
613 context.version = 0;
614 context.info = client;
615 context.retain = NULL;
616 context.release = NULL;
617 context.copyDescription = NULL;
618
619 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
620
621 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
622 break;
623 }
624}
625
88c977fa 626static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef *exception) {
c1582939
JF
627 return NULL;
628}
629
ea2d184c
JF
630typedef id jocData;
631
88c977fa 632static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
0c862573
JF
633 @try {
634 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
635 return CYMakeObject(context, [[data alloc] autorelease]);
636 } CYCatch
637}
638
04450da0 639struct ptrData {
b21525c7 640 apr_pool_t *pool_;
04450da0 641 void *value_;
b21525c7 642 sig::Type type_;
77e87a6c
JF
643
644 void *operator new(size_t size) {
645 apr_pool_t *pool;
646 apr_pool_create(&pool, NULL);
647 void *data(apr_palloc(pool, size));
648 reinterpret_cast<ptrData *>(data)->pool_ = pool;
649 return data;;
650 }
651
652 ptrData(void *value) :
653 value_(value)
654 {
655 }
656};
657
658struct ffiData : ptrData {
659 sig::Signature signature_;
660 ffi_cif cif_;
661
662 ffiData(void (*value)(), const char *type) :
663 ptrData(reinterpret_cast<void *>(value))
664 {
665 sig::Parse(pool_, &signature_, type);
666 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
667 }
668};
669
670struct selData : ptrData {
671 selData(SEL value) :
672 ptrData(value)
673 {
674 }
04450da0
JF
675};
676
88c977fa 677static void Pointer_finalize(JSObjectRef object) {
04450da0 678 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
b21525c7 679 apr_pool_destroy(data->pool_);
04450da0
JF
680}
681
88c977fa 682static void Instance_finalize(JSObjectRef object) {
ea2d184c
JF
683 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
684 [data release];
685}
686
88c977fa
JF
687JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
688 ffiData *data(new ffiData(function, type));
689 return JSObjectMake(context, Functor_, data);
690}
691
692
693JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
694 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
695}
696
ea2d184c
JF
697void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
698 JSValueRef exception(NULL);
7ba62cfd 699 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
ea2d184c
JF
700 CYThrow(context, exception);
701}
702
7ba62cfd
JF
703char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
704 size_t size(JSStringGetMaximumUTF8CStringSize(value));
b21525c7 705 char *string(new(pool) char[size]);
7ba62cfd
JF
706 JSStringGetUTF8CString(value, string, size);
707 JSStringRelease(value);
708 return string;
709}
710
77e87a6c
JF
711char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
712 return CYPoolCString(pool, CYString(context, value));
713}
714
b21525c7
JF
715// XXX: this macro is dangerous
716#define CYCastCString(context, value) ({ \
717 JSValueRef exception(NULL); \
718 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
719 CYThrow(context, exception); \
720 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
721 char *utf8(reinterpret_cast<char *>(alloca(size))); \
722 JSStringGetUTF8CString(string, utf8, size); \
723 JSStringRelease(string); \
724 utf8; \
725})
726
7ba62cfd
JF
727SEL CYCastSEL(JSContextRef context, JSValueRef value) {
728 if (JSValueIsNull(context, value))
729 return NULL;
88c977fa 730 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
77e87a6c
JF
731 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
732 return reinterpret_cast<SEL>(data->value_);
733 } else
b21525c7
JF
734 return sel_registerName(CYCastCString(context, value));
735}
736
737void *CYCastPointer(JSContextRef context, JSValueRef value) {
738 switch (JSValueGetType(context, value)) {
739 case kJSTypeNull:
740 return NULL;
b21525c7
JF
741 case kJSTypeString:
742 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
b21525c7 743 case kJSTypeObject:
77e87a6c 744 // XXX: maybe support more than just pointers, like ffis and sels
88c977fa 745 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
b21525c7
JF
746 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
747 return data->value_;
748 }
749 default:
750 JSValueRef exception(NULL);
751 double number(JSValueToNumber(context, value, &exception));
752 CYThrow(context, exception);
753 return reinterpret_cast<void *>(static_cast<uintptr_t>(number));
7ba62cfd
JF
754 }
755}
756
43cb3d68 757void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
ea2d184c
JF
758 switch (type->primitive) {
759 case sig::boolean_P:
760 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
761 break;
762
43cb3d68 763#define CYPoolFFI_(primitive, native) \
ea2d184c 764 case sig::primitive ## _P: { \
7ba62cfd
JF
765 JSValueRef exception(NULL); \
766 double number(JSValueToNumber(context, value, &exception)); \
767 CYThrow(context, exception); \
768 *reinterpret_cast<native *>(data) = number; \
ea2d184c
JF
769 } break;
770
43cb3d68
JF
771 CYPoolFFI_(uchar, unsigned char)
772 CYPoolFFI_(char, char)
773 CYPoolFFI_(ushort, unsigned short)
774 CYPoolFFI_(short, short)
775 CYPoolFFI_(ulong, unsigned long)
776 CYPoolFFI_(long, long)
777 CYPoolFFI_(uint, unsigned int)
778 CYPoolFFI_(int, int)
779 CYPoolFFI_(ulonglong, unsigned long long)
780 CYPoolFFI_(longlong, long long)
781 CYPoolFFI_(float, float)
782 CYPoolFFI_(double, double)
ea2d184c
JF
783
784 case sig::object_P:
785 case sig::typename_P:
7ba62cfd
JF
786 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
787 break;
788
ea2d184c 789 case sig::selector_P:
7ba62cfd
JF
790 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
791 break;
ea2d184c 792
b21525c7
JF
793 case sig::pointer_P:
794 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
795 break;
ea2d184c 796
77e87a6c
JF
797 case sig::string_P:
798 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
799 break;
7ba62cfd 800
ea2d184c
JF
801 case sig::struct_P:
802 goto fail;
803
804 case sig::void_P:
805 break;
806
807 default: fail:
43cb3d68 808 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
ea2d184c
JF
809 _assert(false);
810 }
811}
812
43cb3d68 813JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
ea2d184c
JF
814 JSValueRef value;
815
816 switch (type->primitive) {
817 case sig::boolean_P:
818 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
819 break;
820
821#define CYFromFFI_(primitive, native) \
822 case sig::primitive ## _P: \
823 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
824 break;
825
826 CYFromFFI_(uchar, unsigned char)
827 CYFromFFI_(char, char)
828 CYFromFFI_(ushort, unsigned short)
829 CYFromFFI_(short, short)
830 CYFromFFI_(ulong, unsigned long)
831 CYFromFFI_(long, long)
832 CYFromFFI_(uint, unsigned int)
833 CYFromFFI_(int, int)
834 CYFromFFI_(ulonglong, unsigned long long)
835 CYFromFFI_(longlong, long long)
836 CYFromFFI_(float, float)
837 CYFromFFI_(double, double)
838
839 case sig::object_P:
840 case sig::typename_P: {
841 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
842 } break;
843
7ba62cfd 844 case sig::selector_P: {
77e87a6c
JF
845 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
846 selData *data(new selData(sel));
88c977fa 847 value = JSObjectMake(context, Selector_, data);
77e87a6c 848 } else value = JSValueMakeNull(context);
7ba62cfd
JF
849 } break;
850
851 case sig::pointer_P: {
04450da0 852 if (void *pointer = *reinterpret_cast<void **>(data)) {
77e87a6c 853 ptrData *data(new ptrData(pointer));
88c977fa 854 value = JSObjectMake(context, Pointer_, data);
04450da0 855 } else value = JSValueMakeNull(context);
7ba62cfd 856 } break;
ea2d184c
JF
857
858 case sig::string_P: {
859 char *utf8(*reinterpret_cast<char **>(data));
7ba62cfd 860 value = utf8 == NULL ? JSValueMakeNull(context) : JSValueMakeString(context, CYString(utf8));
ea2d184c
JF
861 } break;
862
863 case sig::struct_P:
864 goto fail;
865
866 case sig::void_P:
867 value = NULL;
868 break;
869
870 default: fail:
871 NSLog(@"CYFromFFI(%c)\n", type->primitive);
872 _assert(false);
873 }
874
875 return value;
876}
877
0c862573 878static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
7ba62cfd 879 @try {
85a33bf5
JF
880 if (count != signature->count - 1)
881 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi function"];
882
7ba62cfd
JF
883 CYPool pool;
884 void *values[count];
ea2d184c 885
7ba62cfd
JF
886 for (unsigned index(0); index != count; ++index) {
887 sig::Element *element(&signature->elements[index + 1]);
77e87a6c 888 // XXX: alignment?
b21525c7 889 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
43cb3d68 890 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
7ba62cfd 891 }
ea2d184c 892
7ba62cfd
JF
893 uint8_t value[cif->rtype->size];
894 ffi_call(cif, function, value, values);
895
43cb3d68 896 return CYFromFFI(context, signature->elements[0].type, value);
0c862573 897 } CYCatch
7ba62cfd 898}
ea2d184c 899
707bcb93
JF
900static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) { _pooled
901 @try {
902 NSString *string(CYCastNSString(name));
903 if (Class _class = NSClassFromString(string))
904 return CYMakeObject(context, _class);
905 if (NSMutableArray *entry = [Bridge_ objectForKey:string])
906 switch ([[entry objectAtIndex:0] intValue]) {
907 case 0:
908 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
909 case 1:
910 return CYMakeFunction(context, [string cy$symbol], [[entry objectAtIndex:1] UTF8String]);
911 case 2:
912 CYPool pool;
913 sig::Signature signature;
914 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
915 return CYFromFFI(context, signature.elements[0].type, [string cy$symbol]);
916 }
917 return NULL;
918 } CYCatch
919}
920
04450da0
JF
921bool stret(ffi_type *ffi_type) {
922 return ffi_type->type == FFI_TYPE_STRUCT && (
923 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
924 struct_forward_array[ffi_type->size] != 0
925 );
926}
927
7ba62cfd 928static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
7ba62cfd 929 const char *type;
ea2d184c
JF
930
931 @try {
85a33bf5
JF
932 if (count < 2)
933 [NSException raise:NSInvalidArgumentException format:@"too few arguments to objc_msgSend"];
934
7ba62cfd
JF
935 id self(CYCastNSObject(context, arguments[0]));
936 if (self == nil)
937 return JSValueMakeNull(context);
7ba62cfd 938
85a33bf5 939 SEL _cmd(CYCastSEL(context, arguments[1]));
7ba62cfd 940 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
85a33bf5
JF
941 if (method == nil)
942 [NSException raise:NSInvalidArgumentException format:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self];
7ba62cfd
JF
943
944 type = [[method _typeString] UTF8String];
0c862573 945 } CYCatch
ea2d184c 946
7ba62cfd
JF
947 CYPool pool;
948
949 sig::Signature signature;
950 sig::Parse(pool, &signature, type);
ea2d184c 951
7ba62cfd 952 ffi_cif cif;
b21525c7 953 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
7ba62cfd 954
04450da0 955 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
7ba62cfd
JF
956 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
957}
958
959static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
960 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
77e87a6c 961 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
ea2d184c
JF
962}
963
b21525c7
JF
964JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
965 @try {
966 if (count != 2)
967 [NSException raise:NSInvalidArgumentException format:@"incorrect number of arguments to ffi constructor"];
88c977fa 968 void *function(CYCastPointer(context, arguments[0]));
b21525c7
JF
969 const char *type(CYCastCString(context, arguments[1]));
970 return CYMakeFunction(context, function, type);
0c862573 971 } CYCatch
ea2d184c
JF
972}
973
88c977fa 974JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) {
04450da0
JF
975 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
976 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
977}
978
88c977fa
JF
979static JSStaticValue Pointer_staticValues[2] = {
980 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
981 {NULL, NULL, NULL, 0}
982};
983
7ba62cfd 984MSInitialize { _pooled
ea2d184c
JF
985 apr_initialize();
986
c1582939
JF
987 NSCFBoolean_ = objc_getClass("NSCFBoolean");
988
989 pid_t pid(getpid());
990
991 struct sockaddr_in address;
992 address.sin_len = sizeof(address);
993 address.sin_family = AF_INET;
994 address.sin_addr.s_addr = INADDR_ANY;
995 address.sin_port = htons(10000 + pid);
996
997 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
998
999 CFSocketSignature signature;
1000 signature.protocolFamily = AF_INET;
1001 signature.socketType = SOCK_STREAM;
1002 signature.protocol = IPPROTO_TCP;
1003 signature.address = data;
1004
1005 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1006 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1007
1008 JSClassDefinition definition;
1009
1010 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1011 definition.className = "Pointer";
1012 definition.staticValues = Pointer_staticValues;
1013 definition.finalize = &Pointer_finalize;
1014 Pointer_ = JSClassCreate(&definition);
c1582939
JF
1015
1016 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1017 definition.className = "Functor";
1018 definition.parentClass = Pointer_;
1019 definition.callAsFunction = &ffi_callAsFunction;
1020 Functor_ = JSClassCreate(&definition);
7ba62cfd 1021
77e87a6c 1022 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1023 definition.className = "Selector";
1024 definition.parentClass = Pointer_;
1025 Selector_ = JSClassCreate(&definition);
77e87a6c 1026
7ba62cfd 1027 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1028 definition.className = "Instance_";
1029 definition.getProperty = &Instance_getProperty;
1030 definition.callAsConstructor = &Instance_callAsConstructor;
1031 definition.finalize = &Instance_finalize;
1032 Instance_ = JSClassCreate(&definition);
7ba62cfd
JF
1033
1034 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1035 definition.getProperty = &Global_getProperty;
1036 JSClassRef Global(JSClassCreate(&definition));
c1582939 1037
88c977fa 1038 JSContextRef context(JSGlobalContextCreate(Global));
ea2d184c
JF
1039 Context_ = context;
1040
1041 JSObjectRef global(JSContextGetGlobalObject(context));
c1582939 1042
88c977fa 1043 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
7ba62cfd
JF
1044
1045 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1046
88c977fa 1047 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcyrver.plist"] retain];
c1582939 1048
62ca2b82
JF
1049 name_ = JSStringCreateWithUTF8CString("name");
1050 message_ = JSStringCreateWithUTF8CString("message");
c1582939
JF
1051 length_ = JSStringCreateWithUTF8CString("length");
1052
62ca2b82 1053 JSValueRef exception(NULL);
7ba62cfd 1054 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
ea2d184c 1055 CYThrow(context, exception);
62ca2b82 1056 Array_ = JSValueToObject(JSGetContext(), value, &exception);
ea2d184c 1057 CYThrow(context, exception);
c1582939 1058}