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