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