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