]> git.saurik.com Git - cycript.git/blob - Tweak.mm
ba44bfdb28a32955890cb5adddc1dec970632eeb
[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 /* XXX: bad _assert */
74 #define _assert(test) do { \
75 if (!(test)) \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
77 @throw [NSNumber class]; \
78 } while (false)
79
80 #define _trace() do { \
81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
82 } while (false)
83
84 /* Objective-C Handle<> {{{ */
85 template <typename Type_>
86 class _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 /* }}} */
134 /* APR Pool Helpers {{{ */
135 void *operator new(size_t size, apr_pool_t *pool) {
136 return apr_palloc(pool, size);
137 }
138
139 void *operator new [](size_t size, apr_pool_t *pool) {
140 return apr_palloc(pool, size);
141 }
142
143 class 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
164 static JSContextRef Context_;
165
166 static JSClassRef Functor_;
167 static JSClassRef Instance_;
168 static JSClassRef Pointer_;
169 static JSClassRef Selector_;
170
171 static JSObjectRef Array_;
172
173 static JSStringRef name_;
174 static JSStringRef message_;
175 static JSStringRef length_;
176
177 static Class NSCFBoolean_;
178
179 static NSMutableDictionary *Bridge_;
180
181 struct Client {
182 CFHTTPMessageRef message_;
183 CFSocketRef socket_;
184 };
185
186 JSObjectRef CYMakeObject(JSContextRef context, id object) {
187 return JSObjectMake(context, Instance_, [object retain]);
188 }
189
190 @interface NSMethodSignature (Cyrver)
191 - (NSString *) _typeString;
192 @end
193
194 @interface NSObject (Cyrver)
195 - (NSString *) cy$toJSON;
196 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
197 @end
198
199 @interface NSString (Cyrver)
200 - (void *) cy$symbol;
201 @end
202
203 @interface NSNumber (Cyrver)
204 - (void *) cy$symbol;
205 @end
206
207 @implementation NSObject (Cyrver)
208
209 - (NSString *) cy$toJSON {
210 return [self description];
211 }
212
213 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
214 return CYMakeObject(context, self);
215 }
216
217 @end
218
219 @implementation WebUndefined (Cyrver)
220
221 - (NSString *) cy$toJSON {
222 return @"undefined";
223 }
224
225 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
226 return JSValueMakeUndefined(context);
227 }
228
229 @end
230
231 @implementation NSArray (Cyrver)
232
233 - (NSString *) cy$toJSON {
234 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
235 [json appendString:@"["];
236
237 bool comma(false);
238 for (id object in self) {
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;
248 }
249
250 @end
251
252 @implementation NSDictionary (Cyrver)
253
254 - (NSString *) cy$toJSON {
255 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
256 [json appendString:@"("];
257 [json appendString:@"{"];
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
276
277 @implementation NSNumber (Cyrver)
278
279 - (NSString *) cy$toJSON {
280 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
281 }
282
283 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
284 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
285 }
286
287 - (void *) cy$symbol {
288 return [self pointerValue];
289 }
290
291 @end
292
293 @implementation NSString (Cyrver)
294
295 - (NSString *) cy$toJSON {
296 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
297
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
307 return [reinterpret_cast<const NSString *>(json) autorelease];
308 }
309
310 - (void *) cy$symbol {
311 return dlsym(RTLD_DEFAULT, [self UTF8String]);
312 }
313
314 @end
315
316 @interface CYJSObject : NSDictionary {
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
330
331 @interface CYJSArray : NSArray {
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
343 JSContextRef JSGetContext() {
344 return Context_;
345 }
346
347 #define CYCatch \
348 @catch (id error) { \
349 CYThrow(context, error, exception); \
350 return NULL; \
351 }
352
353 void CYThrow(JSContextRef context, JSValueRef value);
354
355 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
356 if (JSValueIsObjectOfClass(context, object, Instance_))
357 return reinterpret_cast<id>(JSObjectGetPrivate(object));
358 JSValueRef exception(NULL);
359 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
360 CYThrow(context, exception);
361 if (array)
362 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
363 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
364 }
365
366 JSStringRef CYCopyJSString(id value) {
367 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
368 }
369
370 JSStringRef CYCopyJSString(const char *value) {
371 return JSStringCreateWithUTF8CString(value);
372 }
373
374 JSStringRef CYCopyJSString(JSStringRef value) {
375 return JSStringRetain(value);
376 }
377
378 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
379 JSValueRef exception(NULL);
380 JSStringRef string(JSValueToStringCopy(context, value, &exception));
381 CYThrow(context, exception);
382 return string;
383 }
384
385 // XXX: this is not a safe handle
386 class 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
410 CFStringRef CYCopyCFString(JSStringRef value) {
411 return JSStringCopyCFString(kCFAllocatorDefault, value);
412 }
413
414 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
415 return CYCopyCFString(CYString(context, value));
416 }
417
418 CFNumberRef 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
425 NSString *CYCastNSString(JSStringRef value) {
426 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
427 }
428
429 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
430 JSType type(JSValueGetType(context, value));
431 switch (type) {
432 case kJSTypeUndefined:
433 return CFRetain([WebUndefined undefined]);
434 case kJSTypeNull:
435 return nil;
436 case kJSTypeBoolean:
437 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
438 case kJSTypeNumber:
439 return CYCopyCFNumber(context, value);
440 case kJSTypeString:
441 return CYCopyCFString(context, value);
442 case kJSTypeObject:
443 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
444 default:
445 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
446 }
447 }
448
449 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
450 size_t size(JSPropertyNameArrayGetCount(names));
451 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
452 for (size_t index(0); index != size; ++index)
453 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
454 return array;
455 }
456
457 id CYCastNSObject(JSContextRef context, JSValueRef value) {
458 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
459 return object == nil ? nil : [object autorelease];
460 }
461
462 void CYThrow(JSContextRef context, JSValueRef value) {
463 if (value == NULL)
464 return;
465 @throw CYCastNSObject(context, value);
466 }
467
468 JSValueRef CYCastJSValue(JSContextRef context, id value) {
469 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
470 }
471
472 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
473 *exception = CYCastJSValue(context, error);
474 }
475
476 @implementation CYJSObject
477
478 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
479 if ((self = [super init]) != nil) {
480 object_ = object;
481 context_ = context;
482 } return self;
483 }
484
485 - (NSUInteger) count {
486 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
487 size_t size(JSPropertyNameArrayGetCount(names));
488 JSPropertyNameArrayRelease(names);
489 return size;
490 }
491
492 - (id) objectForKey:(id)key {
493 JSValueRef exception(NULL);
494 JSValueRef value(JSObjectGetProperty(context_, object_, CYString(key), &exception));
495 CYThrow(context_, exception);
496 return CYCastNSObject(context_, value);
497 }
498
499 - (NSEnumerator *) keyEnumerator {
500 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
501 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
502 JSPropertyNameArrayRelease(names);
503 return enumerator;
504 }
505
506 - (void) setObject:(id)object forKey:(id)key {
507 JSValueRef exception(NULL);
508 JSObjectSetProperty(context_, object_, CYString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
509 CYThrow(context_, exception);
510 }
511
512 - (void) removeObjectForKey:(id)key {
513 JSValueRef exception(NULL);
514 // XXX: this returns a bool
515 JSObjectDeleteProperty(context_, object_, CYString(key), &exception);
516 CYThrow(context_, exception);
517 }
518
519 @end
520
521 @implementation CYJSArray
522
523 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
524 if ((self = [super init]) != nil) {
525 object_ = object;
526 context_ = context;
527 } return self;
528 }
529
530 - (NSUInteger) count {
531 JSValueRef exception(NULL);
532 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
533 CYThrow(context_, exception);
534 double number(JSValueToNumber(context_, value, &exception));
535 CYThrow(context_, exception);
536 return number;
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 propertyName, JSValueRef *exception) {
628 return NULL;
629 }
630
631 typedef id jocData;
632
633 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
634 @try {
635 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
636 return CYMakeObject(context, [[data alloc] autorelease]);
637 } CYCatch
638 }
639
640 struct ptrData {
641 apr_pool_t *pool_;
642 void *value_;
643 sig::Type type_;
644
645 void *operator new(size_t size) {
646 apr_pool_t *pool;
647 apr_pool_create(&pool, NULL);
648 void *data(apr_palloc(pool, size));
649 reinterpret_cast<ptrData *>(data)->pool_ = pool;
650 return data;;
651 }
652
653 ptrData(void *value) :
654 value_(value)
655 {
656 }
657 };
658
659 struct ffiData : ptrData {
660 sig::Signature signature_;
661 ffi_cif cif_;
662
663 ffiData(void (*value)(), const char *type) :
664 ptrData(reinterpret_cast<void *>(value))
665 {
666 sig::Parse(pool_, &signature_, type);
667 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
668 }
669 };
670
671 struct selData : ptrData {
672 selData(SEL value) :
673 ptrData(value)
674 {
675 }
676 };
677
678 static void Pointer_finalize(JSObjectRef object) {
679 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
680 apr_pool_destroy(data->pool_);
681 }
682
683 static void Instance_finalize(JSObjectRef object) {
684 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
685 [data release];
686 }
687
688 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
689 ffiData *data(new ffiData(function, type));
690 return JSObjectMake(context, Functor_, data);
691 }
692
693
694 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
695 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
696 }
697
698 void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
699 JSValueRef exception(NULL);
700 JSObjectSetProperty(context, object, CYString(name), value, kJSPropertyAttributeNone, &exception);
701 CYThrow(context, exception);
702 }
703
704 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
705 size_t size(JSStringGetMaximumUTF8CStringSize(value));
706 char *string(new(pool) char[size]);
707 JSStringGetUTF8CString(value, string, size);
708 JSStringRelease(value);
709 return string;
710 }
711
712 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
713 return CYPoolCString(pool, CYString(context, value));
714 }
715
716 // XXX: this macro is dangerous
717 #define CYCastCString(context, value) ({ \
718 JSValueRef exception(NULL); \
719 JSStringRef string(JSValueToStringCopy(context, value, &exception)); \
720 CYThrow(context, exception); \
721 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
722 char *utf8(reinterpret_cast<char *>(alloca(size))); \
723 JSStringGetUTF8CString(string, utf8, size); \
724 JSStringRelease(string); \
725 utf8; \
726 })
727
728 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
729 if (JSValueIsNull(context, value))
730 return NULL;
731 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
732 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
733 return reinterpret_cast<SEL>(data->value_);
734 } else
735 return sel_registerName(CYCastCString(context, value));
736 }
737
738 void *CYCastPointer(JSContextRef context, JSValueRef value) {
739 switch (JSValueGetType(context, value)) {
740 case kJSTypeNull:
741 return NULL;
742 case kJSTypeString:
743 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
744 case kJSTypeObject:
745 // XXX: maybe support more than just pointers, like ffis and sels
746 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
747 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
748 return data->value_;
749 }
750 default:
751 JSValueRef exception(NULL);
752 double number(JSValueToNumber(context, value, &exception));
753 CYThrow(context, exception);
754 return reinterpret_cast<void *>(static_cast<uintptr_t>(number));
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 JSValueRef exception(NULL); \
767 double number(JSValueToNumber(context, value, &exception)); \
768 CYThrow(context, exception); \
769 *reinterpret_cast<native *>(data) = number; \
770 } break;
771
772 CYPoolFFI_(uchar, unsigned char)
773 CYPoolFFI_(char, char)
774 CYPoolFFI_(ushort, unsigned short)
775 CYPoolFFI_(short, short)
776 CYPoolFFI_(ulong, unsigned long)
777 CYPoolFFI_(long, long)
778 CYPoolFFI_(uint, unsigned int)
779 CYPoolFFI_(int, int)
780 CYPoolFFI_(ulonglong, unsigned long long)
781 CYPoolFFI_(longlong, long long)
782 CYPoolFFI_(float, float)
783 CYPoolFFI_(double, double)
784
785 case sig::object_P:
786 case sig::typename_P:
787 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
788 break;
789
790 case sig::selector_P:
791 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
792 break;
793
794 case sig::pointer_P:
795 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
796 break;
797
798 case sig::string_P:
799 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
800 break;
801
802 case sig::struct_P:
803 goto fail;
804
805 case sig::void_P:
806 break;
807
808 default: fail:
809 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
810 _assert(false);
811 }
812 }
813
814 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
815 JSValueRef value;
816
817 switch (type->primitive) {
818 case sig::boolean_P:
819 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
820 break;
821
822 #define CYFromFFI_(primitive, native) \
823 case sig::primitive ## _P: \
824 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
825 break;
826
827 CYFromFFI_(uchar, unsigned char)
828 CYFromFFI_(char, char)
829 CYFromFFI_(ushort, unsigned short)
830 CYFromFFI_(short, short)
831 CYFromFFI_(ulong, unsigned long)
832 CYFromFFI_(long, long)
833 CYFromFFI_(uint, unsigned int)
834 CYFromFFI_(int, int)
835 CYFromFFI_(ulonglong, unsigned long long)
836 CYFromFFI_(longlong, long long)
837 CYFromFFI_(float, float)
838 CYFromFFI_(double, double)
839
840 case sig::object_P:
841 case sig::typename_P: {
842 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
843 } break;
844
845 case sig::selector_P: {
846 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
847 selData *data(new selData(sel));
848 value = JSObjectMake(context, Selector_, data);
849 } else value = JSValueMakeNull(context);
850 } break;
851
852 case sig::pointer_P: {
853 if (void *pointer = *reinterpret_cast<void **>(data)) {
854 ptrData *data(new ptrData(pointer));
855 value = JSObjectMake(context, Pointer_, data);
856 } else value = JSValueMakeNull(context);
857 } break;
858
859 case sig::string_P: {
860 char *utf8(*reinterpret_cast<char **>(data));
861 value = utf8 == NULL ? JSValueMakeNull(context) : JSValueMakeString(context, CYString(utf8));
862 } break;
863
864 case sig::struct_P:
865 goto fail;
866
867 case sig::void_P:
868 value = NULL;
869 break;
870
871 default: fail:
872 NSLog(@"CYFromFFI(%c)\n", type->primitive);
873 _assert(false);
874 }
875
876 return value;
877 }
878
879 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
880 @try {
881 if (count != signature->count - 1)
882 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
883
884 CYPool pool;
885 void *values[count];
886
887 for (unsigned index(0); index != count; ++index) {
888 sig::Element *element(&signature->elements[index + 1]);
889 // XXX: alignment?
890 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
891 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
892 }
893
894 uint8_t value[cif->rtype->size];
895 ffi_call(cif, function, value, values);
896
897 return CYFromFFI(context, signature->elements[0].type, value);
898 } CYCatch
899 }
900
901 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) { _pooled
902 @try {
903 NSString *string(CYCastNSString(name));
904 if (Class _class = NSClassFromString(string))
905 return CYMakeObject(context, _class);
906 if (NSMutableArray *entry = [Bridge_ objectForKey:string])
907 switch ([[entry objectAtIndex:0] intValue]) {
908 case 0:
909 return JSEvaluateScript(JSGetContext(), CYString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
910 case 1:
911 return CYMakeFunction(context, [string cy$symbol], [[entry objectAtIndex:1] UTF8String]);
912 case 2:
913 CYPool pool;
914 sig::Signature signature;
915 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
916 return CYFromFFI(context, signature.elements[0].type, [string cy$symbol]);
917 }
918 return NULL;
919 } CYCatch
920 }
921
922 bool stret(ffi_type *ffi_type) {
923 return ffi_type->type == FFI_TYPE_STRUCT && (
924 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
925 struct_forward_array[ffi_type->size] != 0
926 );
927 }
928
929 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
930 const char *type;
931
932 @try {
933 if (count < 2)
934 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
935
936 id self(CYCastNSObject(context, arguments[0]));
937 if (self == nil)
938 return JSValueMakeNull(context);
939
940 SEL _cmd(CYCastSEL(context, arguments[1]));
941 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
942 if (method == nil)
943 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
944
945 type = [[method _typeString] UTF8String];
946 } CYCatch
947
948 CYPool pool;
949
950 sig::Signature signature;
951 sig::Parse(pool, &signature, type);
952
953 ffi_cif cif;
954 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
955
956 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
957 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
958 }
959
960 static JSValueRef ffi_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
961 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
962 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
963 }
964
965 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
966 @try {
967 if (count != 2)
968 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
969 void *function(CYCastPointer(context, arguments[0]));
970 const char *type(CYCastCString(context, arguments[1]));
971 return CYMakeFunction(context, function, type);
972 } CYCatch
973 }
974
975 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef *exception) {
976 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
977 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
978 }
979
980 static JSStaticValue Pointer_staticValues[2] = {
981 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
982 {NULL, NULL, NULL, 0}
983 };
984
985 MSInitialize { _pooled
986 apr_initialize();
987
988 NSCFBoolean_ = objc_getClass("NSCFBoolean");
989
990 pid_t pid(getpid());
991
992 struct sockaddr_in address;
993 address.sin_len = sizeof(address);
994 address.sin_family = AF_INET;
995 address.sin_addr.s_addr = INADDR_ANY;
996 address.sin_port = htons(10000 + pid);
997
998 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
999
1000 CFSocketSignature signature;
1001 signature.protocolFamily = AF_INET;
1002 signature.socketType = SOCK_STREAM;
1003 signature.protocol = IPPROTO_TCP;
1004 signature.address = data;
1005
1006 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1007 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1008
1009 JSClassDefinition definition;
1010
1011 definition = kJSClassDefinitionEmpty;
1012 definition.className = "Pointer";
1013 definition.staticValues = Pointer_staticValues;
1014 definition.finalize = &Pointer_finalize;
1015 Pointer_ = JSClassCreate(&definition);
1016
1017 definition = kJSClassDefinitionEmpty;
1018 definition.className = "Functor";
1019 definition.parentClass = Pointer_;
1020 definition.callAsFunction = &ffi_callAsFunction;
1021 Functor_ = JSClassCreate(&definition);
1022
1023 definition = kJSClassDefinitionEmpty;
1024 definition.className = "Selector";
1025 definition.parentClass = Pointer_;
1026 Selector_ = JSClassCreate(&definition);
1027
1028 definition = kJSClassDefinitionEmpty;
1029 definition.className = "Instance_";
1030 definition.getProperty = &Instance_getProperty;
1031 definition.callAsConstructor = &Instance_callAsConstructor;
1032 definition.finalize = &Instance_finalize;
1033 Instance_ = JSClassCreate(&definition);
1034
1035 definition = kJSClassDefinitionEmpty;
1036 definition.getProperty = &Global_getProperty;
1037 JSClassRef Global(JSClassCreate(&definition));
1038
1039 JSContextRef context(JSGlobalContextCreate(Global));
1040 Context_ = context;
1041
1042 JSObjectRef global(JSContextGetGlobalObject(context));
1043
1044 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
1045
1046 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYString("objc_msgSend"), &$objc_msgSend));
1047
1048 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcyrver.plist"] retain];
1049
1050 name_ = JSStringCreateWithUTF8CString("name");
1051 message_ = JSStringCreateWithUTF8CString("message");
1052 length_ = JSStringCreateWithUTF8CString("length");
1053
1054 JSValueRef exception(NULL);
1055 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYString("Array"), &exception));
1056 CYThrow(context, exception);
1057 Array_ = JSValueToObject(JSGetContext(), value, &exception);
1058 CYThrow(context, exception);
1059 }