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