]> git.saurik.com Git - cycript.git/blame - Library.mm
I finally finished the AST.
[cycript.git] / Library.mm
CommitLineData
62ca2b82 1/* Cyrker - Remove Execution Server and Disassembler
c1582939
JF
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
62ca2b82 5/* Modified BSD License {{{ */
c1582939
JF
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*/
62ca2b82 38/* }}} */
c1582939 39
8d9b5eed
JF
40#define _GNU_SOURCE
41
c1582939 42#include <substrate.h>
04450da0 43#include "Struct.hpp"
c1582939 44
ea2d184c
JF
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
c1582939
JF
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
8d9b5eed
JF
72#include <iostream>
73#include <ext/stdio_filebuf.h>
a2d9403c
JF
74#include <set>
75#include <map>
8d9b5eed 76
e5332278 77#include "Parser.hpp"
63b4c5a8 78#include "Cycript.tab.hh"
e5332278 79
ea2d184c
JF
80#undef _assert
81#undef _trace
82
c1582939 83#define _assert(test) do { \
f5e9be24
JF
84 if (!(test)) \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
c1582939
JF
86} while (false)
87
88#define _trace() do { \
62ca2b82 89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
90} while (false)
91
707bcb93 92/* APR Pool Helpers {{{ */
b21525c7
JF
93void *operator new(size_t size, apr_pool_t *pool) {
94 return apr_palloc(pool, size);
95}
96
97void *operator new [](size_t size, apr_pool_t *pool) {
98 return apr_palloc(pool, size);
99}
100
707bcb93
JF
101class 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 }
e5332278
JF
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 }
707bcb93
JF
125};
126/* }}} */
127
128#define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
129
ea2d184c
JF
130static JSContextRef Context_;
131
88c977fa
JF
132static JSClassRef Functor_;
133static JSClassRef Instance_;
134static JSClassRef Pointer_;
135static JSClassRef Selector_;
ea2d184c 136
c1582939 137static JSObjectRef Array_;
ea2d184c 138
62ca2b82
JF
139static JSStringRef name_;
140static JSStringRef message_;
c1582939 141static JSStringRef length_;
ea2d184c 142
c1582939
JF
143static Class NSCFBoolean_;
144
88c977fa
JF
145static NSMutableDictionary *Bridge_;
146
c1582939
JF
147struct Client {
148 CFHTTPMessageRef message_;
149 CFSocketRef socket_;
150};
151
0c862573 152JSObjectRef CYMakeObject(JSContextRef context, id object) {
88c977fa 153 return JSObjectMake(context, Instance_, [object retain]);
0c862573
JF
154}
155
107e3ed0 156@interface NSMethodSignature (Cycript)
7ba62cfd
JF
157- (NSString *) _typeString;
158@end
159
107e3ed0 160@interface NSObject (Cycript)
c1582939 161- (NSString *) cy$toJSON;
ea2d184c 162- (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
c1582939
JF
163@end
164
107e3ed0 165@interface NSString (Cycript)
88c977fa
JF
166- (void *) cy$symbol;
167@end
168
107e3ed0 169@interface NSNumber (Cycript)
88c977fa
JF
170- (void *) cy$symbol;
171@end
172
107e3ed0 173@implementation NSObject (Cycript)
62ca2b82 174
c1582939 175- (NSString *) cy$toJSON {
62ca2b82
JF
176 return [self description];
177}
178
ea2d184c 179- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
0c862573 180 return CYMakeObject(context, self);
ea2d184c
JF
181}
182
62ca2b82 183@end
c1582939 184
107e3ed0 185@implementation WebUndefined (Cycript)
62ca2b82 186
c1582939
JF
187- (NSString *) cy$toJSON {
188 return @"undefined";
62ca2b82
JF
189}
190
191- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
192 return JSValueMakeUndefined(context);
193}
194
195@end
c1582939 196
107e3ed0 197@implementation NSArray (Cycript)
62ca2b82 198
c1582939
JF
199- (NSString *) cy$toJSON {
200 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
201 [json appendString:@"["];
202
203 bool comma(false);
62ca2b82 204 for (id object in self) {
c1582939
JF
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;
62ca2b82
JF
214}
215
216@end
217
107e3ed0 218@implementation NSDictionary (Cycript)
62ca2b82
JF
219
220- (NSString *) cy$toJSON {
221 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
7ba62cfd
JF
222 [json appendString:@"("];
223 [json appendString:@"{"];
62ca2b82
JF
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
c1582939 242
107e3ed0 243@implementation NSNumber (Cycript)
62ca2b82 244
c1582939
JF
245- (NSString *) cy$toJSON {
246 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
247}
248
249- (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
250 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
251}
252
88c977fa
JF
253- (void *) cy$symbol {
254 return [self pointerValue];
255}
256
62ca2b82 257@end
c1582939 258
107e3ed0 259@implementation NSString (Cycript)
62ca2b82 260
c1582939
JF
261- (NSString *) cy$toJSON {
262 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
263
c1582939
JF
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
62ca2b82
JF
273 return [reinterpret_cast<const NSString *>(json) autorelease];
274}
275
88c977fa
JF
276- (void *) cy$symbol {
277 return dlsym(RTLD_DEFAULT, [self UTF8String]);
278}
279
62ca2b82
JF
280@end
281
b21525c7 282@interface CYJSObject : NSDictionary {
62ca2b82
JF
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
c1582939 296
b21525c7 297@interface CYJSArray : NSArray {
c1582939
JF
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
62ca2b82 309JSContextRef JSGetContext() {
ea2d184c 310 return Context_;
62ca2b82
JF
311}
312
0c862573
JF
313#define CYCatch \
314 @catch (id error) { \
315 CYThrow(context, error, exception); \
316 return NULL; \
317 }
318
ea2d184c
JF
319void CYThrow(JSContextRef context, JSValueRef value);
320
b21525c7 321id CYCastNSObject(JSContextRef context, JSObjectRef object) {
88c977fa 322 if (JSValueIsObjectOfClass(context, object, Instance_))
c1582939 323 return reinterpret_cast<id>(JSObjectGetPrivate(object));
ea2d184c
JF
324 JSValueRef exception(NULL);
325 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
326 CYThrow(context, exception);
327 if (array)
b21525c7
JF
328 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
329 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
62ca2b82
JF
330}
331
77e87a6c
JF
332JSStringRef CYCopyJSString(id value) {
333 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
62ca2b82
JF
334}
335
77e87a6c
JF
336JSStringRef CYCopyJSString(const char *value) {
337 return JSStringCreateWithUTF8CString(value);
338}
339
340JSStringRef CYCopyJSString(JSStringRef value) {
341 return JSStringRetain(value);
342}
343
344JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
62ca2b82 345 JSValueRef exception(NULL);
ea2d184c
JF
346 JSStringRef string(JSValueToStringCopy(context, value, &exception));
347 CYThrow(context, exception);
77e87a6c
JF
348 return string;
349}
350
351// XXX: this is not a safe handle
cf7d4c69 352class CYJSString {
77e87a6c
JF
353 private:
354 JSStringRef string_;
355
356 public:
357 template <typename Arg0_>
cf7d4c69 358 CYJSString(Arg0_ arg0) {
77e87a6c
JF
359 string_ = CYCopyJSString(arg0);
360 }
361
362 template <typename Arg0_, typename Arg1_>
cf7d4c69 363 CYJSString(Arg0_ arg0, Arg1_ arg1) {
77e87a6c
JF
364 string_ = CYCopyJSString(arg0, arg1);
365 }
366
cf7d4c69 367 ~CYJSString() {
77e87a6c
JF
368 JSStringRelease(string_);
369 }
370
371 operator JSStringRef() const {
372 return string_;
373 }
374};
375
376CFStringRef CYCopyCFString(JSStringRef value) {
377 return JSStringCopyCFString(kCFAllocatorDefault, value);
378}
379
380CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
cf7d4c69 381 return CYCopyCFString(CYJSString(context, value));
c1582939
JF
382}
383
f610e1a0 384double CYCastDouble(JSContextRef context, JSValueRef value) {
0c862573
JF
385 JSValueRef exception(NULL);
386 double number(JSValueToNumber(context, value, &exception));
387 CYThrow(context, exception);
f610e1a0
JF
388 return number;
389}
390
391CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
392 double number(CYCastDouble(context, value));
0c862573
JF
393 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
394}
395
62ca2b82
JF
396NSString *CYCastNSString(JSStringRef value) {
397 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
398}
399
ea2d184c 400CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
f610e1a0 401 switch (JSType type = JSValueGetType(context, value)) {
c1582939 402 case kJSTypeUndefined:
62ca2b82 403 return CFRetain([WebUndefined undefined]);
c1582939
JF
404 case kJSTypeNull:
405 return nil;
c1582939 406 case kJSTypeBoolean:
ea2d184c 407 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
0c862573
JF
408 case kJSTypeNumber:
409 return CYCopyCFNumber(context, value);
62ca2b82 410 case kJSTypeString:
ea2d184c 411 return CYCopyCFString(context, value);
c1582939 412 case kJSTypeObject:
b21525c7 413 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
c1582939 414 default:
f5e9be24 415 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
c1582939
JF
416 }
417}
418
62ca2b82
JF
419NSArray *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
ea2d184c
JF
427id CYCastNSObject(JSContextRef context, JSValueRef value) {
428 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
c1582939
JF
429 return object == nil ? nil : [object autorelease];
430}
431
ea2d184c 432void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
433 if (value == NULL)
434 return;
ea2d184c 435 @throw CYCastNSObject(context, value);
62ca2b82
JF
436}
437
ea2d184c
JF
438JSValueRef CYCastJSValue(JSContextRef context, id value) {
439 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
62ca2b82
JF
440}
441
7ba62cfd
JF
442void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
443 *exception = CYCastJSValue(context, error);
444}
445
b21525c7 446@implementation CYJSObject
62ca2b82
JF
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);
cf7d4c69 464 JSValueRef value(JSObjectGetProperty(context_, object_, CYJSString(key), &exception));
62ca2b82
JF
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);
cf7d4c69 478 JSObjectSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object), kJSPropertyAttributeNone, &exception);
62ca2b82
JF
479 CYThrow(context_, exception);
480}
481
482- (void) removeObjectForKey:(id)key {
483 JSValueRef exception(NULL);
f610e1a0 484 // XXX: this returns a bool... throw exception, or ignore?
cf7d4c69 485 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
62ca2b82
JF
486 CYThrow(context_, exception);
487}
488
489@end
490
b21525c7 491@implementation CYJSArray
c1582939
JF
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 {
62ca2b82
JF
501 JSValueRef exception(NULL);
502 JSValueRef value(JSObjectGetProperty(context_, object_, length_, &exception));
503 CYThrow(context_, exception);
f610e1a0 504 return CYCastDouble(context_, value);
c1582939
JF
505}
506
507- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
508 JSValueRef exception(NULL);
509 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
510 CYThrow(context_, exception);
511 id object(CYCastNSObject(context_, value));
c1582939
JF
512 return object == nil ? [NSNull null] : object;
513}
514
515@end
516
ea2d184c
JF
517CFStringRef JSValueToJSONCopy(JSContextRef context, JSValueRef value) {
518 id object(CYCastNSObject(context, value));
62ca2b82 519 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
c1582939
JF
520}
521
522static 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
62ca2b82 545 JSValueRef result(JSEvaluateScript(JSGetContext(), script, NULL, NULL, 0, NULL));
c1582939
JF
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
62ca2b82 551 CFStringRef json(JSValueToJSONCopy(JSGetContext(), result));
c1582939
JF
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
574static 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
f610e1a0
JF
595static 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
c1582939
JF
601}
602
ea2d184c
JF
603typedef id jocData;
604
88c977fa 605static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
0c862573
JF
606 @try {
607 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
608 return CYMakeObject(context, [[data alloc] autorelease]);
609 } CYCatch
610}
611
04450da0 612struct ptrData {
b21525c7 613 apr_pool_t *pool_;
04450da0 614 void *value_;
b21525c7 615 sig::Type type_;
77e87a6c
JF
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
631struct 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
643struct selData : ptrData {
644 selData(SEL value) :
645 ptrData(value)
646 {
647 }
04450da0
JF
648};
649
88c977fa 650static void Pointer_finalize(JSObjectRef object) {
04450da0 651 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
b21525c7 652 apr_pool_destroy(data->pool_);
04450da0
JF
653}
654
88c977fa 655static void Instance_finalize(JSObjectRef object) {
ea2d184c
JF
656 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
657 [data release];
658}
659
88c977fa
JF
660JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
661 ffiData *data(new ffiData(function, type));
662 return JSObjectMake(context, Functor_, data);
663}
664
665
666JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
667 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
668}
669
ea2d184c
JF
670void CYSetProperty(JSContextRef context, JSObjectRef object, const char *name, JSValueRef value) {
671 JSValueRef exception(NULL);
cf7d4c69 672 JSObjectSetProperty(context, object, CYJSString(name), value, kJSPropertyAttributeNone, &exception);
ea2d184c
JF
673 CYThrow(context, exception);
674}
675
7ba62cfd
JF
676char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
677 size_t size(JSStringGetMaximumUTF8CStringSize(value));
b21525c7 678 char *string(new(pool) char[size]);
7ba62cfd
JF
679 JSStringGetUTF8CString(value, string, size);
680 JSStringRelease(value);
681 return string;
682}
683
77e87a6c 684char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
cf7d4c69 685 return CYPoolCString(pool, CYJSString(context, value));
77e87a6c
JF
686}
687
f610e1a0 688// XXX: this macro is unhygenic
b21525c7
JF
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
7ba62cfd
JF
700SEL CYCastSEL(JSContextRef context, JSValueRef value) {
701 if (JSValueIsNull(context, value))
702 return NULL;
88c977fa 703 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
77e87a6c
JF
704 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
705 return reinterpret_cast<SEL>(data->value_);
706 } else
b21525c7
JF
707 return sel_registerName(CYCastCString(context, value));
708}
709
710void *CYCastPointer(JSContextRef context, JSValueRef value) {
711 switch (JSValueGetType(context, value)) {
712 case kJSTypeNull:
713 return NULL;
b21525c7
JF
714 case kJSTypeString:
715 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
b21525c7 716 case kJSTypeObject:
88c977fa 717 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
b21525c7
JF
718 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
719 return data->value_;
720 }
721 default:
f610e1a0 722 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
7ba62cfd
JF
723 }
724}
725
43cb3d68 726void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
ea2d184c
JF
727 switch (type->primitive) {
728 case sig::boolean_P:
729 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
730 break;
731
43cb3d68 732#define CYPoolFFI_(primitive, native) \
f610e1a0
JF
733 case sig::primitive ## _P: \
734 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
735 break;
ea2d184c 736
43cb3d68
JF
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)
ea2d184c
JF
749
750 case sig::object_P:
751 case sig::typename_P:
7ba62cfd
JF
752 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
753 break;
754
ea2d184c 755 case sig::selector_P:
7ba62cfd
JF
756 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
757 break;
ea2d184c 758
b21525c7
JF
759 case sig::pointer_P:
760 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
761 break;
ea2d184c 762
77e87a6c
JF
763 case sig::string_P:
764 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
765 break;
7ba62cfd 766
ea2d184c
JF
767 case sig::struct_P:
768 goto fail;
769
770 case sig::void_P:
771 break;
772
773 default: fail:
43cb3d68 774 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
ea2d184c
JF
775 _assert(false);
776 }
777}
778
43cb3d68 779JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
ea2d184c
JF
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
7ba62cfd 810 case sig::selector_P: {
77e87a6c
JF
811 if (SEL sel = *reinterpret_cast<SEL *>(data)) {
812 selData *data(new selData(sel));
88c977fa 813 value = JSObjectMake(context, Selector_, data);
f610e1a0 814 } else goto null;
7ba62cfd
JF
815 } break;
816
817 case sig::pointer_P: {
04450da0 818 if (void *pointer = *reinterpret_cast<void **>(data)) {
77e87a6c 819 ptrData *data(new ptrData(pointer));
88c977fa 820 value = JSObjectMake(context, Pointer_, data);
f610e1a0 821 } else goto null;
7ba62cfd 822 } break;
ea2d184c
JF
823
824 case sig::string_P: {
f610e1a0 825 if (char *utf8 = *reinterpret_cast<char **>(data))
cf7d4c69 826 value = JSValueMakeString(context, CYJSString(utf8));
f610e1a0 827 else goto null;
ea2d184c
JF
828 } break;
829
830 case sig::struct_P:
831 goto fail;
832
833 case sig::void_P:
f610e1a0
JF
834 value = JSValueMakeUndefined(context);
835 break;
836
837 null:
838 value = JSValueMakeNull(context);
ea2d184c
JF
839 break;
840
841 default: fail:
842 NSLog(@"CYFromFFI(%c)\n", type->primitive);
843 _assert(false);
844 }
845
846 return value;
847}
848
0c862573 849static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
7ba62cfd 850 @try {
85a33bf5 851 if (count != signature->count - 1)
f5e9be24 852 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
85a33bf5 853
7ba62cfd
JF
854 CYPool pool;
855 void *values[count];
ea2d184c 856
7ba62cfd
JF
857 for (unsigned index(0); index != count; ++index) {
858 sig::Element *element(&signature->elements[index + 1]);
77e87a6c 859 // XXX: alignment?
b21525c7 860 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
43cb3d68 861 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
7ba62cfd 862 }
ea2d184c 863
7ba62cfd
JF
864 uint8_t value[cif->rtype->size];
865 ffi_call(cif, function, value, values);
866
43cb3d68 867 return CYFromFFI(context, signature->elements[0].type, value);
0c862573 868 } CYCatch
7ba62cfd 869}
ea2d184c 870
f610e1a0 871static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
707bcb93 872 @try {
f610e1a0
JF
873 NSString *name(CYCastNSString(property));
874 if (Class _class = NSClassFromString(name))
707bcb93 875 return CYMakeObject(context, _class);
f610e1a0 876 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
707bcb93
JF
877 switch ([[entry objectAtIndex:0] intValue]) {
878 case 0:
cf7d4c69 879 return JSEvaluateScript(JSGetContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
707bcb93 880 case 1:
f610e1a0 881 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
707bcb93
JF
882 case 2:
883 CYPool pool;
884 sig::Signature signature;
885 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
f610e1a0 886 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
707bcb93
JF
887 }
888 return NULL;
889 } CYCatch
890}
891
04450da0
JF
892bool 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
7ba62cfd 899static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
7ba62cfd 900 const char *type;
ea2d184c
JF
901
902 @try {
85a33bf5 903 if (count < 2)
f5e9be24 904 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
85a33bf5 905
7ba62cfd
JF
906 id self(CYCastNSObject(context, arguments[0]));
907 if (self == nil)
908 return JSValueMakeNull(context);
7ba62cfd 909
85a33bf5 910 SEL _cmd(CYCastSEL(context, arguments[1]));
7ba62cfd 911 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
85a33bf5 912 if (method == nil)
f5e9be24 913 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
7ba62cfd
JF
914
915 type = [[method _typeString] UTF8String];
0c862573 916 } CYCatch
ea2d184c 917
7ba62cfd
JF
918 CYPool pool;
919
920 sig::Signature signature;
921 sig::Parse(pool, &signature, type);
ea2d184c 922
7ba62cfd 923 ffi_cif cif;
b21525c7 924 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
7ba62cfd 925
04450da0 926 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
7ba62cfd
JF
927 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
928}
929
930static 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)));
77e87a6c 932 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
ea2d184c
JF
933}
934
b21525c7
JF
935JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
936 @try {
937 if (count != 2)
f5e9be24 938 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi constructor" userInfo:nil];
88c977fa 939 void *function(CYCastPointer(context, arguments[0]));
b21525c7
JF
940 const char *type(CYCastCString(context, arguments[1]));
941 return CYMakeFunction(context, function, type);
0c862573 942 } CYCatch
ea2d184c
JF
943}
944
f610e1a0 945JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
04450da0
JF
946 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
947 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
948}
949
88c977fa
JF
950static JSStaticValue Pointer_staticValues[2] = {
951 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
952 {NULL, NULL, NULL, 0}
953};
954
924f67b2
JF
955CYParser::CYParser() {
956 ScannerInit();
957}
958
959CYParser::~CYParser() {
960 ScannerDestroy();
961}
962
e5332278 963extern int cydebug;
1431b560 964
63b4c5a8
JF
965void cy::parser::error(const cy::parser::location_type &loc, const std::string &msg) {
966 std::cerr << loc << ": " << msg << std::endl;
967}
968
8d9b5eed 969void CYConsole(FILE *fin, FILE *fout, FILE *ferr) {
e5332278 970 cydebug = 1;
924f67b2
JF
971 CYParser driver;
972 cy::parser parser(&driver);
63b4c5a8 973 parser.parse();
8d9b5eed
JF
974}
975
7ba62cfd 976MSInitialize { _pooled
ea2d184c
JF
977 apr_initialize();
978
c1582939
JF
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;
88c977fa
JF
1003 definition.className = "Pointer";
1004 definition.staticValues = Pointer_staticValues;
1005 definition.finalize = &Pointer_finalize;
1006 Pointer_ = JSClassCreate(&definition);
c1582939
JF
1007
1008 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1009 definition.className = "Functor";
1010 definition.parentClass = Pointer_;
1011 definition.callAsFunction = &ffi_callAsFunction;
1012 Functor_ = JSClassCreate(&definition);
7ba62cfd 1013
77e87a6c 1014 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1015 definition.className = "Selector";
1016 definition.parentClass = Pointer_;
1017 Selector_ = JSClassCreate(&definition);
77e87a6c 1018
7ba62cfd 1019 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1020 definition.className = "Instance_";
1021 definition.getProperty = &Instance_getProperty;
1022 definition.callAsConstructor = &Instance_callAsConstructor;
1023 definition.finalize = &Instance_finalize;
1024 Instance_ = JSClassCreate(&definition);
7ba62cfd
JF
1025
1026 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1027 definition.getProperty = &Global_getProperty;
1028 JSClassRef Global(JSClassCreate(&definition));
c1582939 1029
88c977fa 1030 JSContextRef context(JSGlobalContextCreate(Global));
ea2d184c
JF
1031 Context_ = context;
1032
1033 JSObjectRef global(JSContextGetGlobalObject(context));
c1582939 1034
88c977fa 1035 CYSetProperty(context, global, "ffi", JSObjectMakeConstructor(context, Functor_, &ffi));
7ba62cfd 1036
cf7d4c69 1037 CYSetProperty(context, global, "objc_msgSend", JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
7ba62cfd 1038
107e3ed0 1039 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
c1582939 1040
62ca2b82
JF
1041 name_ = JSStringCreateWithUTF8CString("name");
1042 message_ = JSStringCreateWithUTF8CString("message");
c1582939
JF
1043 length_ = JSStringCreateWithUTF8CString("length");
1044
62ca2b82 1045 JSValueRef exception(NULL);
cf7d4c69 1046 JSValueRef value(JSObjectGetProperty(JSGetContext(), global, CYJSString("Array"), &exception));
ea2d184c 1047 CYThrow(context, exception);
62ca2b82 1048 Array_ = JSValueToObject(JSGetContext(), value, &exception);
ea2d184c 1049 CYThrow(context, exception);
c1582939 1050}