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