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