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