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