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