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