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