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