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