]> git.saurik.com Git - cycript.git/blame_incremental - Library.mm
Minor refactoring, checkpoint commit.
[cycript.git] / Library.mm
... / ...
CommitLineData
1/* Cyrker - Remove Execution Server and Disassembler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
5/* Modified BSD License {{{ */
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
38/* }}} */
39
40#define _GNU_SOURCE
41
42#include <substrate.h>
43#include "cycript.hpp"
44
45#include "sig/parse.hpp"
46#include "sig/ffi_type.hpp"
47
48#include "Pooling.hpp"
49#include "Struct.hpp"
50
51#include <unistd.h>
52
53#include <CoreFoundation/CoreFoundation.h>
54#include <CoreFoundation/CFLogUtilities.h>
55
56#include <CFNetwork/CFNetwork.h>
57
58#include <WebKit/WebScriptObject.h>
59
60#include <sys/types.h>
61#include <sys/socket.h>
62#include <netinet/in.h>
63#include <sys/mman.h>
64
65#include <iostream>
66#include <ext/stdio_filebuf.h>
67#include <set>
68#include <map>
69
70#include <cmath>
71
72#include "Parser.hpp"
73#include "Cycript.tab.hh"
74
75#undef _assert
76#undef _trace
77
78#define _assert(test) do { \
79 if (!(test)) \
80 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
81} while (false)
82
83#define _trace() do { \
84 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
85} while (false)
86
87#define CYPoolTry { \
88 id _saved(nil); \
89 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
90 @try
91#define CYPoolCatch(value) \
92 @catch (NSException *error) { \
93 _saved = [error retain]; \
94 @throw; \
95 return value; \
96 } @finally { \
97 [_pool release]; \
98 if (_saved != nil) \
99 [_saved autorelease]; \
100 } \
101}
102
103static JSGlobalContextRef Context_;
104static JSObjectRef System_;
105
106static JSClassRef Functor_;
107static JSClassRef Instance_;
108static JSClassRef Pointer_;
109static JSClassRef Runtime_;
110static JSClassRef Selector_;
111static JSClassRef Struct_;
112
113static JSObjectRef Array_;
114static JSObjectRef Function_;
115
116static JSStringRef name_;
117static JSStringRef message_;
118static JSStringRef length_;
119
120static Class NSCFBoolean_;
121
122static NSArray *Bridge_;
123
124struct Client {
125 CFHTTPMessageRef message_;
126 CFSocketRef socket_;
127};
128
129struct CYData {
130 apr_pool_t *pool_;
131
132 virtual ~CYData() {
133 }
134
135 void *operator new(size_t size) {
136 apr_pool_t *pool;
137 apr_pool_create(&pool, NULL);
138 void *data(apr_palloc(pool, size));
139 reinterpret_cast<CYData *>(data)->pool_ = pool;
140 return data;;
141 }
142
143 static void Finalize(JSObjectRef object) {
144 CYData *data(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
145 data->~CYData();
146 apr_pool_destroy(data->pool_);
147 }
148};
149
150struct Pointer_privateData :
151 CYData
152{
153 void *value_;
154 sig::Type type_;
155
156 Pointer_privateData() {
157 }
158
159 Pointer_privateData(void *value) :
160 value_(value)
161 {
162 }
163};
164
165struct Functor_privateData :
166 Pointer_privateData
167{
168 sig::Signature signature_;
169 ffi_cif cif_;
170
171 Functor_privateData(const char *type, void (*value)()) :
172 Pointer_privateData(reinterpret_cast<void *>(value))
173 {
174 sig::Parse(pool_, &signature_, type);
175 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
176 }
177};
178
179struct ffoData :
180 Functor_privateData
181{
182 JSContextRef context_;
183 JSObjectRef function_;
184
185 ffoData(const char *type) :
186 Functor_privateData(type, NULL)
187 {
188 }
189};
190
191struct Selector_privateData : Pointer_privateData {
192 Selector_privateData(SEL value) :
193 Pointer_privateData(value)
194 {
195 }
196
197 SEL GetValue() const {
198 return reinterpret_cast<SEL>(value_);
199 }
200};
201
202struct Instance_privateData :
203 Pointer_privateData
204{
205 bool transient_;
206
207 Instance_privateData(id value, bool transient) :
208 Pointer_privateData(value)
209 {
210 }
211
212 virtual ~Instance_privateData() {
213 if (!transient_)
214 [GetValue() release];
215 }
216
217 id GetValue() const {
218 return reinterpret_cast<id>(value_);
219 }
220};
221
222namespace sig {
223
224void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
225
226void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
227 lhs.name = apr_pstrdup(pool, rhs.name);
228 if (rhs.type == NULL)
229 lhs.type = NULL;
230 else {
231 lhs.type = new(pool) Type;
232 Copy(pool, *lhs.type, *rhs.type);
233 }
234 lhs.offset = rhs.offset;
235}
236
237void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
238 size_t count(rhs.count);
239 lhs.count = count;
240 lhs.elements = new(pool) Element[count];
241 for (size_t index(0); index != count; ++index)
242 Copy(pool, lhs.elements[index], rhs.elements[index]);
243}
244
245void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
246 lhs.primitive = rhs.primitive;
247 lhs.name = apr_pstrdup(pool, rhs.name);
248 lhs.flags = rhs.flags;
249
250 if (sig::IsAggregate(rhs.primitive))
251 Copy(pool, lhs.data.signature, rhs.data.signature);
252 else {
253 if (rhs.data.data.type != NULL) {
254 lhs.data.data.type = new(pool) Type;
255 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
256 }
257
258 lhs.data.data.size = rhs.data.data.size;
259 }
260}
261
262void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
263 lhs.size = rhs.size;
264 lhs.alignment = rhs.alignment;
265 lhs.type = rhs.type;
266 if (rhs.elements == NULL)
267 lhs.elements = NULL;
268 else {
269 size_t count(0);
270 while (rhs.elements[count] != NULL)
271 ++count;
272
273 lhs.elements = new(pool) ffi_type *[count + 1];
274 lhs.elements[count] = NULL;
275
276 for (size_t index(0); index != count; ++index) {
277 // XXX: if these are libffi native then you can just take them
278 ffi_type *ffi(new(pool) ffi_type);
279 lhs.elements[index] = ffi;
280 sig::Copy(pool, *ffi, *rhs.elements[index]);
281 }
282 }
283}
284
285}
286
287struct Type_privateData {
288 sig::Type type_;
289 ffi_type ffi_;
290 //size_t count_;
291
292 Type_privateData(apr_pool_t *pool, sig::Type *type, ffi_type *ffi) {
293 sig::Copy(pool, type_, *type);
294 sig::Copy(pool, ffi_, *ffi);
295
296 /*sig::Element element;
297 element.name = NULL;
298 element.type = type;
299 element.offset = 0;
300
301 sig::Signature signature;
302 signature.elements = &element;
303 signature.count = 1;
304
305 ffi_cif cif;
306 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
307 ffi_ = *cif.rtype;*/
308
309 /*if (type_->type != FFI_TYPE_STRUCT)
310 count_ = 0;
311 else {
312 size_t count(0);
313 while (type_->elements[count] != NULL)
314 ++count;
315 count_ = count;
316 }*/
317 }
318};
319
320struct Struct_privateData :
321 Pointer_privateData
322{
323 JSObjectRef owner_;
324 Type_privateData *type_;
325
326 Struct_privateData() {
327 }
328};
329
330struct CStringMapLess :
331 std::binary_function<const char *, const char *, bool>
332{
333 _finline bool operator ()(const char *lhs, const char *rhs) const {
334 return strcmp(lhs, rhs) < 0;
335 }
336};
337
338typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
339static TypeMap Types_;
340
341JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
342 Struct_privateData *internal(new Struct_privateData());
343 apr_pool_t *pool(internal->pool_);
344 Type_privateData *typical(new(pool) Type_privateData(pool, type, ffi));
345 internal->type_ = typical;
346
347 if (owner != NULL) {
348 internal->owner_ = owner;
349 internal->value_ = data;
350 } else {
351 internal->owner_ = NULL;
352
353 size_t size(typical->ffi_.size);
354 void *copy(apr_palloc(internal->pool_, size));
355 memcpy(copy, data, size);
356 internal->value_ = copy;
357 }
358
359 return JSObjectMake(context, Struct_, internal);
360}
361
362JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
363 if (!transient)
364 object = [object retain];
365 Instance_privateData *data(new Instance_privateData(object, transient));
366 return JSObjectMake(context, Instance_, data);
367}
368
369const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
370 if (pool == NULL)
371 return [value UTF8String];
372 else {
373 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
374 char *string(new(pool) char[size]);
375 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
376 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
377 return string;
378 }
379}
380
381JSValueRef CYCastJSValue(JSContextRef context, bool value) {
382 return JSValueMakeBoolean(context, value);
383}
384
385JSValueRef CYCastJSValue(JSContextRef context, double value) {
386 return JSValueMakeNumber(context, value);
387}
388
389#define CYCastJSValue_(Type_) \
390 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
391 return JSValueMakeNumber(context, static_cast<double>(value)); \
392 }
393
394CYCastJSValue_(int)
395CYCastJSValue_(unsigned int)
396CYCastJSValue_(long int)
397CYCastJSValue_(long unsigned int)
398CYCastJSValue_(long long int)
399CYCastJSValue_(long long unsigned int)
400
401JSValueRef CYJSUndefined(JSContextRef context) {
402 return JSValueMakeUndefined(context);
403}
404
405@interface NSMethodSignature (Cycript)
406- (NSString *) _typeString;
407@end
408
409@interface NSObject (Cycript)
410- (bool) cy$isUndefined;
411- (NSString *) cy$toJSON;
412- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient;
413- (NSObject *) cy$getProperty:(NSString *)name;
414- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
415- (bool) cy$deleteProperty:(NSString *)name;
416@end
417
418@interface NSString (Cycript)
419- (void *) cy$symbol;
420@end
421
422@interface NSNumber (Cycript)
423- (void *) cy$symbol;
424@end
425
426@implementation NSObject (Cycript)
427
428- (bool) cy$isUndefined {
429 return false;
430}
431
432- (NSString *) cy$toJSON {
433 return [self description];
434}
435
436- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
437 return CYMakeInstance(context, self, transient);
438}
439
440- (NSObject *) cy$getProperty:(NSString *)name {
441 if (![name isEqualToString:@"prototype"])
442 NSLog(@"get:%@", name);
443 return nil;
444}
445
446- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
447 NSLog(@"set:%@", name);
448 return false;
449}
450
451- (bool) cy$deleteProperty:(NSString *)name {
452 NSLog(@"delete:%@", name);
453 return false;
454}
455
456@end
457
458@implementation WebUndefined (Cycript)
459
460- (bool) cy$isUndefined {
461 return true;
462}
463
464- (NSString *) cy$toJSON {
465 return @"undefined";
466}
467
468- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
469 return CYJSUndefined(context);
470}
471
472@end
473
474@implementation NSNull (Cycript)
475
476- (NSString *) cy$toJSON {
477 return @"null";
478}
479
480@end
481
482@implementation NSArray (Cycript)
483
484- (NSString *) cy$toJSON {
485 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
486 [json appendString:@"["];
487
488 bool comma(false);
489 for (id object in self) {
490 if (comma)
491 [json appendString:@","];
492 else
493 comma = true;
494 if (![object cy$isUndefined])
495 [json appendString:[object cy$toJSON]];
496 else {
497 [json appendString:@","];
498 comma = false;
499 }
500 }
501
502 [json appendString:@"]"];
503 return json;
504}
505
506- (NSObject *) cy$getProperty:(NSString *)name {
507 int index([name intValue]);
508 if (index < 0 || index >= static_cast<int>([self count]))
509 return [super cy$getProperty:name];
510 else
511 return [self objectAtIndex:index];
512}
513
514@end
515
516@implementation NSMutableArray (Cycript)
517
518- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
519 int index([name intValue]);
520 if (index < 0 || index >= static_cast<int>([self count]))
521 return [super cy$setProperty:name to:value];
522 else {
523 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
524 return true;
525 }
526}
527
528- (bool) cy$deleteProperty:(NSString *)name {
529 int index([name intValue]);
530 if (index < 0 || index >= static_cast<int>([self count]))
531 return [super cy$deleteProperty:name];
532 else {
533 [self removeObjectAtIndex:index];
534 return true;
535 }
536}
537
538@end
539
540@implementation NSDictionary (Cycript)
541
542- (NSString *) cy$toJSON {
543 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
544 [json appendString:@"({"];
545
546 bool comma(false);
547 for (id key in self) {
548 if (comma)
549 [json appendString:@","];
550 else
551 comma = true;
552 [json appendString:[key cy$toJSON]];
553 [json appendString:@":"];
554 NSObject *object([self objectForKey:key]);
555 [json appendString:[object cy$toJSON]];
556 }
557
558 [json appendString:@"})"];
559 return json;
560}
561
562- (NSObject *) cy$getProperty:(NSString *)name {
563 return [self objectForKey:name];
564}
565
566@end
567
568@implementation NSMutableDictionary (Cycript)
569
570- (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
571 [self setObject:(value ?: [NSNull null]) forKey:name];
572 return true;
573}
574
575- (bool) cy$deleteProperty:(NSString *)name {
576 if ([self objectForKey:name] == nil)
577 return false;
578 else {
579 [self removeObjectForKey:name];
580 return true;
581 }
582}
583
584@end
585
586@implementation NSNumber (Cycript)
587
588- (NSString *) cy$toJSON {
589 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
590}
591
592- (JSValueRef) cy$JSValueInContext:(JSContextRef)context transient:(bool)transient {
593 return [self class] != NSCFBoolean_ ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
594}
595
596- (void *) cy$symbol {
597 return [self pointerValue];
598}
599
600@end
601
602@implementation NSString (Cycript)
603
604- (NSString *) cy$toJSON {
605 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
606
607 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
608 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
609 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
610 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
611 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
612
613 CFStringInsert(json, 0, CFSTR("\""));
614 CFStringAppend(json, CFSTR("\""));
615
616 return [reinterpret_cast<const NSString *>(json) autorelease];
617}
618
619- (void *) cy$symbol {
620 CYPool pool;
621 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
622}
623
624@end
625
626@interface CYJSObject : NSDictionary {
627 JSObjectRef object_;
628 JSContextRef context_;
629}
630
631- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
632
633- (NSUInteger) count;
634- (id) objectForKey:(id)key;
635- (NSEnumerator *) keyEnumerator;
636- (void) setObject:(id)object forKey:(id)key;
637- (void) removeObjectForKey:(id)key;
638
639@end
640
641@interface CYJSArray : NSArray {
642 JSObjectRef object_;
643 JSContextRef context_;
644}
645
646- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
647
648- (NSUInteger) count;
649- (id) objectAtIndex:(NSUInteger)index;
650
651@end
652
653CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
654CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
655
656JSGlobalContextRef CYGetJSContext() {
657 return Context_;
658}
659
660#define CYTry \
661 @try
662#define CYCatch \
663 @catch (id error) { \
664 CYThrow(context, error, exception); \
665 return NULL; \
666 }
667
668void CYThrow(JSContextRef context, JSValueRef value);
669
670apr_status_t CYPoolRelease_(void *data) {
671 id object(reinterpret_cast<id>(data));
672 [object release];
673 return APR_SUCCESS;
674}
675
676id CYPoolRelease(apr_pool_t *pool, id object) {
677 if (pool == NULL)
678 return [object autorelease];
679 else {
680 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
681 return object;
682 }
683}
684
685CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
686 return (CFTypeRef) CYPoolRelease(pool, (id) object);
687}
688
689id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
690 if (JSValueIsObjectOfClass(context, object, Instance_)) {
691 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
692 return data->GetValue();
693 }
694
695 JSValueRef exception(NULL);
696 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
697 CYThrow(context, exception);
698 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
699 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
700}
701
702JSStringRef CYCopyJSString(id value) {
703 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
704}
705
706JSStringRef CYCopyJSString(const char *value) {
707 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
708}
709
710JSStringRef CYCopyJSString(JSStringRef value) {
711 return value == NULL ? NULL : JSStringRetain(value);
712}
713
714JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
715 if (JSValueIsNull(context, value))
716 return NULL;
717 JSValueRef exception(NULL);
718 JSStringRef string(JSValueToStringCopy(context, value, &exception));
719 CYThrow(context, exception);
720 return string;
721}
722
723class CYJSString {
724 private:
725 JSStringRef string_;
726
727 void Clear_() {
728 JSStringRelease(string_);
729 }
730
731 public:
732 CYJSString(const CYJSString &rhs) :
733 string_(CYCopyJSString(rhs.string_))
734 {
735 }
736
737 template <typename Arg0_>
738 CYJSString(Arg0_ arg0) :
739 string_(CYCopyJSString(arg0))
740 {
741 }
742
743 template <typename Arg0_, typename Arg1_>
744 CYJSString(Arg0_ arg0, Arg1_ arg1) :
745 string_(CYCopyJSString(arg0, arg1))
746 {
747 }
748
749 CYJSString &operator =(const CYJSString &rhs) {
750 Clear_();
751 string_ = CYCopyJSString(rhs.string_);
752 return *this;
753 }
754
755 ~CYJSString() {
756 Clear_();
757 }
758
759 void Clear() {
760 Clear_();
761 string_ = NULL;
762 }
763
764 operator JSStringRef() const {
765 return string_;
766 }
767};
768
769CFStringRef CYCopyCFString(JSStringRef value) {
770 return JSStringCopyCFString(kCFAllocatorDefault, value);
771}
772
773CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
774 return CYCopyCFString(CYJSString(context, value));
775}
776
777double CYCastDouble(const char *value, size_t size) {
778 char *end;
779 double number(strtod(value, &end));
780 if (end != value + size)
781 return NAN;
782 return number;
783}
784
785double CYCastDouble(const char *value) {
786 return CYCastDouble(value, strlen(value));
787}
788
789double CYCastDouble(JSContextRef context, JSValueRef value) {
790 JSValueRef exception(NULL);
791 double number(JSValueToNumber(context, value, &exception));
792 CYThrow(context, exception);
793 return number;
794}
795
796CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
797 double number(CYCastDouble(context, value));
798 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
799}
800
801CFStringRef CYCopyCFString(const char *value) {
802 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
803}
804
805NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
806 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
807}
808
809NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
810 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
811}
812
813bool CYCastBool(JSContextRef context, JSValueRef value) {
814 return JSValueToBoolean(context, value);
815}
816
817CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
818 CFTypeRef object;
819 bool copy;
820
821 switch (JSType type = JSValueGetType(context, value)) {
822 case kJSTypeUndefined:
823 object = [WebUndefined undefined];
824 copy = false;
825 break;
826
827 case kJSTypeNull:
828 return NULL;
829 break;
830
831 case kJSTypeBoolean:
832 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
833 copy = false;
834 break;
835
836 case kJSTypeNumber:
837 object = CYCopyCFNumber(context, value);
838 copy = true;
839 break;
840
841 case kJSTypeString:
842 object = CYCopyCFString(context, value);
843 copy = true;
844 break;
845
846 case kJSTypeObject:
847 // XXX: this might could be more efficient
848 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
849 copy = false;
850 break;
851
852 default:
853 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
854 break;
855 }
856
857 if (cast != copy)
858 return object;
859 else if (copy)
860 return CYPoolRelease(pool, object);
861 else
862 return CFRetain(object);
863}
864
865CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
866 return CYCFType(pool, context, value, true);
867}
868
869CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
870 return CYCFType(pool, context, value, false);
871}
872
873NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
874 CYPool pool;
875 size_t size(JSPropertyNameArrayGetCount(names));
876 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
877 for (size_t index(0); index != size; ++index)
878 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
879 return array;
880}
881
882id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
883 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
884}
885
886void CYThrow(JSContextRef context, JSValueRef value) {
887 if (value == NULL)
888 return;
889 @throw CYCastNSObject(NULL, context, value);
890}
891
892JSValueRef CYJSNull(JSContextRef context) {
893 return JSValueMakeNull(context);
894}
895
896JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
897 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
898}
899
900JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
901 return CYCastJSValue(context, CYJSString(value));
902}
903
904JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
905 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
906}
907
908JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
909 JSValueRef exception(NULL);
910 JSObjectRef object(JSValueToObject(context, value, &exception));
911 CYThrow(context, exception);
912 return object;
913}
914
915JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
916 JSValueRef exception(NULL);
917 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
918 CYThrow(context, exception);
919 return value;
920}
921
922JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
923 JSValueRef exception(NULL);
924 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
925 CYThrow(context, exception);
926 return value;
927}
928
929void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
930 JSValueRef exception(NULL);
931 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
932 CYThrow(context, exception);
933}
934
935void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
936 if (exception == NULL)
937 throw error;
938 *exception = CYCastJSValue(context, error);
939}
940
941@implementation CYJSObject
942
943- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
944 if ((self = [super init]) != nil) {
945 object_ = object;
946 context_ = context;
947 } return self;
948}
949
950- (NSUInteger) count {
951 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
952 size_t size(JSPropertyNameArrayGetCount(names));
953 JSPropertyNameArrayRelease(names);
954 return size;
955}
956
957- (id) objectForKey:(id)key {
958 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
959}
960
961- (NSEnumerator *) keyEnumerator {
962 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
963 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
964 JSPropertyNameArrayRelease(names);
965 return enumerator;
966}
967
968- (void) setObject:(id)object forKey:(id)key {
969 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
970}
971
972- (void) removeObjectForKey:(id)key {
973 JSValueRef exception(NULL);
974 // XXX: this returns a bool... throw exception, or ignore?
975 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
976 CYThrow(context_, exception);
977}
978
979@end
980
981@implementation CYJSArray
982
983- (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
984 if ((self = [super init]) != nil) {
985 object_ = object;
986 context_ = context;
987 } return self;
988}
989
990- (NSUInteger) count {
991 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
992}
993
994- (id) objectAtIndex:(NSUInteger)index {
995 JSValueRef exception(NULL);
996 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
997 CYThrow(context_, exception);
998 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
999}
1000
1001@end
1002
1003CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1004 CYTry {
1005 CYPoolTry {
1006 id object(CYCastNSObject(NULL, context, value));
1007 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
1008 } CYPoolCatch(NULL)
1009 } CYCatch
1010}
1011
1012const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1013 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
1014 const char *string(CYPoolCString(pool, json));
1015 [json release];
1016 return string;
1017 } else return NULL;
1018}
1019
1020static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1021 switch (type) {
1022 case kCFSocketDataCallBack:
1023 CFDataRef data(reinterpret_cast<CFDataRef>(value));
1024 Client *client(reinterpret_cast<Client *>(info));
1025
1026 if (client->message_ == NULL)
1027 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
1028
1029 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
1030 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
1031 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
1032 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
1033 Boolean absolute;
1034 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
1035 CFRelease(client->message_);
1036
1037 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
1038 CFRelease(path);
1039
1040 JSStringRef script(JSStringCreateWithCFString(code));
1041 CFRelease(code);
1042
1043 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
1044 JSStringRelease(script);
1045
1046 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
1047 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
1048
1049 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
1050 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
1051 CFRelease(json);
1052
1053 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
1054 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
1055 CFRelease(length);
1056
1057 CFHTTPMessageSetBody(response, body);
1058 CFRelease(body);
1059
1060 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
1061 CFRelease(response);
1062
1063 CFSocketSendData(socket, NULL, serialized, 0);
1064 CFRelease(serialized);
1065
1066 CFRelease(url);
1067 }
1068 break;
1069 }
1070}
1071
1072static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1073 switch (type) {
1074 case kCFSocketAcceptCallBack:
1075 Client *client(new Client());
1076
1077 client->message_ = NULL;
1078
1079 CFSocketContext context;
1080 context.version = 0;
1081 context.info = client;
1082 context.retain = NULL;
1083 context.release = NULL;
1084 context.copyDescription = NULL;
1085
1086 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
1087
1088 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
1089 break;
1090 }
1091}
1092
1093static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1094 CYTry {
1095 CYPool pool;
1096 NSString *self(CYCastNSObject(pool, context, object));
1097 NSString *name(CYCastNSString(pool, property));
1098 NSObject *data([self cy$getProperty:name]);
1099 return data == nil ? NULL : CYCastJSValue(context, data);
1100 } CYCatch
1101}
1102
1103static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1104 CYTry {
1105 CYPool pool;
1106 NSString *self(CYCastNSObject(pool, context, object));
1107 NSString *name(CYCastNSString(pool, property));
1108 NSString *data(CYCastNSObject(pool, context, value));
1109 return [self cy$setProperty:name to:data];
1110 } CYCatch
1111}
1112
1113static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1114 CYTry {
1115 CYPool pool;
1116 NSString *self(CYCastNSObject(pool, context, object));
1117 NSString *name(CYCastNSString(pool, property));
1118 return [self cy$deleteProperty:name];
1119 } CYCatch
1120}
1121
1122static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1123 CYTry {
1124 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1125 return CYMakeInstance(context, [data->GetValue() alloc], true);
1126 } CYCatch
1127}
1128
1129JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1130 Selector_privateData *data(new Selector_privateData(sel));
1131 return JSObjectMake(context, Selector_, data);
1132}
1133
1134JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1135 Pointer_privateData *data(new Pointer_privateData(pointer));
1136 return JSObjectMake(context, Pointer_, data);
1137}
1138
1139JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1140 Functor_privateData *data(new Functor_privateData(type, function));
1141 return JSObjectMake(context, Functor_, data);
1142}
1143
1144const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1145 if (pool == NULL) {
1146 const char *string([CYCastNSString(NULL, value) UTF8String]);
1147 if (length != NULL)
1148 *length = strlen(string);
1149 return string;
1150 } else {
1151 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1152 char *string(new(pool) char[size]);
1153 JSStringGetUTF8CString(value, string, size);
1154 // XXX: this is ironic
1155 if (length != NULL)
1156 *length = strlen(string);
1157 return string;
1158 }
1159}
1160
1161const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1162 if (!JSValueIsNull(context, value))
1163 return CYPoolCString(pool, CYJSString(context, value), length);
1164 else {
1165 if (length != NULL)
1166 *length = 0;
1167 return NULL;
1168 }
1169}
1170
1171// XXX: this macro is unhygenic
1172#define CYCastCString(context, value) ({ \
1173 char *utf8; \
1174 if (value == NULL) \
1175 utf8 = NULL; \
1176 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1177 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1178 utf8 = reinterpret_cast<char *>(alloca(size)); \
1179 JSStringGetUTF8CString(string, utf8, size); \
1180 JSStringRelease(string); \
1181 } else \
1182 utf8 = NULL; \
1183 utf8; \
1184})
1185
1186SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1187 if (JSValueIsNull(context, value))
1188 return NULL;
1189 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1190 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1191 return reinterpret_cast<SEL>(data->value_);
1192 } else
1193 return sel_registerName(CYCastCString(context, value));
1194}
1195
1196void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1197 switch (JSValueGetType(context, value)) {
1198 case kJSTypeNull:
1199 return NULL;
1200 /*case kJSTypeString:
1201 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1202 case kJSTypeObject:
1203 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1204 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1205 return data->value_;
1206 }*/
1207 default:
1208 double number(CYCastDouble(context, value));
1209 if (std::isnan(number))
1210 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1211 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1212 }
1213}
1214
1215template <typename Type_>
1216_finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1217 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1218}
1219
1220void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1221 switch (type->primitive) {
1222 case sig::boolean_P:
1223 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1224 break;
1225
1226#define CYPoolFFI_(primitive, native) \
1227 case sig::primitive ## _P: \
1228 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1229 break;
1230
1231 CYPoolFFI_(uchar, unsigned char)
1232 CYPoolFFI_(char, char)
1233 CYPoolFFI_(ushort, unsigned short)
1234 CYPoolFFI_(short, short)
1235 CYPoolFFI_(ulong, unsigned long)
1236 CYPoolFFI_(long, long)
1237 CYPoolFFI_(uint, unsigned int)
1238 CYPoolFFI_(int, int)
1239 CYPoolFFI_(ulonglong, unsigned long long)
1240 CYPoolFFI_(longlong, long long)
1241 CYPoolFFI_(float, float)
1242 CYPoolFFI_(double, double)
1243
1244 case sig::object_P:
1245 case sig::typename_P:
1246 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1247 break;
1248
1249 case sig::selector_P:
1250 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1251 break;
1252
1253 case sig::pointer_P:
1254 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1255 break;
1256
1257 case sig::string_P:
1258 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1259 break;
1260
1261 case sig::struct_P: {
1262 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1263 bool aggregate(JSValueIsObject(context, value));
1264 for (size_t index(0); index != type->data.signature.count; ++index) {
1265 ffi_type *element(ffi->elements[index]);
1266 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1267 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1268 // XXX: alignment?
1269 base += element->size;
1270 }
1271 } break;
1272
1273 case sig::void_P:
1274 break;
1275
1276 default:
1277 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1278 _assert(false);
1279 }
1280}
1281
1282JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1283 JSValueRef value;
1284
1285 switch (type->primitive) {
1286 case sig::boolean_P:
1287 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1288 break;
1289
1290#define CYFromFFI_(primitive, native) \
1291 case sig::primitive ## _P: \
1292 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1293 break;
1294
1295 CYFromFFI_(uchar, unsigned char)
1296 CYFromFFI_(char, char)
1297 CYFromFFI_(ushort, unsigned short)
1298 CYFromFFI_(short, short)
1299 CYFromFFI_(ulong, unsigned long)
1300 CYFromFFI_(long, long)
1301 CYFromFFI_(uint, unsigned int)
1302 CYFromFFI_(int, int)
1303 CYFromFFI_(ulonglong, unsigned long long)
1304 CYFromFFI_(longlong, long long)
1305 CYFromFFI_(float, float)
1306 CYFromFFI_(double, double)
1307
1308 case sig::object_P:
1309 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1310 break;
1311
1312 case sig::typename_P:
1313 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1314 break;
1315
1316 case sig::selector_P:
1317 if (SEL sel = *reinterpret_cast<SEL *>(data))
1318 value = CYMakeSelector(context, sel);
1319 else goto null;
1320 break;
1321
1322 case sig::pointer_P:
1323 if (void *pointer = *reinterpret_cast<void **>(data))
1324 value = CYMakePointer(context, pointer);
1325 else goto null;
1326 break;
1327
1328 case sig::string_P:
1329 if (char *utf8 = *reinterpret_cast<char **>(data))
1330 value = CYCastJSValue(context, utf8);
1331 else goto null;
1332 break;
1333
1334 case sig::struct_P:
1335 value = CYMakeStruct(context, data, type, ffi, owner);
1336 break;
1337
1338 case sig::void_P:
1339 value = CYJSUndefined(context);
1340 break;
1341
1342 null:
1343 value = CYJSNull(context);
1344 break;
1345
1346 default:
1347 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1348 _assert(false);
1349 }
1350
1351 return value;
1352}
1353
1354bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1355 Type_privateData *typical(internal->type_);
1356
1357 size_t length;
1358 const char *name(CYPoolCString(pool, property, &length));
1359 double number(CYCastDouble(name, length));
1360
1361 if (std::isnan(number)) {
1362 if (property == NULL)
1363 return false;
1364
1365 // XXX: implement!
1366 return false;
1367 } else {
1368 index = static_cast<ssize_t>(number);
1369 if (index != number || index < 0 || static_cast<size_t>(index) >= typical->type_.data.signature.count)
1370 return false;
1371 }
1372
1373 base = reinterpret_cast<uint8_t *>(internal->value_);
1374 for (ssize_t local(0); local != index; ++local)
1375 base += typical->ffi_.elements[local]->size;
1376
1377 return true;
1378}
1379
1380static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1381 CYTry {
1382 CYPool pool;
1383 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1384 Type_privateData *typical(internal->type_);
1385
1386 ssize_t index;
1387 uint8_t *base;
1388
1389 if (!Index_(pool, internal, property, index, base))
1390 return NULL;
1391
1392 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1393 } CYCatch
1394}
1395
1396static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1397 CYTry {
1398 CYPool pool;
1399 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1400 Type_privateData *typical(internal->type_);
1401
1402 ssize_t index;
1403 uint8_t *base;
1404
1405 if (!Index_(pool, internal, property, index, base))
1406 return false;
1407
1408 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1409 return true;
1410 } CYCatch
1411}
1412
1413static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1414 CYTry {
1415 if (count != signature->count - 1)
1416 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1417
1418 CYPool pool;
1419 void *values[count];
1420
1421 for (unsigned index(0); index != count; ++index) {
1422 sig::Element *element(&signature->elements[index + 1]);
1423 ffi_type *ffi(cif->arg_types[index]);
1424 // XXX: alignment?
1425 values[index] = new(pool) uint8_t[ffi->size];
1426 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1427 }
1428
1429 uint8_t value[cif->rtype->size];
1430 ffi_call(cif, function, value, values);
1431
1432 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1433 } CYCatch
1434}
1435
1436void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1437 ffoData *data(reinterpret_cast<ffoData *>(arg));
1438
1439 JSContextRef context(data->context_);
1440
1441 size_t count(data->cif_.nargs);
1442 JSValueRef values[count];
1443
1444 for (size_t index(0); index != count; ++index)
1445 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1446
1447 JSValueRef exception(NULL);
1448 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1449 CYThrow(context, exception);
1450
1451 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1452}
1453
1454JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1455 // XXX: in case of exceptions this will leak
1456 ffoData *data(new ffoData(type));
1457
1458 ffi_closure *closure;
1459 _syscall(closure = (ffi_closure *) mmap(
1460 NULL, sizeof(ffi_closure),
1461 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1462 -1, 0
1463 ));
1464
1465 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1466 _assert(status == FFI_OK);
1467
1468 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1469
1470 data->value_ = closure;
1471
1472 data->context_ = CYGetJSContext();
1473 data->function_ = function;
1474
1475 return JSObjectMake(context, Functor_, data);
1476}
1477
1478static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1479 CYTry {
1480 CYPool pool;
1481 NSString *name(CYCastNSString(pool, property));
1482 if (Class _class = NSClassFromString(name))
1483 return CYMakeInstance(context, _class, true);
1484 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1485 switch ([[entry objectAtIndex:0] intValue]) {
1486 case 0:
1487 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1488 case 1:
1489 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1490 case 2:
1491 // XXX: this is horrendously inefficient
1492 sig::Signature signature;
1493 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1494 ffi_cif cif;
1495 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1496 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1497 }
1498 return NULL;
1499 } CYCatch
1500}
1501
1502bool stret(ffi_type *ffi_type) {
1503 return ffi_type->type == FFI_TYPE_STRUCT && (
1504 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1505 struct_forward_array[ffi_type->size] != 0
1506 );
1507}
1508
1509extern "C" {
1510 int *_NSGetArgc(void);
1511 char ***_NSGetArgv(void);
1512 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1513}
1514
1515static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1516 CYTry {
1517 NSLog(@"%s", CYCastCString(context, arguments[0]));
1518 return CYJSUndefined(context);
1519 } CYCatch
1520}
1521
1522static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1523 CYTry {
1524 CYPool pool;
1525 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1526 int argc(*_NSGetArgc());
1527 char **argv(*_NSGetArgv());
1528 for (int i(0); i != argc; ++i)
1529 NSLog(@"argv[%i]=%s", i, argv[i]);
1530 _pooled
1531 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1532 } CYCatch
1533}
1534
1535static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1536 const char *type;
1537
1538 CYPool pool;
1539
1540 CYTry {
1541 if (count < 2)
1542 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1543
1544 id self(CYCastNSObject(pool, context, arguments[0]));
1545 if (self == nil)
1546 return CYJSNull(context);
1547
1548 SEL _cmd(CYCastSEL(context, arguments[1]));
1549
1550 Class _class(object_getClass(self));
1551 if (Method method = class_getInstanceMethod(_class, _cmd))
1552 type = method_getTypeEncoding(method);
1553 else {
1554 CYPoolTry {
1555 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1556 if (method == nil)
1557 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1558 type = CYPoolCString(pool, [method _typeString]);
1559 } CYPoolCatch(NULL)
1560 }
1561 } CYCatch
1562
1563 sig::Signature signature;
1564 sig::Parse(pool, &signature, type);
1565
1566 ffi_cif cif;
1567 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1568
1569 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1570 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1571}
1572
1573static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1574 JSValueRef setup[count + 2];
1575 setup[0] = _this;
1576 setup[1] = object;
1577 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1578 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1579}
1580
1581static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1582 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1583 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1584}
1585
1586JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1587 CYTry {
1588 if (count != 1)
1589 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1590 const char *name(CYCastCString(context, arguments[0]));
1591 return CYMakeSelector(context, sel_registerName(name));
1592 } CYCatch
1593}
1594
1595JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1596 CYTry {
1597 if (count != 2)
1598 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1599 const char *type(CYCastCString(context, arguments[1]));
1600 JSValueRef exception(NULL);
1601 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1602 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1603 return CYMakeFunctor(context, function, type);
1604 } else if (exception != NULL) {
1605 return NULL;
1606 } else {
1607 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1608 return CYMakeFunctor(context, function, type);
1609 }
1610 } CYCatch
1611}
1612
1613JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1614 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1615 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1616}
1617
1618JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1619 return Function_;
1620}
1621
1622static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1623 CYTry {
1624 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1625 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1626 } CYCatch
1627}
1628
1629static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1630 CYTry {
1631 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1632 CYPoolTry {
1633 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1634 } CYPoolCatch(NULL)
1635 } CYCatch
1636}
1637
1638static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1639 CYTry {
1640 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1641 return CYCastJSValue(context, sel_getName(data->GetValue()));
1642 } CYCatch
1643}
1644
1645static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1646 CYTry {
1647 if (count != 2)
1648 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1649 CYPool pool;
1650 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1651 Class _class(CYCastNSObject(pool, context, arguments[0]));
1652 bool instance(CYCastBool(context, arguments[1]));
1653 SEL sel(data->GetValue());
1654 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1655 return CYCastJSValue(context, method_getTypeEncoding(method));
1656 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1657 return CYCastJSValue(context, CYJSString(type));
1658 else
1659 return CYJSNull(context);
1660 } CYCatch
1661}
1662
1663static JSStaticValue Pointer_staticValues[2] = {
1664 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1665 {NULL, NULL, NULL, 0}
1666};
1667
1668static JSStaticFunction Pointer_staticFunctions[2] = {
1669 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1670 {NULL, NULL, 0}
1671};
1672
1673/*static JSStaticValue Selector_staticValues[2] = {
1674 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1675 {NULL, NULL, NULL, 0}
1676};*/
1677
1678static JSStaticFunction Instance_staticFunctions[2] = {
1679 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1680 {NULL, NULL, 0}
1681};
1682
1683static JSStaticFunction Selector_staticFunctions[3] = {
1684 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1685 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1686 {NULL, NULL, 0}
1687};
1688
1689CYDriver::CYDriver(const std::string &filename) :
1690 state_(CYClear),
1691 data_(NULL),
1692 size_(0),
1693 filename_(filename),
1694 source_(NULL)
1695{
1696 ScannerInit();
1697}
1698
1699CYDriver::~CYDriver() {
1700 ScannerDestroy();
1701}
1702
1703void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1704 CYDriver::Error error;
1705 error.location_ = location;
1706 error.message_ = message;
1707 driver.errors_.push_back(error);
1708}
1709
1710void CYSetArgs(int argc, const char *argv[]) {
1711 JSContextRef context(CYGetJSContext());
1712 JSValueRef args[argc];
1713 for (int i(0); i != argc; ++i)
1714 args[i] = CYCastJSValue(context, argv[i]);
1715 JSValueRef exception(NULL);
1716 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1717 CYThrow(context, exception);
1718 CYSetProperty(context, System_, CYJSString("args"), array);
1719}
1720
1721JSObjectRef CYGetGlobalObject(JSContextRef context) {
1722 return JSContextGetGlobalObject(context);
1723}
1724
1725MSInitialize { _pooled
1726 apr_initialize();
1727
1728 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1729
1730 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1731
1732 pid_t pid(getpid());
1733
1734 struct sockaddr_in address;
1735 address.sin_len = sizeof(address);
1736 address.sin_family = AF_INET;
1737 address.sin_addr.s_addr = INADDR_ANY;
1738 address.sin_port = htons(10000 + pid);
1739
1740 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1741
1742 CFSocketSignature signature;
1743 signature.protocolFamily = AF_INET;
1744 signature.socketType = SOCK_STREAM;
1745 signature.protocol = IPPROTO_TCP;
1746 signature.address = data;
1747
1748 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1749 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1750
1751 JSClassDefinition definition;
1752
1753 definition = kJSClassDefinitionEmpty;
1754 definition.className = "Pointer";
1755 definition.staticValues = Pointer_staticValues;
1756 definition.staticFunctions = Pointer_staticFunctions;
1757 definition.finalize = &CYData::Finalize;
1758 Pointer_ = JSClassCreate(&definition);
1759
1760 definition = kJSClassDefinitionEmpty;
1761 definition.className = "Functor";
1762 definition.staticValues = Pointer_staticValues;
1763 definition.staticFunctions = Pointer_staticFunctions;
1764 definition.callAsFunction = &Functor_callAsFunction;
1765 definition.finalize = &CYData::Finalize;
1766 Functor_ = JSClassCreate(&definition);
1767
1768 definition = kJSClassDefinitionEmpty;
1769 definition.className = "Struct";
1770 definition.getProperty = &Struct_getProperty;
1771 definition.setProperty = &Struct_setProperty;
1772 definition.finalize = &CYData::Finalize;
1773 Struct_ = JSClassCreate(&definition);
1774
1775 definition = kJSClassDefinitionEmpty;
1776 definition.className = "Selector";
1777 definition.staticValues = Pointer_staticValues;
1778 //definition.staticValues = Selector_staticValues;
1779 definition.staticFunctions = Selector_staticFunctions;
1780 definition.callAsFunction = &Selector_callAsFunction;
1781 definition.finalize = &CYData::Finalize;
1782 Selector_ = JSClassCreate(&definition);
1783
1784 definition = kJSClassDefinitionEmpty;
1785 definition.className = "Instance";
1786 definition.staticValues = Pointer_staticValues;
1787 definition.staticFunctions = Instance_staticFunctions;
1788 definition.getProperty = &Instance_getProperty;
1789 definition.setProperty = &Instance_setProperty;
1790 definition.deleteProperty = &Instance_deleteProperty;
1791 definition.callAsConstructor = &Instance_callAsConstructor;
1792 definition.finalize = &CYData::Finalize;
1793 Instance_ = JSClassCreate(&definition);
1794
1795 definition = kJSClassDefinitionEmpty;
1796 definition.className = "Runtime";
1797 definition.getProperty = &Runtime_getProperty;
1798 Runtime_ = JSClassCreate(&definition);
1799
1800 definition = kJSClassDefinitionEmpty;
1801 //definition.getProperty = &Global_getProperty;
1802 JSClassRef Global(JSClassCreate(&definition));
1803
1804 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1805 Context_ = context;
1806
1807 JSObjectRef global(CYGetGlobalObject(context));
1808
1809 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1810 CYSetProperty(context, global, CYJSString("ObjectiveC"), JSObjectMake(context, Runtime_, NULL));
1811
1812 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1813 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1814
1815 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1816 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1817
1818 System_ = JSObjectMake(context, NULL, NULL);
1819 CYSetProperty(context, global, CYJSString("system"), System_);
1820 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1821 //CYSetProperty(context, System_, CYJSString("global"), global);
1822
1823 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1824
1825 name_ = JSStringCreateWithUTF8CString("name");
1826 message_ = JSStringCreateWithUTF8CString("message");
1827 length_ = JSStringCreateWithUTF8CString("length");
1828
1829 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1830 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1831}