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