]> git.saurik.com Git - cycript.git/blob - Library.mm
Output all message declarations (not just one or the first and last), flesh out some...
[cycript.git] / Library.mm
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
103 static JSGlobalContextRef Context_;
104 static JSObjectRef System_;
105
106 static JSClassRef Functor_;
107 static JSClassRef Instance_;
108 static JSClassRef Pointer_;
109 static JSClassRef Runtime_;
110 static JSClassRef Selector_;
111 static JSClassRef Struct_;
112
113 static JSObjectRef Array_;
114 static JSObjectRef Function_;
115
116 static JSStringRef name_;
117 static JSStringRef message_;
118 static JSStringRef length_;
119
120 static Class NSCFBoolean_;
121
122 static NSArray *Bridge_;
123
124 struct Client {
125 CFHTTPMessageRef message_;
126 CFSocketRef socket_;
127 };
128
129 struct 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
150 struct 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
165 struct 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
179 struct 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
191 struct 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
202 struct 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
222 namespace sig {
223
224 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
225
226 void 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
237 void 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
245 void 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
262 void 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
287 struct 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
320 struct Struct_privateData :
321 Pointer_privateData
322 {
323 JSObjectRef owner_;
324 Type_privateData *type_;
325
326 Struct_privateData() {
327 }
328 };
329
330 struct 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
338 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
339 static TypeMap Types_;
340
341 JSObjectRef 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
362 JSObjectRef 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
369 const 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
381 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
382 return JSValueMakeBoolean(context, value);
383 }
384
385 JSValueRef 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
394 CYCastJSValue_(int)
395 CYCastJSValue_(unsigned int)
396 CYCastJSValue_(long int)
397 CYCastJSValue_(long unsigned int)
398 CYCastJSValue_(long long int)
399 CYCastJSValue_(long long unsigned int)
400
401 JSValueRef 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
653 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
654 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
655
656 JSGlobalContextRef CYGetJSContext() {
657 return Context_;
658 }
659
660 #define CYTry \
661 @try
662 #define CYCatch \
663 @catch (id error) { \
664 NSLog(@"e:%@", error); \
665 CYThrow(context, error, exception); \
666 return NULL; \
667 }
668
669 void CYThrow(JSContextRef context, JSValueRef value);
670
671 apr_status_t CYPoolRelease_(void *data) {
672 id object(reinterpret_cast<id>(data));
673 [object release];
674 return APR_SUCCESS;
675 }
676
677 id CYPoolRelease(apr_pool_t *pool, id object) {
678 if (pool == NULL)
679 return [object autorelease];
680 else {
681 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
682 return object;
683 }
684 }
685
686 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
687 return (CFTypeRef) CYPoolRelease(pool, (id) object);
688 }
689
690 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
691 if (JSValueIsObjectOfClass(context, object, Instance_)) {
692 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
693 return data->GetValue();
694 }
695
696 JSValueRef exception(NULL);
697 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
698 CYThrow(context, exception);
699 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
700 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
701 }
702
703 JSStringRef CYCopyJSString(id value) {
704 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
705 }
706
707 JSStringRef CYCopyJSString(const char *value) {
708 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
709 }
710
711 JSStringRef CYCopyJSString(JSStringRef value) {
712 return value == NULL ? NULL : JSStringRetain(value);
713 }
714
715 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
716 if (JSValueIsNull(context, value))
717 return NULL;
718 JSValueRef exception(NULL);
719 JSStringRef string(JSValueToStringCopy(context, value, &exception));
720 CYThrow(context, exception);
721 return string;
722 }
723
724 class CYJSString {
725 private:
726 JSStringRef string_;
727
728 void Clear_() {
729 JSStringRelease(string_);
730 }
731
732 public:
733 CYJSString(const CYJSString &rhs) :
734 string_(CYCopyJSString(rhs.string_))
735 {
736 }
737
738 template <typename Arg0_>
739 CYJSString(Arg0_ arg0) :
740 string_(CYCopyJSString(arg0))
741 {
742 }
743
744 template <typename Arg0_, typename Arg1_>
745 CYJSString(Arg0_ arg0, Arg1_ arg1) :
746 string_(CYCopyJSString(arg0, arg1))
747 {
748 }
749
750 CYJSString &operator =(const CYJSString &rhs) {
751 Clear_();
752 string_ = CYCopyJSString(rhs.string_);
753 return *this;
754 }
755
756 ~CYJSString() {
757 Clear_();
758 }
759
760 void Clear() {
761 Clear_();
762 string_ = NULL;
763 }
764
765 operator JSStringRef() const {
766 return string_;
767 }
768 };
769
770 CFStringRef CYCopyCFString(JSStringRef value) {
771 return JSStringCopyCFString(kCFAllocatorDefault, value);
772 }
773
774 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
775 return CYCopyCFString(CYJSString(context, value));
776 }
777
778 double CYCastDouble(const char *value, size_t size) {
779 char *end;
780 double number(strtod(value, &end));
781 if (end != value + size)
782 return NAN;
783 return number;
784 }
785
786 double CYCastDouble(const char *value) {
787 return CYCastDouble(value, strlen(value));
788 }
789
790 double CYCastDouble(JSContextRef context, JSValueRef value) {
791 JSValueRef exception(NULL);
792 double number(JSValueToNumber(context, value, &exception));
793 CYThrow(context, exception);
794 return number;
795 }
796
797 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
798 double number(CYCastDouble(context, value));
799 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
800 }
801
802 CFStringRef CYCopyCFString(const char *value) {
803 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
804 }
805
806 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
807 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
808 }
809
810 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
811 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
812 }
813
814 bool CYCastBool(JSContextRef context, JSValueRef value) {
815 return JSValueToBoolean(context, value);
816 }
817
818 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
819 CFTypeRef object;
820 bool copy;
821
822 switch (JSType type = JSValueGetType(context, value)) {
823 case kJSTypeUndefined:
824 object = [WebUndefined undefined];
825 copy = false;
826 break;
827
828 case kJSTypeNull:
829 return NULL;
830 break;
831
832 case kJSTypeBoolean:
833 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
834 copy = false;
835 break;
836
837 case kJSTypeNumber:
838 object = CYCopyCFNumber(context, value);
839 copy = true;
840 break;
841
842 case kJSTypeString:
843 object = CYCopyCFString(context, value);
844 copy = true;
845 break;
846
847 case kJSTypeObject:
848 // XXX: this might could be more efficient
849 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
850 copy = false;
851 break;
852
853 default:
854 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
855 break;
856 }
857
858 if (cast != copy)
859 return object;
860 else if (copy)
861 return CYPoolRelease(pool, object);
862 else
863 return CFRetain(object);
864 }
865
866 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
867 return CYCFType(pool, context, value, true);
868 }
869
870 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
871 return CYCFType(pool, context, value, false);
872 }
873
874 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
875 CYPool pool;
876 size_t size(JSPropertyNameArrayGetCount(names));
877 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
878 for (size_t index(0); index != size; ++index)
879 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
880 return array;
881 }
882
883 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
884 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
885 }
886
887 void CYThrow(JSContextRef context, JSValueRef value) {
888 if (value == NULL)
889 return;
890 @throw CYCastNSObject(NULL, context, value);
891 }
892
893 JSValueRef CYJSNull(JSContextRef context) {
894 return JSValueMakeNull(context);
895 }
896
897 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
898 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
899 }
900
901 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
902 return CYCastJSValue(context, CYJSString(value));
903 }
904
905 JSValueRef CYCastJSValue(JSContextRef context, id value, bool transient = true) {
906 return value == nil ? CYJSNull(context) : [value cy$JSValueInContext:context transient:transient];
907 }
908
909 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
910 JSValueRef exception(NULL);
911 JSObjectRef object(JSValueToObject(context, value, &exception));
912 CYThrow(context, exception);
913 return object;
914 }
915
916 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
917 JSValueRef exception(NULL);
918 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
919 CYThrow(context, exception);
920 return value;
921 }
922
923 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
924 JSValueRef exception(NULL);
925 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
926 CYThrow(context, exception);
927 return value;
928 }
929
930 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
931 JSValueRef exception(NULL);
932 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
933 CYThrow(context, exception);
934 }
935
936 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
937 if (exception == NULL)
938 throw error;
939 *exception = CYCastJSValue(context, error);
940 }
941
942 @implementation CYJSObject
943
944 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
945 if ((self = [super init]) != nil) {
946 object_ = object;
947 context_ = context;
948 } return self;
949 }
950
951 - (NSUInteger) count {
952 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
953 size_t size(JSPropertyNameArrayGetCount(names));
954 JSPropertyNameArrayRelease(names);
955 return size;
956 }
957
958 - (id) objectForKey:(id)key {
959 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
960 }
961
962 - (NSEnumerator *) keyEnumerator {
963 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
964 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
965 JSPropertyNameArrayRelease(names);
966 return enumerator;
967 }
968
969 - (void) setObject:(id)object forKey:(id)key {
970 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
971 }
972
973 - (void) removeObjectForKey:(id)key {
974 JSValueRef exception(NULL);
975 // XXX: this returns a bool... throw exception, or ignore?
976 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
977 CYThrow(context_, exception);
978 }
979
980 @end
981
982 @implementation CYJSArray
983
984 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
985 if ((self = [super init]) != nil) {
986 object_ = object;
987 context_ = context;
988 } return self;
989 }
990
991 - (NSUInteger) count {
992 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
993 }
994
995 - (id) objectAtIndex:(NSUInteger)index {
996 JSValueRef exception(NULL);
997 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
998 CYThrow(context_, exception);
999 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1000 }
1001
1002 @end
1003
1004 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1005 CYTry {
1006 CYPoolTry {
1007 id object(CYCastNSObject(NULL, context, value));
1008 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
1009 } CYPoolCatch(NULL)
1010 } CYCatch
1011 }
1012
1013 const char *CYPoolJSONString(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1014 if (NSString *json = (NSString *) CYCopyJSONString(context, value, exception)) {
1015 const char *string(CYPoolCString(pool, json));
1016 [json release];
1017 return string;
1018 } else return NULL;
1019 }
1020
1021 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1022 switch (type) {
1023 case kCFSocketDataCallBack:
1024 CFDataRef data(reinterpret_cast<CFDataRef>(value));
1025 Client *client(reinterpret_cast<Client *>(info));
1026
1027 if (client->message_ == NULL)
1028 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
1029
1030 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
1031 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
1032 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
1033 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
1034 Boolean absolute;
1035 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
1036 CFRelease(client->message_);
1037
1038 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
1039 CFRelease(path);
1040
1041 JSStringRef script(JSStringCreateWithCFString(code));
1042 CFRelease(code);
1043
1044 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
1045 JSStringRelease(script);
1046
1047 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
1048 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
1049
1050 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result, NULL));
1051 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
1052 CFRelease(json);
1053
1054 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
1055 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
1056 CFRelease(length);
1057
1058 CFHTTPMessageSetBody(response, body);
1059 CFRelease(body);
1060
1061 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
1062 CFRelease(response);
1063
1064 CFSocketSendData(socket, NULL, serialized, 0);
1065 CFRelease(serialized);
1066
1067 CFRelease(url);
1068 }
1069 break;
1070 }
1071 }
1072
1073 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
1074 switch (type) {
1075 case kCFSocketAcceptCallBack:
1076 Client *client(new Client());
1077
1078 client->message_ = NULL;
1079
1080 CFSocketContext context;
1081 context.version = 0;
1082 context.info = client;
1083 context.retain = NULL;
1084 context.release = NULL;
1085 context.copyDescription = NULL;
1086
1087 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
1088
1089 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
1090 break;
1091 }
1092 }
1093
1094 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1095 CYTry {
1096 CYPool pool;
1097 NSString *self(CYCastNSObject(pool, context, object));
1098 NSString *name(CYCastNSString(pool, property));
1099 NSObject *data([self cy$getProperty:name]);
1100 return data == nil ? NULL : CYCastJSValue(context, data);
1101 } CYCatch
1102 }
1103
1104 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1105 CYTry {
1106 CYPool pool;
1107 NSString *self(CYCastNSObject(pool, context, object));
1108 NSString *name(CYCastNSString(pool, property));
1109 NSString *data(CYCastNSObject(pool, context, value));
1110 return [self cy$setProperty:name to:data];
1111 } CYCatch
1112 }
1113
1114 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1115 CYTry {
1116 CYPool pool;
1117 NSString *self(CYCastNSObject(pool, context, object));
1118 NSString *name(CYCastNSString(pool, property));
1119 return [self cy$deleteProperty:name];
1120 } CYCatch
1121 }
1122
1123 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1124 CYTry {
1125 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(object)));
1126 return CYMakeInstance(context, [data->GetValue() alloc], true);
1127 } CYCatch
1128 }
1129
1130 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1131 Selector_privateData *data(new Selector_privateData(sel));
1132 return JSObjectMake(context, Selector_, data);
1133 }
1134
1135 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
1136 Pointer_privateData *data(new Pointer_privateData(pointer));
1137 return JSObjectMake(context, Pointer_, data);
1138 }
1139
1140 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1141 Functor_privateData *data(new Functor_privateData(type, function));
1142 return JSObjectMake(context, Functor_, data);
1143 }
1144
1145 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value, size_t *length = NULL) {
1146 if (pool == NULL) {
1147 const char *string([CYCastNSString(NULL, value) UTF8String]);
1148 if (length != NULL)
1149 *length = strlen(string);
1150 return string;
1151 } else {
1152 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1153 char *string(new(pool) char[size]);
1154 JSStringGetUTF8CString(value, string, size);
1155 // XXX: this is ironic
1156 if (length != NULL)
1157 *length = strlen(string);
1158 return string;
1159 }
1160 }
1161
1162 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value, size_t *length = NULL) {
1163 if (!JSValueIsNull(context, value))
1164 return CYPoolCString(pool, CYJSString(context, value), length);
1165 else {
1166 if (length != NULL)
1167 *length = 0;
1168 return NULL;
1169 }
1170 }
1171
1172 // XXX: this macro is unhygenic
1173 #define CYCastCString(context, value) ({ \
1174 char *utf8; \
1175 if (value == NULL) \
1176 utf8 = NULL; \
1177 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1178 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1179 utf8 = reinterpret_cast<char *>(alloca(size)); \
1180 JSStringGetUTF8CString(string, utf8, size); \
1181 JSStringRelease(string); \
1182 } else \
1183 utf8 = NULL; \
1184 utf8; \
1185 })
1186
1187 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1188 if (JSValueIsNull(context, value))
1189 return NULL;
1190 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
1191 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1192 return reinterpret_cast<SEL>(data->value_);
1193 } else
1194 return sel_registerName(CYCastCString(context, value));
1195 }
1196
1197 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1198 switch (JSValueGetType(context, value)) {
1199 case kJSTypeNull:
1200 return NULL;
1201 /*case kJSTypeString:
1202 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1203 case kJSTypeObject:
1204 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1205 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1206 return data->value_;
1207 }*/
1208 default:
1209 double number(CYCastDouble(context, value));
1210 if (std::isnan(number))
1211 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1212 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1213 }
1214 }
1215
1216 template <typename Type_>
1217 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1218 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1219 }
1220
1221 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1222 switch (type->primitive) {
1223 case sig::boolean_P:
1224 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1225 break;
1226
1227 #define CYPoolFFI_(primitive, native) \
1228 case sig::primitive ## _P: \
1229 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1230 break;
1231
1232 CYPoolFFI_(uchar, unsigned char)
1233 CYPoolFFI_(char, char)
1234 CYPoolFFI_(ushort, unsigned short)
1235 CYPoolFFI_(short, short)
1236 CYPoolFFI_(ulong, unsigned long)
1237 CYPoolFFI_(long, long)
1238 CYPoolFFI_(uint, unsigned int)
1239 CYPoolFFI_(int, int)
1240 CYPoolFFI_(ulonglong, unsigned long long)
1241 CYPoolFFI_(longlong, long long)
1242 CYPoolFFI_(float, float)
1243 CYPoolFFI_(double, double)
1244
1245 case sig::object_P:
1246 case sig::typename_P:
1247 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1248 break;
1249
1250 case sig::selector_P:
1251 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1252 break;
1253
1254 case sig::pointer_P:
1255 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1256 break;
1257
1258 case sig::string_P:
1259 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1260 break;
1261
1262 case sig::struct_P: {
1263 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1264 bool aggregate(JSValueIsObject(context, value));
1265 for (size_t index(0); index != type->data.signature.count; ++index) {
1266 ffi_type *element(ffi->elements[index]);
1267 JSValueRef rhs(aggregate ? CYGetProperty(context, (JSObjectRef) value, index) : value);
1268 CYPoolFFI(pool, context, type->data.signature.elements[index].type, element, base, rhs);
1269 // XXX: alignment?
1270 base += element->size;
1271 }
1272 } break;
1273
1274 case sig::void_P:
1275 break;
1276
1277 default:
1278 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1279 _assert(false);
1280 }
1281 }
1282
1283 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSObjectRef owner = NULL) {
1284 JSValueRef value;
1285
1286 switch (type->primitive) {
1287 case sig::boolean_P:
1288 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1289 break;
1290
1291 #define CYFromFFI_(primitive, native) \
1292 case sig::primitive ## _P: \
1293 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1294 break;
1295
1296 CYFromFFI_(uchar, unsigned char)
1297 CYFromFFI_(char, char)
1298 CYFromFFI_(ushort, unsigned short)
1299 CYFromFFI_(short, short)
1300 CYFromFFI_(ulong, unsigned long)
1301 CYFromFFI_(long, long)
1302 CYFromFFI_(uint, unsigned int)
1303 CYFromFFI_(int, int)
1304 CYFromFFI_(ulonglong, unsigned long long)
1305 CYFromFFI_(longlong, long long)
1306 CYFromFFI_(float, float)
1307 CYFromFFI_(double, double)
1308
1309 case sig::object_P:
1310 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
1311 break;
1312
1313 case sig::typename_P:
1314 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1315 break;
1316
1317 case sig::selector_P:
1318 if (SEL sel = *reinterpret_cast<SEL *>(data))
1319 value = CYMakeSelector(context, sel);
1320 else goto null;
1321 break;
1322
1323 case sig::pointer_P:
1324 if (void *pointer = *reinterpret_cast<void **>(data))
1325 value = CYMakePointer(context, pointer);
1326 else goto null;
1327 break;
1328
1329 case sig::string_P:
1330 if (char *utf8 = *reinterpret_cast<char **>(data))
1331 value = CYCastJSValue(context, utf8);
1332 else goto null;
1333 break;
1334
1335 case sig::struct_P:
1336 value = CYMakeStruct(context, data, type, ffi, owner);
1337 break;
1338
1339 case sig::void_P:
1340 value = CYJSUndefined(context);
1341 break;
1342
1343 null:
1344 value = CYJSNull(context);
1345 break;
1346
1347 default:
1348 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1349 _assert(false);
1350 }
1351
1352 return value;
1353 }
1354
1355 void Index_(Struct_privateData *internal, double number, ssize_t &index, uint8_t *&base) {
1356 Type_privateData *typical(internal->type_);
1357
1358 index = static_cast<ssize_t>(number);
1359 if (index != number)
1360 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index non-integral" userInfo:nil];
1361 if (index < 0)
1362 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index negative" userInfo:nil];
1363
1364 base = reinterpret_cast<uint8_t *>(internal->value_);
1365 for (ssize_t local(0); local != index; ++local)
1366 if (ffi_type *element = typical->ffi_.elements[local])
1367 base += element->size;
1368 else
1369 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"struct index out-of-range" userInfo:nil];
1370 }
1371
1372 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1373 CYTry {
1374 CYPool pool;
1375 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1376 Type_privateData *typical(internal->type_);
1377
1378 size_t length;
1379 const char *name(CYPoolCString(pool, property, &length));
1380 double number(CYCastDouble(name, length));
1381
1382 if (std::isnan(number)) {
1383 // XXX: implement!
1384 return NULL;
1385 }
1386
1387 ssize_t index;
1388 uint8_t *base;
1389
1390 Index_(internal, number, index, base);
1391
1392 return CYFromFFI(context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, object);
1393 } CYCatch
1394 }
1395
1396 static 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 size_t length;
1403 const char *name(CYPoolCString(pool, property, &length));
1404 double number(CYCastDouble(name, length));
1405
1406 if (std::isnan(number)) {
1407 // XXX: implement!
1408 return false;
1409 }
1410
1411 ssize_t index;
1412 uint8_t *base;
1413
1414 Index_(internal, number, index, base);
1415
1416 CYPoolFFI(NULL, context, typical->type_.data.signature.elements[index].type, typical->ffi_.elements[index], base, value);
1417 return true;
1418 } CYCatch
1419 }
1420
1421 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1422 CYTry {
1423 if (count != signature->count - 1)
1424 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1425
1426 CYPool pool;
1427 void *values[count];
1428
1429 for (unsigned index(0); index != count; ++index) {
1430 sig::Element *element(&signature->elements[index + 1]);
1431 ffi_type *ffi(cif->arg_types[index]);
1432 // XXX: alignment?
1433 values[index] = new(pool) uint8_t[ffi->size];
1434 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index]);
1435 }
1436
1437 uint8_t value[cif->rtype->size];
1438 ffi_call(cif, function, value, values);
1439
1440 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value);
1441 } CYCatch
1442 }
1443
1444 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1445 ffoData *data(reinterpret_cast<ffoData *>(arg));
1446
1447 JSContextRef context(data->context_);
1448
1449 size_t count(data->cif_.nargs);
1450 JSValueRef values[count];
1451
1452 for (size_t index(0); index != count; ++index)
1453 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1454
1455 JSValueRef exception(NULL);
1456 JSValueRef value(JSObjectCallAsFunction(context, data->function_, NULL, count, values, &exception));
1457 CYThrow(context, exception);
1458
1459 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1460 }
1461
1462 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1463 // XXX: in case of exceptions this will leak
1464 ffoData *data(new ffoData(type));
1465
1466 ffi_closure *closure;
1467 _syscall(closure = (ffi_closure *) mmap(
1468 NULL, sizeof(ffi_closure),
1469 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1470 -1, 0
1471 ));
1472
1473 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1474 _assert(status == FFI_OK);
1475
1476 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1477
1478 data->value_ = closure;
1479
1480 data->context_ = CYGetJSContext();
1481 data->function_ = function;
1482
1483 return JSObjectMake(context, Functor_, data);
1484 }
1485
1486 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1487 CYTry {
1488 CYPool pool;
1489 NSString *name(CYCastNSString(pool, property));
1490 if (Class _class = NSClassFromString(name))
1491 return CYMakeInstance(context, _class, true);
1492 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
1493 switch ([[entry objectAtIndex:0] intValue]) {
1494 case 0:
1495 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
1496 case 1:
1497 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
1498 case 2:
1499 // XXX: this is horrendously inefficient
1500 sig::Signature signature;
1501 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]));
1502 ffi_cif cif;
1503 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1504 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
1505 }
1506 return NULL;
1507 } CYCatch
1508 }
1509
1510 bool stret(ffi_type *ffi_type) {
1511 return ffi_type->type == FFI_TYPE_STRUCT && (
1512 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
1513 struct_forward_array[ffi_type->size] != 0
1514 );
1515 }
1516
1517 extern "C" {
1518 int *_NSGetArgc(void);
1519 char ***_NSGetArgv(void);
1520 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
1521 }
1522
1523 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1524 CYTry {
1525 NSLog(@"%s", CYCastCString(context, arguments[0]));
1526 return CYJSUndefined(context);
1527 } CYCatch
1528 }
1529
1530 static JSValueRef CYApplicationMain(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1531 CYTry {
1532 CYPool pool;
1533 NSString *name(CYCastNSObject(pool, context, arguments[0]));
1534 int argc(*_NSGetArgc());
1535 char **argv(*_NSGetArgv());
1536 for (int i(0); i != argc; ++i)
1537 NSLog(@"argv[%i]=%s", i, argv[i]);
1538 _pooled
1539 return CYCastJSValue(context, UIApplicationMain(argc, argv, name, name));
1540 } CYCatch
1541 }
1542
1543 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1544 const char *type;
1545
1546 CYPool pool;
1547
1548 CYTry {
1549 if (count < 2)
1550 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
1551
1552 id self(CYCastNSObject(pool, context, arguments[0]));
1553 if (self == nil)
1554 return CYJSNull(context);
1555
1556 SEL _cmd(CYCastSEL(context, arguments[1]));
1557
1558 Class _class(object_getClass(self));
1559 if (Method method = class_getInstanceMethod(_class, _cmd))
1560 type = method_getTypeEncoding(method);
1561 else {
1562 CYPoolTry {
1563 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
1564 if (method == nil)
1565 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
1566 type = CYPoolCString(pool, [method _typeString]);
1567 } CYPoolCatch(NULL)
1568 }
1569 } CYCatch
1570
1571 sig::Signature signature;
1572 sig::Parse(pool, &signature, type);
1573
1574 ffi_cif cif;
1575 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1576
1577 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
1578 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
1579 }
1580
1581 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1582 JSValueRef setup[count + 2];
1583 setup[0] = _this;
1584 setup[1] = object;
1585 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
1586 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
1587 }
1588
1589 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1590 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
1591 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
1592 }
1593
1594 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1595 CYTry {
1596 if (count != 1)
1597 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
1598 const char *name(CYCastCString(context, arguments[0]));
1599 return CYMakeSelector(context, sel_registerName(name));
1600 } CYCatch
1601 }
1602
1603 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1604 CYTry {
1605 if (count != 2)
1606 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
1607 const char *type(CYCastCString(context, arguments[1]));
1608 JSValueRef exception(NULL);
1609 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
1610 JSObjectRef function(CYCastJSObject(context, arguments[0]));
1611 return CYMakeFunctor(context, function, type);
1612 } else if (exception != NULL) {
1613 return NULL;
1614 } else {
1615 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
1616 return CYMakeFunctor(context, function, type);
1617 }
1618 } CYCatch
1619 }
1620
1621 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1622 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(object)));
1623 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1624 }
1625
1626 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1627 return Function_;
1628 }
1629
1630 static JSValueRef Pointer_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1631 CYTry {
1632 Pointer_privateData *data(reinterpret_cast<Pointer_privateData *>(JSObjectGetPrivate(_this)));
1633 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(data->value_));
1634 } CYCatch
1635 }
1636
1637 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1638 CYTry {
1639 Instance_privateData *data(reinterpret_cast<Instance_privateData *>(JSObjectGetPrivate(_this)));
1640 CYPoolTry {
1641 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
1642 } CYPoolCatch(NULL)
1643 } CYCatch
1644 }
1645
1646 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1647 CYTry {
1648 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1649 return CYCastJSValue(context, sel_getName(data->GetValue()));
1650 } CYCatch
1651 }
1652
1653 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1654 CYTry {
1655 if (count != 2)
1656 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
1657 CYPool pool;
1658 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
1659 Class _class(CYCastNSObject(pool, context, arguments[0]));
1660 bool instance(CYCastBool(context, arguments[1]));
1661 SEL sel(data->GetValue());
1662 if (Method method = (*(instance ? &class_getInstanceMethod : class_getClassMethod))(_class, sel))
1663 return CYCastJSValue(context, method_getTypeEncoding(method));
1664 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1665 return CYCastJSValue(context, CYJSString(type));
1666 else
1667 return CYJSNull(context);
1668 } CYCatch
1669 }
1670
1671 static JSStaticValue Pointer_staticValues[2] = {
1672 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1673 {NULL, NULL, NULL, 0}
1674 };
1675
1676 static JSStaticFunction Pointer_staticFunctions[2] = {
1677 {"valueOf", &Pointer_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1678 {NULL, NULL, 0}
1679 };
1680
1681 /*static JSStaticValue Selector_staticValues[2] = {
1682 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
1683 {NULL, NULL, NULL, 0}
1684 };*/
1685
1686 static JSStaticFunction Instance_staticFunctions[2] = {
1687 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1688 {NULL, NULL, 0}
1689 };
1690
1691 static JSStaticFunction Selector_staticFunctions[3] = {
1692 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1693 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1694 {NULL, NULL, 0}
1695 };
1696
1697 CYDriver::CYDriver(const std::string &filename) :
1698 state_(CYClear),
1699 data_(NULL),
1700 size_(0),
1701 filename_(filename),
1702 source_(NULL)
1703 {
1704 ScannerInit();
1705 }
1706
1707 CYDriver::~CYDriver() {
1708 ScannerDestroy();
1709 }
1710
1711 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
1712 CYDriver::Error error;
1713 error.location_ = location;
1714 error.message_ = message;
1715 driver.errors_.push_back(error);
1716 }
1717
1718 void CYSetArgs(int argc, const char *argv[]) {
1719 JSContextRef context(CYGetJSContext());
1720 JSValueRef args[argc];
1721 for (int i(0); i != argc; ++i)
1722 args[i] = CYCastJSValue(context, argv[i]);
1723 JSValueRef exception(NULL);
1724 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
1725 CYThrow(context, exception);
1726 CYSetProperty(context, System_, CYJSString("args"), array);
1727 }
1728
1729 MSInitialize { _pooled
1730 apr_initialize();
1731
1732 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1733
1734 NSCFBoolean_ = objc_getClass("NSCFBoolean");
1735
1736 pid_t pid(getpid());
1737
1738 struct sockaddr_in address;
1739 address.sin_len = sizeof(address);
1740 address.sin_family = AF_INET;
1741 address.sin_addr.s_addr = INADDR_ANY;
1742 address.sin_port = htons(10000 + pid);
1743
1744 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
1745
1746 CFSocketSignature signature;
1747 signature.protocolFamily = AF_INET;
1748 signature.socketType = SOCK_STREAM;
1749 signature.protocol = IPPROTO_TCP;
1750 signature.address = data;
1751
1752 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1753 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1754
1755 JSClassDefinition definition;
1756
1757 definition = kJSClassDefinitionEmpty;
1758 definition.className = "Pointer";
1759 definition.staticValues = Pointer_staticValues;
1760 definition.staticFunctions = Pointer_staticFunctions;
1761 definition.finalize = &CYData::Finalize;
1762 Pointer_ = JSClassCreate(&definition);
1763
1764 definition = kJSClassDefinitionEmpty;
1765 definition.className = "Functor";
1766 definition.staticValues = Pointer_staticValues;
1767 definition.staticFunctions = Pointer_staticFunctions;
1768 definition.callAsFunction = &Functor_callAsFunction;
1769 definition.finalize = &CYData::Finalize;
1770 Functor_ = JSClassCreate(&definition);
1771
1772 definition = kJSClassDefinitionEmpty;
1773 definition.className = "Struct";
1774 definition.getProperty = &Struct_getProperty;
1775 definition.setProperty = &Struct_setProperty;
1776 definition.finalize = &CYData::Finalize;
1777 Struct_ = JSClassCreate(&definition);
1778
1779 definition = kJSClassDefinitionEmpty;
1780 definition.className = "Selector";
1781 definition.staticValues = Pointer_staticValues;
1782 //definition.staticValues = Selector_staticValues;
1783 definition.staticFunctions = Selector_staticFunctions;
1784 definition.callAsFunction = &Selector_callAsFunction;
1785 definition.finalize = &CYData::Finalize;
1786 Selector_ = JSClassCreate(&definition);
1787
1788 definition = kJSClassDefinitionEmpty;
1789 definition.className = "Instance";
1790 definition.staticValues = Pointer_staticValues;
1791 definition.staticFunctions = Instance_staticFunctions;
1792 definition.getProperty = &Instance_getProperty;
1793 definition.setProperty = &Instance_setProperty;
1794 definition.deleteProperty = &Instance_deleteProperty;
1795 definition.callAsConstructor = &Instance_callAsConstructor;
1796 definition.finalize = &CYData::Finalize;
1797 Instance_ = JSClassCreate(&definition);
1798
1799 definition = kJSClassDefinitionEmpty;
1800 definition.className = "Runtime";
1801 definition.getProperty = &Runtime_getProperty;
1802 Runtime_ = JSClassCreate(&definition);
1803
1804 definition = kJSClassDefinitionEmpty;
1805 //definition.getProperty = &Global_getProperty;
1806 JSClassRef Global(JSClassCreate(&definition));
1807
1808 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1809 Context_ = context;
1810
1811 JSObjectRef global(JSContextGetGlobalObject(context));
1812
1813 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1814 CYSetProperty(context, global, CYJSString("obc"), JSObjectMake(context, Runtime_, NULL));
1815
1816 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
1817 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
1818
1819 CYSetProperty(context, global, CYJSString("CYApplicationMain"), JSObjectMakeFunctionWithCallback(context, CYJSString("CYApplicationMain"), &CYApplicationMain));
1820 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1821
1822 System_ = JSObjectMake(context, NULL, NULL);
1823 CYSetProperty(context, global, CYJSString("system"), System_);
1824 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1825 CYSetProperty(context, System_, CYJSString("global"), global);
1826
1827 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1828
1829 name_ = JSStringCreateWithUTF8CString("name");
1830 message_ = JSStringCreateWithUTF8CString("message");
1831 length_ = JSStringCreateWithUTF8CString("length");
1832
1833 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1834 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1835 }