]> git.saurik.com Git - cycript.git/blame - Library.mm
Added support for array and dictionary property access.
[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>
30ddc20c 43#include "cycript.hpp"
c1582939 44
ea2d184c
JF
45#include "sig/parse.hpp"
46#include "sig/ffi_type.hpp"
47
5999c315 48#include "Pooling.hpp"
057f943f 49#include "Struct.hpp"
ea2d184c 50
c1582939
JF
51#include <unistd.h>
52
53#include <CoreFoundation/CoreFoundation.h>
54#include <CoreFoundation/CFLogUtilities.h>
55
56#include <CFNetwork/CFNetwork.h>
c1582939
JF
57
58#include <WebKit/WebScriptObject.h>
59
60#include <sys/types.h>
61#include <sys/socket.h>
62#include <netinet/in.h>
b09da87b 63#include <sys/mman.h>
c1582939 64
8d9b5eed
JF
65#include <iostream>
66#include <ext/stdio_filebuf.h>
a2d9403c
JF
67#include <set>
68#include <map>
8d9b5eed 69
e5332278 70#include "Parser.hpp"
63b4c5a8 71#include "Cycript.tab.hh"
e5332278 72
ea2d184c
JF
73#undef _assert
74#undef _trace
75
c1582939 76#define _assert(test) do { \
f5e9be24
JF
77 if (!(test)) \
78 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
c1582939
JF
79} while (false)
80
81#define _trace() do { \
62ca2b82 82 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
c1582939
JF
83} while (false)
84
4cf49641
JF
85#define CYPoolTry { \
86 id _saved(nil); \
87 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
88 @try
89#define CYPoolCatch(value) \
90 @catch (NSException *error) { \
91 _saved = [error retain]; \
92 @throw; \
93 return value; \
94 } @finally { \
95 [_pool release]; \
96 if (_saved != nil) \
97 [_saved autorelease]; \
98 } \
99}
100
478d4ed0 101static JSGlobalContextRef Context_;
b09da87b 102static JSObjectRef System_;
ea2d184c 103
88c977fa
JF
104static JSClassRef Functor_;
105static JSClassRef Instance_;
106static JSClassRef Pointer_;
107static JSClassRef Selector_;
ea2d184c 108
c1582939 109static JSObjectRef Array_;
dea834b0 110static JSObjectRef Function_;
ea2d184c 111
62ca2b82
JF
112static JSStringRef name_;
113static JSStringRef message_;
c1582939 114static JSStringRef length_;
ea2d184c 115
c1582939
JF
116static Class NSCFBoolean_;
117
88c977fa
JF
118static NSMutableDictionary *Bridge_;
119
c1582939
JF
120struct Client {
121 CFHTTPMessageRef message_;
122 CFSocketRef socket_;
123};
124
478d4ed0
JF
125struct ptrData {
126 apr_pool_t *pool_;
127 void *value_;
128 sig::Type type_;
129
130 void *operator new(size_t size) {
131 apr_pool_t *pool;
132 apr_pool_create(&pool, NULL);
133 void *data(apr_palloc(pool, size));
134 reinterpret_cast<ptrData *>(data)->pool_ = pool;
135 return data;;
136 }
137
138 ptrData(void *value) :
139 value_(value)
140 {
141 }
142
143 virtual ~ptrData() {
144 }
145};
146
147struct ffiData : ptrData {
148 sig::Signature signature_;
149 ffi_cif cif_;
150
151 ffiData(const char *type, void (*value)()) :
152 ptrData(reinterpret_cast<void *>(value))
153 {
154 sig::Parse(pool_, &signature_, type);
155 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
156 }
157};
158
159struct ffoData : ffiData {
160 JSContextRef context_;
161 JSObjectRef function_;
162
163 ffoData(const char *type) :
164 ffiData(type, NULL)
165 {
166 }
167};
168
169struct selData : ptrData {
170 selData(SEL value) :
171 ptrData(value)
172 {
173 }
174
175 SEL GetValue() const {
176 return reinterpret_cast<SEL>(value_);
177 }
178};
179
180struct jocData : ptrData {
181 bool transient_;
182
183 jocData(id value, bool transient) :
184 ptrData(value)
185 {
186 }
187
188 virtual ~jocData() {
189 if (!transient_)
190 [GetValue() release];
191 }
192
193 id GetValue() const {
194 return reinterpret_cast<id>(value_);
195 }
196};
197
4cf49641 198JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
478d4ed0
JF
199 if (!transient)
200 object = [object retain];
201 jocData *data(new jocData(object, transient));
202 return JSObjectMake(context, Instance_, data);
203}
204
205const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
206 if (pool == NULL)
207 return [value UTF8String];
208 else {
209 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
210 char *string(new(pool) char[size]);
211 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
212 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
213 return string;
214 }
b09da87b
JF
215}
216
217JSValueRef CYCastJSValue(JSContextRef context, bool value) {
218 return JSValueMakeBoolean(context, value);
219}
220
221JSValueRef CYCastJSValue(JSContextRef context, double value) {
222 return JSValueMakeNumber(context, value);
223}
224
225#define CYCastJSValue_(Type_) \
226 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
227 return JSValueMakeNumber(context, static_cast<double>(value)); \
228 }
229
230CYCastJSValue_(int)
231CYCastJSValue_(unsigned int)
232CYCastJSValue_(long int)
233CYCastJSValue_(long unsigned int)
234CYCastJSValue_(long long int)
235CYCastJSValue_(long long unsigned int)
236
237JSValueRef CYJSUndefined(JSContextRef context) {
238 return JSValueMakeUndefined(context);
0c862573
JF
239}
240
107e3ed0 241@interface NSMethodSignature (Cycript)
7ba62cfd
JF
242- (NSString *) _typeString;
243@end
244
107e3ed0 245@interface NSObject (Cycript)
6b8a9500 246- (bool) cy$isUndefined;
c1582939 247- (NSString *) cy$toJSON;
4cf49641 248- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
cc103044
JF
249- (NSObject *) cy$getProperty:(NSString *)name;
250- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
251- (bool) cy$deleteProperty:(NSString *)name;
c1582939
JF
252@end
253
107e3ed0 254@interface NSString (Cycript)
88c977fa
JF
255- (void *) cy$symbol;
256@end
257
107e3ed0 258@interface NSNumber (Cycript)
88c977fa
JF
259- (void *) cy$symbol;
260@end
261
107e3ed0 262@implementation NSObject (Cycript)
62ca2b82 263
6b8a9500
JF
264- (bool) cy$isUndefined {
265 return false;
266}
267
c1582939 268- (NSString *) cy$toJSON {
62ca2b82
JF
269 return [self description];
270}
271
4cf49641
JF
272- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
273 return CYMakeInstance(context, self, transient);
ea2d184c
JF
274}
275
cc103044
JF
276- (NSObject *) cy$getProperty:(NSString *)name {
277 NSLog(@"get:%@", name);
278 return nil;
279}
280
281- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
282 NSLog(@"set:%@", name);
283 return false;
284}
285
286- (bool) cy$deleteProperty:(NSString *)name {
287 NSLog(@"delete:%@", name);
288 return false;
289}
290
62ca2b82 291@end
c1582939 292
107e3ed0 293@implementation WebUndefined (Cycript)
62ca2b82 294
6b8a9500
JF
295- (bool) cy$isUndefined {
296 return true;
297}
298
c1582939
JF
299- (NSString *) cy$toJSON {
300 return @"undefined";
62ca2b82
JF
301}
302
4cf49641 303- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
b09da87b 304 return CYJSUndefined(context);
62ca2b82
JF
305}
306
307@end
c1582939 308
478d4ed0
JF
309@implementation NSNull (Cycript)
310
311- (NSString *) cy$toJSON {
312 return @"null";
313}
314
315@end
316
107e3ed0 317@implementation NSArray (Cycript)
62ca2b82 318
c1582939
JF
319- (NSString *) cy$toJSON {
320 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
321 [json appendString:@"["];
322
323 bool comma(false);
62ca2b82 324 for (id object in self) {
c1582939
JF
325 if (comma)
326 [json appendString:@","];
327 else
328 comma = true;
6b8a9500
JF
329 if (![object cy$isUndefined])
330 [json appendString:[object cy$toJSON]];
331 else {
332 [json appendString:@","];
333 comma = false;
334 }
c1582939
JF
335 }
336
337 [json appendString:@"]"];
338 return json;
62ca2b82
JF
339}
340
cc103044
JF
341- (NSObject *) cy$getProperty:(NSString *)name {
342 int index([name intValue]);
343 if (index < 0 || index >= static_cast<int>([self count]))
344 return [super cy$getProperty:name];
345 else
346 return [self objectAtIndex:index];
347}
348
349@end
350
351@implementation NSMutableArray (Cycript)
352
353- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
354 int index([name intValue]);
355 if (index < 0 || index >= static_cast<int>([self count]))
356 return [super cy$setProperty:name to:value];
357 else {
358 [self replaceObjectAtIndex:index withObject:value];
359 return true;
360 }
361}
362
363- (bool) cy$deleteProperty:(NSString *)name {
364 int index([name intValue]);
365 if (index < 0 || index >= static_cast<int>([self count]))
366 return [super cy$deleteProperty:name];
367 else {
368 [self removeObjectAtIndex:index];
369 return true;
370 }
371}
372
62ca2b82
JF
373@end
374
107e3ed0 375@implementation NSDictionary (Cycript)
62ca2b82
JF
376
377- (NSString *) cy$toJSON {
378 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
d35a3b07 379 [json appendString:@"({"];
62ca2b82
JF
380
381 bool comma(false);
382 for (id key in self) {
383 if (comma)
384 [json appendString:@","];
385 else
386 comma = true;
387 [json appendString:[key cy$toJSON]];
388 [json appendString:@":"];
389 NSObject *object([self objectForKey:key]);
390 [json appendString:[object cy$toJSON]];
391 }
392
393 [json appendString:@"})"];
394 return json;
395}
396
cc103044
JF
397- (NSObject *) cy$getProperty:(NSString *)name {
398 return [self objectForKey:name];
399}
400
401@end
402
403@implementation NSMutableDictionary (Cycript)
404
405- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
406 [self setObject:value forKey:name];
407 return true;
408}
409
410- (bool) cy$deleteProperty:(NSString *)name {
411 if ([self objectForKey:name] == nil)
412 return false;
413 else {
414 [self removeObjectForKey:name];
415 return true;
416 }
417}
418
62ca2b82 419@end
c1582939 420
107e3ed0 421@implementation NSNumber (Cycript)
62ca2b82 422
c1582939
JF
423- (NSString *) cy$toJSON {
424 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
62ca2b82
JF
425}
426
4cf49641 427- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
b09da87b 428 return [self class] != NSCFBoolean_ ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
62ca2b82
JF
429}
430
88c977fa
JF
431- (void *) cy$symbol {
432 return [self pointerValue];
433}
434
62ca2b82 435@end
c1582939 436
107e3ed0 437@implementation NSString (Cycript)
62ca2b82 438
c1582939
JF
439- (NSString *) cy$toJSON {
440 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
441
c1582939
JF
442 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
443 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
444 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
445 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
446 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
447
448 CFStringInsert(json, 0, CFSTR("\""));
449 CFStringAppend(json, CFSTR("\""));
450
62ca2b82
JF
451 return [reinterpret_cast<const NSString *>(json) autorelease];
452}
453
88c977fa 454- (void *) cy$symbol {
478d4ed0
JF
455 CYPool pool;
456 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
88c977fa
JF
457}
458
62ca2b82
JF
459@end
460
b21525c7 461@interface CYJSObject : NSDictionary {
62ca2b82
JF
462 JSObjectRef object_;
463 JSContextRef context_;
464}
465
466- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
467
468- (NSUInteger) count;
469- (id) objectForKey:(id)key;
470- (NSEnumerator *) keyEnumerator;
471- (void) setObject:(id)object forKey:(id)key;
472- (void) removeObjectForKey:(id)key;
473
474@end
c1582939 475
b21525c7 476@interface CYJSArray : NSArray {
c1582939
JF
477 JSObjectRef object_;
478 JSContextRef context_;
479}
480
481- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
482
483- (NSUInteger) count;
484- (id) objectAtIndex:(NSUInteger)index;
485
486@end
487
dea834b0
JF
488CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
489CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
490
478d4ed0 491JSGlobalContextRef CYGetJSContext() {
ea2d184c 492 return Context_;
62ca2b82
JF
493}
494
4cf49641
JF
495#define CYTry \
496 @try
0c862573
JF
497#define CYCatch \
498 @catch (id error) { \
b09da87b 499 NSLog(@"e:%@", error); \
0c862573
JF
500 CYThrow(context, error, exception); \
501 return NULL; \
502 }
503
ea2d184c
JF
504void CYThrow(JSContextRef context, JSValueRef value);
505
b09da87b
JF
506apr_status_t CYPoolRelease_(void *data) {
507 id object(reinterpret_cast<id>(data));
508 [object release];
509 return APR_SUCCESS;
510}
511
512id CYPoolRelease(apr_pool_t *pool, id object) {
513 if (pool == NULL)
514 return [object autorelease];
515 else {
516 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
517 return object;
518 }
519}
520
521id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
478d4ed0
JF
522 if (JSValueIsObjectOfClass(context, object, Instance_)) {
523 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(object)));
524 return data->GetValue();
525 }
526
ea2d184c
JF
527 JSValueRef exception(NULL);
528 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
529 CYThrow(context, exception);
b09da87b
JF
530 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
531 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
62ca2b82
JF
532}
533
77e87a6c 534JSStringRef CYCopyJSString(id value) {
b09da87b 535 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
62ca2b82
JF
536}
537
77e87a6c 538JSStringRef CYCopyJSString(const char *value) {
b09da87b 539 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
77e87a6c
JF
540}
541
542JSStringRef CYCopyJSString(JSStringRef value) {
b09da87b 543 return value == NULL ? NULL : JSStringRetain(value);
77e87a6c
JF
544}
545
546JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
b09da87b
JF
547 if (JSValueIsNull(context, value))
548 return NULL;
62ca2b82 549 JSValueRef exception(NULL);
ea2d184c
JF
550 JSStringRef string(JSValueToStringCopy(context, value, &exception));
551 CYThrow(context, exception);
77e87a6c
JF
552 return string;
553}
554
cf7d4c69 555class CYJSString {
77e87a6c
JF
556 private:
557 JSStringRef string_;
558
b09da87b
JF
559 void Clear_() {
560 JSStringRelease(string_);
561 }
562
77e87a6c 563 public:
b09da87b
JF
564 CYJSString(const CYJSString &rhs) :
565 string_(CYCopyJSString(rhs.string_))
566 {
567 }
568
77e87a6c 569 template <typename Arg0_>
b09da87b
JF
570 CYJSString(Arg0_ arg0) :
571 string_(CYCopyJSString(arg0))
572 {
77e87a6c
JF
573 }
574
575 template <typename Arg0_, typename Arg1_>
b09da87b
JF
576 CYJSString(Arg0_ arg0, Arg1_ arg1) :
577 string_(CYCopyJSString(arg0, arg1))
578 {
579 }
580
581 CYJSString &operator =(const CYJSString &rhs) {
582 Clear_();
583 string_ = CYCopyJSString(rhs.string_);
584 return *this;
77e87a6c
JF
585 }
586
cf7d4c69 587 ~CYJSString() {
b09da87b
JF
588 Clear_();
589 }
590
591 void Clear() {
592 Clear_();
593 string_ = NULL;
77e87a6c
JF
594 }
595
596 operator JSStringRef() const {
597 return string_;
598 }
599};
600
601CFStringRef CYCopyCFString(JSStringRef value) {
602 return JSStringCopyCFString(kCFAllocatorDefault, value);
603}
604
605CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
cf7d4c69 606 return CYCopyCFString(CYJSString(context, value));
c1582939
JF
607}
608
f610e1a0 609double CYCastDouble(JSContextRef context, JSValueRef value) {
0c862573
JF
610 JSValueRef exception(NULL);
611 double number(JSValueToNumber(context, value, &exception));
612 CYThrow(context, exception);
f610e1a0
JF
613 return number;
614}
615
616CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
617 double number(CYCastDouble(context, value));
0c862573
JF
618 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
619}
620
b09da87b
JF
621NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
622 return CYPoolRelease(pool, reinterpret_cast<const NSString *>(CYCopyCFString(value)));
623}
624
625bool CYCastBool(JSContextRef context, JSValueRef value) {
626 return JSValueToBoolean(context, value);
62ca2b82
JF
627}
628
b09da87b
JF
629CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
630 CFTypeRef object;
631 bool copy;
632
f610e1a0 633 switch (JSType type = JSValueGetType(context, value)) {
c1582939 634 case kJSTypeUndefined:
b09da87b
JF
635 object = [WebUndefined undefined];
636 copy = false;
637 break;
638
c1582939 639 case kJSTypeNull:
b09da87b
JF
640 return NULL;
641 break;
642
c1582939 643 case kJSTypeBoolean:
b09da87b
JF
644 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
645 copy = false;
646 break;
647
0c862573 648 case kJSTypeNumber:
b09da87b
JF
649 object = CYCopyCFNumber(context, value);
650 copy = true;
651 break;
652
62ca2b82 653 case kJSTypeString:
b09da87b
JF
654 object = CYCopyCFString(context, value);
655 copy = true;
656 break;
657
c1582939 658 case kJSTypeObject:
b09da87b
JF
659 // XXX: this might could be more efficient
660 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
661 copy = false;
662 break;
663
c1582939 664 default:
f5e9be24 665 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
b09da87b 666 break;
c1582939 667 }
b09da87b
JF
668
669 if (cast != copy)
670 return object;
671 else if (copy)
672 return CYPoolRelease(pool, (id) object);
673 else
674 return CFRetain(object);
675}
676
677CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
678 return CYCFType(pool, context, value, true);
679}
680
681CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
682 return CYCFType(pool, context, value, false);
c1582939
JF
683}
684
62ca2b82 685NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
b09da87b 686 CYPool pool;
62ca2b82
JF
687 size_t size(JSPropertyNameArrayGetCount(names));
688 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
689 for (size_t index(0); index != size; ++index)
b09da87b 690 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
62ca2b82
JF
691 return array;
692}
693
b09da87b
JF
694id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
695 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
c1582939
JF
696}
697
ea2d184c 698void CYThrow(JSContextRef context, JSValueRef value) {
62ca2b82
JF
699 if (value == NULL)
700 return;
b09da87b
JF
701 @throw CYCastNSObject(NULL, context, value);
702}
703
704JSValueRef CYJSNull(JSContextRef context) {
705 return JSValueMakeNull(context);
706}
707
708JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
709 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
710}
711
712JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
713 return CYCastJSValue(context, CYJSString(value));
62ca2b82
JF
714}
715
4cf49641
JF
716JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
717 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
62ca2b82
JF
718}
719
dea834b0
JF
720JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
721 JSValueRef exception(NULL);
722 JSObjectRef object(JSValueToObject(context, value, &exception));
723 CYThrow(context, exception);
724 return object;
725}
726
727JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
728 JSValueRef exception(NULL);
729 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
730 CYThrow(context, exception);
731 return value;
732}
733
734void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
735 JSValueRef exception(NULL);
736 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
737 CYThrow(context, exception);
738}
739
30ddc20c 740void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
4cf49641
JF
741 if (exception == NULL)
742 throw error;
7ba62cfd
JF
743 *exception = CYCastJSValue(context, error);
744}
745
b21525c7 746@implementation CYJSObject
62ca2b82
JF
747
748- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
749 if ((self = [super init]) != nil) {
750 object_ = object;
751 context_ = context;
752 } return self;
753}
754
755- (NSUInteger) count {
756 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
757 size_t size(JSPropertyNameArrayGetCount(names));
758 JSPropertyNameArrayRelease(names);
759 return size;
760}
761
762- (id) objectForKey:(id)key {
478d4ed0 763 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
62ca2b82
JF
764}
765
766- (NSEnumerator *) keyEnumerator {
767 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
768 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
769 JSPropertyNameArrayRelease(names);
770 return enumerator;
771}
772
773- (void) setObject:(id)object forKey:(id)key {
dea834b0 774 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
62ca2b82
JF
775}
776
777- (void) removeObjectForKey:(id)key {
778 JSValueRef exception(NULL);
f610e1a0 779 // XXX: this returns a bool... throw exception, or ignore?
cf7d4c69 780 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
62ca2b82
JF
781 CYThrow(context_, exception);
782}
783
784@end
785
b21525c7 786@implementation CYJSArray
c1582939
JF
787
788- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
789 if ((self = [super init]) != nil) {
790 object_ = object;
791 context_ = context;
792 } return self;
793}
794
795- (NSUInteger) count {
dea834b0 796 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
c1582939
JF
797}
798
799- (id) objectAtIndex:(NSUInteger)index {
62ca2b82
JF
800 JSValueRef exception(NULL);
801 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
802 CYThrow(context_, exception);
478d4ed0 803 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
c1582939
JF
804}
805
806@end
807
4cf49641
JF
808CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
809 CYTry {
810 CYPoolTry {
811 id object(CYCastNSObject(NULL, context, value));
812 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
813 } CYPoolCatch(NULL)
814 } CYCatch
c1582939
JF
815}
816
4cf49641
JF
817const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
818 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
819 const char *string(CYPoolCString(pool, json));
820 [json release];
821 return string;
822 } else return NULL;
478d4ed0
JF
823}
824
c1582939
JF
825static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
826 switch (type) {
827 case kCFSocketDataCallBack:
828 CFDataRef data(reinterpret_cast<CFDataRef>(value));
829 Client *client(reinterpret_cast<Client *>(info));
830
831 if (client->message_ == NULL)
832 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
833
834 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
835 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
836 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
837 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
838 Boolean absolute;
839 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
840 CFRelease(client->message_);
841
842 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
843 CFRelease(path);
844
845 JSStringRef script(JSStringCreateWithCFString(code));
846 CFRelease(code);
847
057f943f 848 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
c1582939
JF
849 JSStringRelease(script);
850
851 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
852 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
853
4cf49641 854 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
c1582939
JF
855 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
856 CFRelease(json);
857
858 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
859 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
860 CFRelease(length);
861
862 CFHTTPMessageSetBody(response, body);
863 CFRelease(body);
864
865 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
866 CFRelease(response);
867
868 CFSocketSendData(socket, NULL, serialized, 0);
869 CFRelease(serialized);
870
871 CFRelease(url);
872 }
873 break;
874 }
875}
876
877static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
878 switch (type) {
879 case kCFSocketAcceptCallBack:
880 Client *client(new Client());
881
882 client->message_ = NULL;
883
884 CFSocketContext context;
885 context.version = 0;
886 context.info = client;
887 context.retain = NULL;
888 context.release = NULL;
889 context.copyDescription = NULL;
890
891 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
892
893 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
894 break;
895 }
896}
897
b09da87b 898static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 899 CYTry {
b09da87b 900 CYPool pool;
cc103044 901 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 902 NSString *name(CYCastNSString(pool, property));
cc103044
JF
903 NSObject *data([self cy$getProperty:name]);
904 return data == nil ? NULL : CYCastJSValue(context, data);
f610e1a0 905 } CYCatch
c1582939
JF
906}
907
b09da87b 908static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
4cf49641 909 CYTry {
b09da87b 910 CYPool pool;
cc103044 911 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 912 NSString *name(CYCastNSString(pool, property));
cc103044
JF
913 NSString *data(CYCastNSObject(pool, context, value));
914 return [self cy$setProperty:name to:data];
b09da87b
JF
915 } CYCatch
916}
917
918static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 919 CYTry {
b09da87b 920 CYPool pool;
cc103044 921 NSString *self(CYCastNSObject(pool, context, object));
b09da87b 922 NSString *name(CYCastNSString(pool, property));
cc103044 923 return [self cy$deleteProperty:name];
b09da87b
JF
924 } CYCatch
925}
926
b09da87b 927static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 928 CYTry {
478d4ed0 929 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(object)));
4cf49641 930 return CYMakeInstance(context, [data->GetValue() alloc], true);
0c862573
JF
931 } CYCatch
932}
933
dea834b0
JF
934JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
935 selData *data(new selData(sel));
936 return JSObjectMake(context, Selector_, data);
937}
938
939JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
940 ptrData *data(new ptrData(pointer));
941 return JSObjectMake(context, Pointer_, data);
942}
943
88c977fa 944static void Pointer_finalize(JSObjectRef object) {
04450da0 945 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
478d4ed0 946 data->~ptrData();
b21525c7 947 apr_pool_destroy(data->pool_);
04450da0
JF
948}
949
b09da87b
JF
950JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
951 ffiData *data(new ffiData(type, function));
88c977fa
JF
952 return JSObjectMake(context, Functor_, data);
953}
954
478d4ed0
JF
955const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
956 if (pool == NULL)
957 return [CYCastNSString(NULL, value) UTF8String];
958 else {
959 size_t size(JSStringGetMaximumUTF8CStringSize(value));
960 char *string(new(pool) char[size]);
961 JSStringGetUTF8CString(value, string, size);
962 return string;
963 }
7ba62cfd
JF
964}
965
478d4ed0 966const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
b09da87b
JF
967 if (JSValueIsNull(context, value))
968 return NULL;
cf7d4c69 969 return CYPoolCString(pool, CYJSString(context, value));
77e87a6c
JF
970}
971
f610e1a0 972// XXX: this macro is unhygenic
b21525c7 973#define CYCastCString(context, value) ({ \
b09da87b
JF
974 char *utf8; \
975 if (value == NULL) \
976 utf8 = NULL; \
478d4ed0 977 else if (JSStringRef string = CYCopyJSString(context, value)) { \
b09da87b
JF
978 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
979 utf8 = reinterpret_cast<char *>(alloca(size)); \
980 JSStringGetUTF8CString(string, utf8, size); \
981 JSStringRelease(string); \
478d4ed0
JF
982 } else \
983 utf8 = NULL; \
b21525c7
JF
984 utf8; \
985})
986
7ba62cfd
JF
987SEL CYCastSEL(JSContextRef context, JSValueRef value) {
988 if (JSValueIsNull(context, value))
989 return NULL;
88c977fa 990 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
77e87a6c
JF
991 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
992 return reinterpret_cast<SEL>(data->value_);
993 } else
b21525c7
JF
994 return sel_registerName(CYCastCString(context, value));
995}
996
b09da87b 997void *CYCastPointer_(JSContextRef context, JSValueRef value) {
b21525c7
JF
998 switch (JSValueGetType(context, value)) {
999 case kJSTypeNull:
1000 return NULL;
b21525c7
JF
1001 case kJSTypeString:
1002 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
b21525c7 1003 case kJSTypeObject:
88c977fa 1004 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
b21525c7
JF
1005 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
1006 return data->value_;
1007 }
1008 default:
f610e1a0 1009 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
7ba62cfd
JF
1010 }
1011}
1012
b09da87b
JF
1013template <typename Type_>
1014_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1015 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1016}
1017
43cb3d68 1018void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
ea2d184c
JF
1019 switch (type->primitive) {
1020 case sig::boolean_P:
1021 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1022 break;
1023
43cb3d68 1024#define CYPoolFFI_(primitive, native) \
f610e1a0
JF
1025 case sig::primitive ## _P: \
1026 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1027 break;
ea2d184c 1028
43cb3d68
JF
1029 CYPoolFFI_(uchar, unsigned char)
1030 CYPoolFFI_(char, char)
1031 CYPoolFFI_(ushort, unsigned short)
1032 CYPoolFFI_(short, short)
1033 CYPoolFFI_(ulong, unsigned long)
1034 CYPoolFFI_(long, long)
1035 CYPoolFFI_(uint, unsigned int)
1036 CYPoolFFI_(int, int)
1037 CYPoolFFI_(ulonglong, unsigned long long)
1038 CYPoolFFI_(longlong, long long)
1039 CYPoolFFI_(float, float)
1040 CYPoolFFI_(double, double)
ea2d184c
JF
1041
1042 case sig::object_P:
1043 case sig::typename_P:
b09da87b 1044 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
7ba62cfd
JF
1045 break;
1046
ea2d184c 1047 case sig::selector_P:
7ba62cfd
JF
1048 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1049 break;
ea2d184c 1050
b21525c7 1051 case sig::pointer_P:
b09da87b 1052 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
b21525c7 1053 break;
ea2d184c 1054
77e87a6c 1055 case sig::string_P:
478d4ed0 1056 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
77e87a6c 1057 break;
7ba62cfd 1058
ea2d184c
JF
1059 case sig::struct_P:
1060 goto fail;
1061
1062 case sig::void_P:
1063 break;
1064
1065 default: fail:
43cb3d68 1066 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
ea2d184c
JF
1067 _assert(false);
1068 }
1069}
1070
43cb3d68 1071JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
ea2d184c
JF
1072 JSValueRef value;
1073
1074 switch (type->primitive) {
1075 case sig::boolean_P:
b09da87b 1076 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
ea2d184c
JF
1077 break;
1078
1079#define CYFromFFI_(primitive, native) \
1080 case sig::primitive ## _P: \
b09da87b 1081 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
ea2d184c
JF
1082 break;
1083
1084 CYFromFFI_(uchar, unsigned char)
1085 CYFromFFI_(char, char)
1086 CYFromFFI_(ushort, unsigned short)
1087 CYFromFFI_(short, short)
1088 CYFromFFI_(ulong, unsigned long)
1089 CYFromFFI_(long, long)
1090 CYFromFFI_(uint, unsigned int)
1091 CYFromFFI_(int, int)
1092 CYFromFFI_(ulonglong, unsigned long long)
1093 CYFromFFI_(longlong, long long)
1094 CYFromFFI_(float, float)
1095 CYFromFFI_(double, double)
1096
1097 case sig::object_P:
ea2d184c 1098 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
dea834b0
JF
1099 break;
1100
b09da87b 1101 case sig::typename_P:
4cf49641 1102 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
b09da87b
JF
1103 break;
1104
dea834b0
JF
1105 case sig::selector_P:
1106 if (SEL sel = *reinterpret_cast<SEL *>(data))
1107 value = CYMakeSelector(context, sel);
1108 else goto null;
1109 break;
1110
1111 case sig::pointer_P:
1112 if (void *pointer = *reinterpret_cast<void **>(data))
1113 value = CYMakePointer(context, pointer);
1114 else goto null;
1115 break;
1116
1117 case sig::string_P:
f610e1a0 1118 if (char *utf8 = *reinterpret_cast<char **>(data))
b09da87b 1119 value = CYCastJSValue(context, utf8);
f610e1a0 1120 else goto null;
dea834b0 1121 break;
ea2d184c
JF
1122
1123 case sig::struct_P:
1124 goto fail;
1125
1126 case sig::void_P:
b09da87b 1127 value = CYJSUndefined(context);
f610e1a0
JF
1128 break;
1129
1130 null:
b09da87b 1131 value = CYJSNull(context);
ea2d184c
JF
1132 break;
1133
1134 default: fail:
1135 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1136 _assert(false);
1137 }
1138
1139 return value;
1140}
1141
b09da87b 1142static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
4cf49641 1143 CYTry {
85a33bf5 1144 if (count != signature->count - 1)
f5e9be24 1145 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
85a33bf5 1146
7ba62cfd
JF
1147 CYPool pool;
1148 void *values[count];
ea2d184c 1149
7ba62cfd
JF
1150 for (unsigned index(0); index != count; ++index) {
1151 sig::Element *element(&signature->elements[index + 1]);
77e87a6c 1152 // XXX: alignment?
b21525c7 1153 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
43cb3d68 1154 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
7ba62cfd 1155 }
ea2d184c 1156
7ba62cfd
JF
1157 uint8_t value[cif->rtype->size];
1158 ffi_call(cif, function, value, values);
1159
43cb3d68 1160 return CYFromFFI(context, signature->elements[0].type, value);
0c862573 1161 } CYCatch
7ba62cfd 1162}
ea2d184c 1163
478d4ed0 1164void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
478d4ed0
JF
1165 ffoData *data(reinterpret_cast<ffoData *>(arg));
1166
1167 JSContextRef context(data->context_);
1168
1169 size_t count(data->cif_.nargs);
1170 JSValueRef values[count];
1171
1172 for (size_t index(0); index != count; ++index)
1173 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, arguments[index]);
1174
1175 JSValueRef exception(NULL);
1176 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1177 CYThrow(context, exception);
1178
1179 CYPoolFFI(NULL, context, data->signature_.elements[0].type, result, value);
1180}
1181
1182JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1183 // XXX: in case of exceptions this will leak
1184 ffoData *data(new ffoData(type));
1185
1186 ffi_closure *closure;
1187 _syscall(closure = (ffi_closure *) mmap(
1188 NULL, sizeof(ffi_closure),
1189 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1190 -1, 0
1191 ));
1192
1193 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1194 _assert(status == FFI_OK);
1195
1196 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1197
1198 data->value_ = closure;
1199
1200 data->context_ = CYGetJSContext();
1201 data->function_ = function;
1202
1203 return JSObjectMake(context, Functor_, data);
1204}
1205
b09da87b 1206static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
4cf49641 1207 CYTry {
b09da87b
JF
1208 CYPool pool;
1209 NSString *name(CYCastNSString(pool, property));
f610e1a0 1210 if (Class _class = NSClassFromString(name))
4cf49641 1211 return CYMakeInstance(context, _class, true);
f610e1a0 1212 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
707bcb93
JF
1213 switch ([[entry objectAtIndex:0] intValue]) {
1214 case 0:
057f943f 1215 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
707bcb93 1216 case 1:
478d4ed0 1217 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
707bcb93 1218 case 2:
707bcb93 1219 sig::Signature signature;
478d4ed0 1220 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
f610e1a0 1221 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
707bcb93
JF
1222 }
1223 return NULL;
1224 } CYCatch
1225}
1226
04450da0
JF
1227bool stret(ffi_type *ffi_type) {
1228 return ffi_type->type == FFI_TYPE_STRUCT && (
1229 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1230 struct_forward_array[ffi_type->size] != 0
1231 );
1232}
1233
b09da87b
JF
1234extern "C" {
1235 int *_NSGetArgc(void);
1236 char ***_NSGetArgv(void);
1237 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1238}
1239
1240static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1241 CYTry {
b09da87b
JF
1242 NSLog(@"%s", CYCastCString(context, arguments[0]));
1243 return CYJSUndefined(context);
1244 } CYCatch
1245}
1246
1247static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1248 CYTry {
b09da87b
JF
1249 CYPool pool;
1250 NSString *name(CYCastNSObject(pool, context, arguments[0]));
478d4ed0
JF
1251 int argc(*_NSGetArgc());
1252 char **argv(*_NSGetArgv());
b09da87b
JF
1253 for (int i(0); i != argc; ++i)
1254 NSLog(@"argv[%i]=%s", i, argv[i]);
478d4ed0 1255 _pooled
b09da87b
JF
1256 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1257 } CYCatch
1258}
1259
1260static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
7ba62cfd 1261 const char *type;
ea2d184c 1262
478d4ed0
JF
1263 CYPool pool;
1264
4cf49641 1265 CYTry {
85a33bf5 1266 if (count < 2)
f5e9be24 1267 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
85a33bf5 1268
b09da87b 1269 id self(CYCastNSObject(pool, context, arguments[0]));
7ba62cfd 1270 if (self == nil)
b09da87b 1271 return CYJSNull(context);
7ba62cfd 1272
85a33bf5 1273 SEL _cmd(CYCastSEL(context, arguments[1]));
7ba62cfd 1274
478d4ed0
JF
1275 Class _class(object_getClass(self));
1276 if (Method method = class_getInstanceMethod(_class, _cmd))
1277 type = method_getTypeEncoding(method);
4cf49641
JF
1278 else {
1279 CYPoolTry {
1280 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1281 if (method == nil)
1282 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1283 type = CYPoolCString(pool, [method _typeString]);
1284 } CYPoolCatch(NULL)
478d4ed0 1285 }
0c862573 1286 } CYCatch
ea2d184c 1287
7ba62cfd
JF
1288 sig::Signature signature;
1289 sig::Parse(pool, &signature, type);
ea2d184c 1290
7ba62cfd 1291 ffi_cif cif;
b21525c7 1292 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
7ba62cfd 1293
04450da0 1294 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
7ba62cfd
JF
1295 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1296}
1297
dea834b0
JF
1298static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1299 JSValueRef setup[count + 2];
1300 setup[0] = _this;
1301 setup[1] = object;
1302 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1303 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1304}
1305
1306static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
7ba62cfd 1307 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
77e87a6c 1308 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
ea2d184c
JF
1309}
1310
b09da87b 1311JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1312 CYTry {
dea834b0
JF
1313 if (count != 1)
1314 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1315 const char *name(CYCastCString(context, arguments[0]));
1316 return CYMakeSelector(context, sel_registerName(name));
1317 } CYCatch
1318}
1319
b09da87b 1320JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1321 CYTry {
b21525c7 1322 if (count != 2)
dea834b0 1323 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
b21525c7 1324 const char *type(CYCastCString(context, arguments[1]));
b09da87b
JF
1325 JSValueRef exception(NULL);
1326 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1327 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1328 return CYMakeFunctor(context, function, type);
1329 } else if (exception != NULL) {
1330 return NULL;
1331 } else {
1332 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1333 return CYMakeFunctor(context, function, type);
1334 }
0c862573 1335 } CYCatch
ea2d184c
JF
1336}
1337
f610e1a0 1338JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
04450da0 1339 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
b09da87b 1340 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
04450da0
JF
1341}
1342
dea834b0
JF
1343JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1344 return Function_;
1345}
1346
4cf49641
JF
1347static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1348 CYTry {
478d4ed0 1349 jocData *data(reinterpret_cast<jocData *>(JSObjectGetPrivate(_this)));
4cf49641
JF
1350 NSString *description; CYPoolTry {
1351 description = [data->GetValue() description];
1352 } CYPoolCatch(NULL)
1353 return CYCastJSValue(context, CYJSString(description));
478d4ed0
JF
1354 } CYCatch
1355}
1356
1357static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1358 CYTry {
478d4ed0
JF
1359 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate(_this)));
1360 return CYCastJSValue(context, sel_getName(data->GetValue()));
1361 } CYCatch
1362}
1363
b09da87b 1364static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
4cf49641 1365 CYTry {
b09da87b
JF
1366 if (count != 2)
1367 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1368 CYPool pool;
1369 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate(_this)));
1370 Class _class(CYCastNSObject(pool, context, arguments[0]));
1371 bool instance(CYCastBool(context, arguments[1]));
1372 SEL sel(data->GetValue());
1373 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1374 return CYCastJSValue(context, method_getTypeEncoding(method));
478d4ed0 1375 else if (NSString *type = [Bridge_ objectForKey:CYPoolRelease(pool, [[NSString alloc] initWithFormat:@":%s", sel_getName(sel)])])
b09da87b
JF
1376 return CYCastJSValue(context, CYJSString(type));
1377 else
1378 return CYJSNull(context);
1379 } CYCatch
1380}
1381
88c977fa
JF
1382static JSStaticValue Pointer_staticValues[2] = {
1383 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
04450da0
JF
1384 {NULL, NULL, NULL, 0}
1385};
1386
dea834b0
JF
1387/*static JSStaticValue Selector_staticValues[2] = {
1388 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1389 {NULL, NULL, NULL, 0}
1390};*/
1391
478d4ed0
JF
1392static JSStaticFunction Instance_staticFunctions[2] = {
1393 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1394 {NULL, NULL, 0}
1395};
1396
1397static JSStaticFunction Selector_staticFunctions[3] = {
1398 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
b09da87b
JF
1399 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1400 {NULL, NULL, 0}
1401};
1402
5999c315 1403CYDriver::CYDriver(const std::string &filename) :
db5e2840 1404 state_(CYClear),
e7ed5354
JF
1405 data_(NULL),
1406 size_(0),
5999c315
JF
1407 filename_(filename),
1408 source_(NULL)
1409{
924f67b2
JF
1410 ScannerInit();
1411}
1412
5999c315 1413CYDriver::~CYDriver() {
924f67b2
JF
1414 ScannerDestroy();
1415}
1416
5befe15e
JF
1417void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1418 CYDriver::Error error;
1419 error.location_ = location;
1420 error.message_ = message;
1421 driver.errors_.push_back(error);
63b4c5a8
JF
1422}
1423
b09da87b
JF
1424void CYSetArgs(int argc, const char *argv[]) {
1425 JSContextRef context(CYGetJSContext());
1426 JSValueRef args[argc];
1427 for (int i(0); i != argc; ++i)
1428 args[i] = CYCastJSValue(context, argv[i]);
1429 JSValueRef exception(NULL);
1430 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1431 CYThrow(context, exception);
1432 CYSetProperty(context, System_, CYJSString("args"), array);
1433}
1434
7ba62cfd 1435MSInitialize { _pooled
ea2d184c
JF
1436 apr_initialize();
1437
c1582939
JF
1438 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1439
1440 pid_t pid(getpid());
1441
1442 struct sockaddr_in address;
1443 address.sin_len = sizeof(address);
1444 address.sin_family = AF_INET;
1445 address.sin_addr.s_addr = INADDR_ANY;
1446 address.sin_port = htons(10000 + pid);
1447
1448 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1449
1450 CFSocketSignature signature;
1451 signature.protocolFamily = AF_INET;
1452 signature.socketType = SOCK_STREAM;
1453 signature.protocol = IPPROTO_TCP;
1454 signature.address = data;
1455
1456 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1457 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1458
1459 JSClassDefinition definition;
1460
1461 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1462 definition.className = "Pointer";
1463 definition.staticValues = Pointer_staticValues;
1464 definition.finalize = &Pointer_finalize;
1465 Pointer_ = JSClassCreate(&definition);
c1582939
JF
1466
1467 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1468 definition.className = "Functor";
1469 definition.parentClass = Pointer_;
dea834b0 1470 definition.callAsFunction = &Functor_callAsFunction;
88c977fa 1471 Functor_ = JSClassCreate(&definition);
7ba62cfd 1472
77e87a6c 1473 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1474 definition.className = "Selector";
1475 definition.parentClass = Pointer_;
dea834b0 1476 //definition.staticValues = Selector_staticValues;
b09da87b 1477 definition.staticFunctions = Selector_staticFunctions;
dea834b0 1478 definition.callAsFunction = &Selector_callAsFunction;
88c977fa 1479 Selector_ = JSClassCreate(&definition);
77e87a6c 1480
7ba62cfd 1481 definition = kJSClassDefinitionEmpty;
b09da87b 1482 definition.className = "Instance";
478d4ed0
JF
1483 definition.parentClass = Pointer_;
1484 definition.staticFunctions = Instance_staticFunctions;
88c977fa 1485 definition.getProperty = &Instance_getProperty;
b09da87b
JF
1486 definition.setProperty = &Instance_setProperty;
1487 definition.deleteProperty = &Instance_deleteProperty;
88c977fa 1488 definition.callAsConstructor = &Instance_callAsConstructor;
88c977fa 1489 Instance_ = JSClassCreate(&definition);
7ba62cfd
JF
1490
1491 definition = kJSClassDefinitionEmpty;
88c977fa
JF
1492 definition.getProperty = &Global_getProperty;
1493 JSClassRef Global(JSClassCreate(&definition));
c1582939 1494
478d4ed0 1495 JSGlobalContextRef context(JSGlobalContextCreate(Global));
ea2d184c
JF
1496 Context_ = context;
1497
1498 JSObjectRef global(JSContextGetGlobalObject(context));
c1582939 1499
b09da87b
JF
1500 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1501 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
7ba62cfd 1502
b09da87b 1503 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
dea834b0 1504 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
7ba62cfd 1505
b09da87b
JF
1506 System_ = JSObjectMake(context, NULL, NULL);
1507 CYSetProperty(context, global, CYJSString("system"), System_);
1508 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1509 CYSetProperty(context, System_, CYJSString("global"), global);
1510
1511 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1512
107e3ed0 1513 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
c1582939 1514
62ca2b82
JF
1515 name_ = JSStringCreateWithUTF8CString("name");
1516 message_ = JSStringCreateWithUTF8CString("message");
c1582939
JF
1517 length_ = JSStringCreateWithUTF8CString("length");
1518
dea834b0
JF
1519 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1520 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
c1582939 1521}