]> git.saurik.com Git - cycript.git/blob - Library.mm
a2f5891bd3f1093c9afd59fc45c8ec3b50eed224
[cycript.git] / Library.mm
1 /* Cycript - 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 <WebKit/WebScriptObject.h>
57
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <sys/un.h>
62
63 #include <sys/mman.h>
64
65 #include <iostream>
66 #include <ext/stdio_filebuf.h>
67 #include <set>
68 #include <map>
69
70 #include <sstream>
71 #include <cmath>
72
73 #include "Parser.hpp"
74 #include "Cycript.tab.hh"
75
76 #include <fcntl.h>
77
78 #include <apr-1/apr_thread_proc.h>
79
80 #undef _assert
81 #undef _trace
82
83 #define _assert(test) do { \
84 if (!(test)) \
85 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
86 } while (false)
87
88 #define _trace() do { \
89 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
90 } while (false)
91
92 #define CYPoolTry { \
93 id _saved(nil); \
94 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
95 @try
96 #define CYPoolCatch(value) \
97 @catch (NSException *error) { \
98 _saved = [error retain]; \
99 @throw; \
100 return value; \
101 } @finally { \
102 [_pool release]; \
103 if (_saved != nil) \
104 [_saved autorelease]; \
105 } \
106 }
107
108 static JSGlobalContextRef Context_;
109 static JSObjectRef System_;
110 static JSObjectRef ObjectiveC_;
111
112 static JSClassRef Functor_;
113 static JSClassRef Instance_;
114 static JSClassRef Pointer_;
115 static JSClassRef Runtime_;
116 static JSClassRef Selector_;
117 static JSClassRef Struct_;
118 static JSClassRef Type_;
119
120 static JSClassRef ObjectiveC_Classes_;
121 static JSClassRef ObjectiveC_Image_Classes_;
122 static JSClassRef ObjectiveC_Images_;
123 static JSClassRef ObjectiveC_Protocols_;
124
125 static JSObjectRef Array_;
126 static JSObjectRef Function_;
127
128 static JSStringRef Result_;
129
130 static JSStringRef length_;
131 static JSStringRef message_;
132 static JSStringRef name_;
133 static JSStringRef toCYON_;
134 static JSStringRef toJSON_;
135
136 static Class NSCFBoolean_;
137 static Class NSCFType_;
138 static Class NSMessageBuilder_;
139 static Class NSZombie_;
140 static Class Object_;
141
142 static NSArray *Bridge_;
143
144 struct CYData {
145 apr_pool_t *pool_;
146
147 virtual ~CYData() {
148 }
149
150 static void *operator new(size_t size, apr_pool_t *pool) {
151 void *data(apr_palloc(pool, size));
152 reinterpret_cast<CYData *>(data)->pool_ = pool;
153 return data;
154 }
155
156 static void *operator new(size_t size) {
157 apr_pool_t *pool;
158 apr_pool_create(&pool, NULL);
159 return operator new(size, pool);
160 }
161
162 static void operator delete(void *data) {
163 apr_pool_destroy(reinterpret_cast<CYData *>(data)->pool_);
164 }
165
166 static void Finalize(JSObjectRef object) {
167 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
168 }
169 };
170
171 struct CYValue :
172 CYData
173 {
174 void *value_;
175
176 CYValue() {
177 }
178
179 CYValue(void *value) :
180 value_(value)
181 {
182 }
183 };
184
185 struct Selector_privateData :
186 CYValue
187 {
188 Selector_privateData(SEL value) :
189 CYValue(value)
190 {
191 }
192
193 SEL GetValue() const {
194 return reinterpret_cast<SEL>(value_);
195 }
196 };
197
198 struct Instance :
199 CYValue
200 {
201 enum Flags {
202 None = 0,
203 Transient = (1 << 0),
204 Uninitialized = (1 << 1),
205 };
206
207 Flags flags_;
208
209 Instance(id value, Flags flags) :
210 CYValue(value),
211 flags_(flags)
212 {
213 }
214
215 virtual ~Instance() {
216 if ((flags_ & Transient) == 0)
217 // XXX: does this handle background threads correctly?
218 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
219 }
220
221 static JSObjectRef Make(JSContextRef context, id object, Flags flags) {
222 return JSObjectMake(context, Instance_, new Instance(object, flags));
223 }
224
225 id GetValue() const {
226 return reinterpret_cast<id>(value_);
227 }
228
229 bool IsUninitialized() const {
230 return (flags_ & Uninitialized) != 0;
231 }
232 };
233
234 namespace sig {
235
236 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
237
238 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
239 lhs.name = apr_pstrdup(pool, rhs.name);
240 if (rhs.type == NULL)
241 lhs.type = NULL;
242 else {
243 lhs.type = new(pool) Type;
244 Copy(pool, *lhs.type, *rhs.type);
245 }
246 lhs.offset = rhs.offset;
247 }
248
249 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
250 size_t count(rhs.count);
251 lhs.count = count;
252 lhs.elements = new(pool) Element[count];
253 for (size_t index(0); index != count; ++index)
254 Copy(pool, lhs.elements[index], rhs.elements[index]);
255 }
256
257 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
258 lhs.primitive = rhs.primitive;
259 lhs.name = apr_pstrdup(pool, rhs.name);
260 lhs.flags = rhs.flags;
261
262 if (sig::IsAggregate(rhs.primitive))
263 Copy(pool, lhs.data.signature, rhs.data.signature);
264 else {
265 if (rhs.data.data.type != NULL) {
266 lhs.data.data.type = new(pool) Type;
267 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
268 }
269
270 lhs.data.data.size = rhs.data.data.size;
271 }
272 }
273
274 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
275 lhs.size = rhs.size;
276 lhs.alignment = rhs.alignment;
277 lhs.type = rhs.type;
278 if (rhs.elements == NULL)
279 lhs.elements = NULL;
280 else {
281 size_t count(0);
282 while (rhs.elements[count] != NULL)
283 ++count;
284
285 lhs.elements = new(pool) ffi_type *[count + 1];
286 lhs.elements[count] = NULL;
287
288 for (size_t index(0); index != count; ++index) {
289 // XXX: if these are libffi native then you can just take them
290 ffi_type *ffi(new(pool) ffi_type);
291 lhs.elements[index] = ffi;
292 sig::Copy(pool, *ffi, *rhs.elements[index]);
293 }
294 }
295 }
296
297 }
298
299 struct CStringMapLess :
300 std::binary_function<const char *, const char *, bool>
301 {
302 _finline bool operator ()(const char *lhs, const char *rhs) const {
303 return strcmp(lhs, rhs) < 0;
304 }
305 };
306
307 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
308 if (name == NULL)
309 return;
310
311 CYPoolTry {
312 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
313 switch ([[entry objectAtIndex:0] intValue]) {
314 case 0: {
315 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
316 } break;
317
318 case 1: {
319 sig::Signature signature;
320 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
321 type = signature.elements[0].type;
322 } break;
323 }
324 } CYPoolCatch()
325 }
326
327 struct Type_privateData :
328 CYData
329 {
330 ffi_type *ffi_;
331 sig::Type *type_;
332
333 void Set(sig::Type *type) {
334 type_ = new(pool_) sig::Type;
335 sig::Copy(pool_, *type_, *type);
336 }
337
338 Type_privateData(apr_pool_t *pool, const char *type) :
339 ffi_(NULL)
340 {
341 if (pool != NULL)
342 pool_ = pool;
343
344 sig::Signature signature;
345 sig::Parse(pool_, &signature, type, &Structor_);
346 type_ = signature.elements[0].type;
347 }
348
349 Type_privateData(sig::Type *type) :
350 ffi_(NULL)
351 {
352 if (type != NULL)
353 Set(type);
354 }
355
356 Type_privateData(sig::Type *type, ffi_type *ffi) {
357 ffi_ = new(pool_) ffi_type;
358 sig::Copy(pool_, *ffi_, *ffi);
359 Set(type);
360 }
361
362 ffi_type *GetFFI() {
363 if (ffi_ == NULL) {
364 ffi_ = new(pool_) ffi_type;
365
366 sig::Element element;
367 element.name = NULL;
368 element.type = type_;
369 element.offset = 0;
370
371 sig::Signature signature;
372 signature.elements = &element;
373 signature.count = 1;
374
375 ffi_cif cif;
376 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
377 *ffi_ = *cif.rtype;
378 }
379
380 return ffi_;
381 }
382 };
383
384 struct Pointer :
385 CYValue
386 {
387 JSObjectRef owner_;
388 Type_privateData *type_;
389
390 Pointer(void *value, sig::Type *type, JSObjectRef owner) :
391 CYValue(value),
392 owner_(owner),
393 type_(new(pool_) Type_privateData(type))
394 {
395 }
396 };
397
398 struct Struct_privateData :
399 CYValue
400 {
401 JSObjectRef owner_;
402 Type_privateData *type_;
403
404 Struct_privateData(JSObjectRef owner) :
405 owner_(owner)
406 {
407 }
408 };
409
410 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
411 static TypeMap Types_;
412
413 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
414 Struct_privateData *internal(new Struct_privateData(owner));
415 apr_pool_t *pool(internal->pool_);
416 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
417 internal->type_ = typical;
418
419 if (owner != NULL)
420 internal->value_ = data;
421 else {
422 size_t size(typical->GetFFI()->size);
423 void *copy(apr_palloc(internal->pool_, size));
424 memcpy(copy, data, size);
425 internal->value_ = copy;
426 }
427
428 return JSObjectMake(context, Struct_, internal);
429 }
430
431 struct Functor_privateData :
432 CYValue
433 {
434 sig::Signature signature_;
435 ffi_cif cif_;
436
437 Functor_privateData(const char *type, void (*value)()) :
438 CYValue(reinterpret_cast<void *>(value))
439 {
440 sig::Parse(pool_, &signature_, type, &Structor_);
441 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
442 }
443 };
444
445 struct ffoData :
446 Functor_privateData
447 {
448 JSContextRef context_;
449 JSObjectRef function_;
450
451 ffoData(const char *type) :
452 Functor_privateData(type, NULL)
453 {
454 }
455 };
456
457 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
458 Instance::Flags flags;
459
460 if (transient)
461 flags = Instance::Transient;
462 else {
463 flags = Instance::None;
464 object = [object retain];
465 }
466
467 return Instance::Make(context, object, flags);
468 }
469
470 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
471 if (pool == NULL)
472 return [value UTF8String];
473 else {
474 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
475 char *string(new(pool) char[size]);
476 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
477 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
478 return string;
479 }
480 }
481
482 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
483 return JSValueMakeBoolean(context, value);
484 }
485
486 JSValueRef CYCastJSValue(JSContextRef context, double value) {
487 return JSValueMakeNumber(context, value);
488 }
489
490 #define CYCastJSValue_(Type_) \
491 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
492 return JSValueMakeNumber(context, static_cast<double>(value)); \
493 }
494
495 CYCastJSValue_(int)
496 CYCastJSValue_(unsigned int)
497 CYCastJSValue_(long int)
498 CYCastJSValue_(long unsigned int)
499 CYCastJSValue_(long long int)
500 CYCastJSValue_(long long unsigned int)
501
502 JSValueRef CYJSUndefined(JSContextRef context) {
503 return JSValueMakeUndefined(context);
504 }
505
506 bool CYGetIndex(const char *value, ssize_t &index) {
507 if (value[0] != '0') {
508 char *end;
509 index = strtol(value, &end, 10);
510 if (value + strlen(value) == end)
511 return true;
512 } else if (value[1] == '\0') {
513 index = 0;
514 return true;
515 }
516
517 return false;
518 }
519
520 bool CYGetIndex(apr_pool_t *pool, NSString *value, ssize_t &index) {
521 return CYGetIndex(CYPoolCString(pool, value), index);
522 }
523
524 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
525
526 @interface NSMethodSignature (Cycript)
527 - (NSString *) _typeString;
528 @end
529
530 @interface NSObject (Cycript)
531
532 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
533 - (JSType) cy$JSType;
534
535 - (NSObject *) cy$toJSON:(NSString *)key;
536 - (NSString *) cy$toCYON;
537 - (NSString *) cy$toKey;
538
539 - (NSObject *) cy$getProperty:(NSString *)name;
540 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
541 - (bool) cy$deleteProperty:(NSString *)name;
542
543 @end
544
545 @protocol Cycript
546 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
547 @end
548
549 @interface NSString (Cycript)
550 - (void *) cy$symbol;
551 @end
552
553 struct PropertyAttributes {
554 CYPool pool_;
555
556 const char *name;
557
558 const char *variable;
559
560 const char *getter_;
561 const char *setter_;
562
563 bool readonly;
564 bool copy;
565 bool retain;
566 bool nonatomic;
567 bool dynamic;
568 bool weak;
569 bool garbage;
570
571 PropertyAttributes(objc_property_t property) :
572 variable(NULL),
573 getter_(NULL),
574 setter_(NULL),
575 readonly(false),
576 copy(false),
577 retain(false),
578 nonatomic(false),
579 dynamic(false),
580 weak(false),
581 garbage(false)
582 {
583 name = property_getName(property);
584 const char *attributes(property_getAttributes(property));
585
586 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
587 switch (*token) {
588 case 'R': readonly = true; break;
589 case 'C': copy = true; break;
590 case '&': retain = true; break;
591 case 'N': nonatomic = true; break;
592 case 'G': getter_ = token + 1; break;
593 case 'S': setter_ = token + 1; break;
594 case 'V': variable = token + 1; break;
595 }
596 }
597
598 /*if (variable == NULL) {
599 variable = property_getName(property);
600 size_t size(strlen(variable));
601 char *name(new(pool_) char[size + 2]);
602 name[0] = '_';
603 memcpy(name + 1, variable, size);
604 name[size + 1] = '\0';
605 variable = name;
606 }*/
607 }
608
609 const char *Getter() {
610 if (getter_ == NULL)
611 getter_ = apr_pstrdup(pool_, name);
612 return getter_;
613 }
614
615 const char *Setter() {
616 if (setter_ == NULL && !readonly) {
617 size_t length(strlen(name));
618
619 char *temp(new(pool_) char[length + 5]);
620 temp[0] = 's';
621 temp[1] = 'e';
622 temp[2] = 't';
623
624 if (length != 0) {
625 temp[3] = toupper(name[0]);
626 memcpy(temp + 4, name + 1, length - 1);
627 }
628
629 temp[length + 3] = ':';
630 temp[length + 4] = '\0';
631 setter_ = temp;
632 }
633
634 return setter_;
635 }
636
637 };
638
639 @implementation NSProxy (Cycript)
640
641 - (NSObject *) cy$toJSON:(NSString *)key {
642 return [self description];
643 }
644
645 - (NSString *) cy$toCYON {
646 return [[self cy$toJSON:@""] cy$toCYON];
647 }
648
649 @end
650
651 @implementation NSObject (Cycript)
652
653 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
654 return CYMakeInstance(context, self, false);
655 }
656
657 - (JSType) cy$JSType {
658 return kJSTypeObject;
659 }
660
661 - (NSObject *) cy$toJSON:(NSString *)key {
662 return [self description];
663 }
664
665 - (NSString *) cy$toCYON {
666 return [[self cy$toJSON:@""] cy$toCYON];
667 }
668
669 - (NSString *) cy$toKey {
670 return [self cy$toCYON];
671 }
672
673 - (NSObject *) cy$getProperty:(NSString *)name {
674 /*if (![name isEqualToString:@"prototype"])
675 NSLog(@"get:%@", name);*/
676 return nil;
677 }
678
679 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
680 //NSLog(@"set:%@", name);
681 return false;
682 }
683
684 - (bool) cy$deleteProperty:(NSString *)name {
685 //NSLog(@"delete:%@", name);
686 return false;
687 }
688
689 @end
690
691 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
692 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
693 }
694
695 @implementation WebUndefined (Cycript)
696
697 - (JSType) cy$JSType {
698 return kJSTypeUndefined;
699 }
700
701 - (NSObject *) cy$toJSON:(NSString *)key {
702 return self;
703 }
704
705 - (NSString *) cy$toCYON {
706 return @"undefined";
707 }
708
709 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
710 return CYJSUndefined(context);
711 }
712
713 @end
714
715 @implementation NSNull (Cycript)
716
717 - (JSType) cy$JSType {
718 return kJSTypeNull;
719 }
720
721 - (NSObject *) cy$toJSON:(NSString *)key {
722 return self;
723 }
724
725 - (NSString *) cy$toCYON {
726 return @"null";
727 }
728
729 @end
730
731 @implementation NSArray (Cycript)
732
733 - (NSString *) cy$toCYON {
734 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
735 [json appendString:@"["];
736
737 bool comma(false);
738 for (id object in self) {
739 if (comma)
740 [json appendString:@","];
741 else
742 comma = true;
743 if ([object cy$JSType] != kJSTypeUndefined)
744 [json appendString:CYPoolNSCYON(NULL, object)];
745 else {
746 [json appendString:@","];
747 comma = false;
748 }
749 }
750
751 [json appendString:@"]"];
752 return json;
753 }
754
755 - (NSObject *) cy$getProperty:(NSString *)name {
756 if ([name isEqualToString:@"length"])
757 return [NSNumber numberWithUnsignedInteger:[self count]];
758
759 ssize_t index;
760 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
761 return [super cy$getProperty:name];
762 else
763 return [self objectAtIndex:index];
764 }
765
766 @end
767
768 @implementation NSMutableArray (Cycript)
769
770 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
771 ssize_t index;
772 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
773 return [super cy$setProperty:name to:value];
774 else {
775 [self replaceObjectAtIndex:index withObject:(value ?: [NSNull null])];
776 return true;
777 }
778 }
779
780 - (bool) cy$deleteProperty:(NSString *)name {
781 ssize_t index;
782 if (!CYGetIndex(NULL, name, index) || index < 0 || index >= static_cast<ssize_t>([self count]))
783 return [super cy$deleteProperty:name];
784 else {
785 [self removeObjectAtIndex:index];
786 return true;
787 }
788 }
789
790 @end
791
792 @implementation NSDictionary (Cycript)
793
794 - (NSString *) cy$toCYON {
795 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
796 [json appendString:@"{"];
797
798 bool comma(false);
799 for (id key in self) {
800 if (comma)
801 [json appendString:@","];
802 else
803 comma = true;
804 [json appendString:[key cy$toKey]];
805 [json appendString:@":"];
806 NSObject *object([self objectForKey:key]);
807 [json appendString:CYPoolNSCYON(NULL, object)];
808 }
809
810 [json appendString:@"}"];
811 return json;
812 }
813
814 - (NSObject *) cy$getProperty:(NSString *)name {
815 return [self objectForKey:name];
816 }
817
818 @end
819
820 @implementation NSMutableDictionary (Cycript)
821
822 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
823 [self setObject:(value ?: [NSNull null]) forKey:name];
824 return true;
825 }
826
827 - (bool) cy$deleteProperty:(NSString *)name {
828 if ([self objectForKey:name] == nil)
829 return false;
830 else {
831 [self removeObjectForKey:name];
832 return true;
833 }
834 }
835
836 @end
837
838 @implementation NSNumber (Cycript)
839
840 - (JSType) cy$JSType {
841 // XXX: this just seems stupid
842 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
843 }
844
845 - (NSObject *) cy$toJSON:(NSString *)key {
846 return self;
847 }
848
849 - (NSString *) cy$toCYON {
850 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
851 }
852
853 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
854 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
855 }
856
857 @end
858
859 @implementation NSString (Cycript)
860
861 - (JSType) cy$JSType {
862 return kJSTypeString;
863 }
864
865 - (NSObject *) cy$toJSON:(NSString *)key {
866 return self;
867 }
868
869 - (NSString *) cy$toCYON {
870 // XXX: this should use the better code from Output.cpp
871 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
872
873 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
874 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
875 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
876 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
877 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
878
879 CFStringInsert(json, 0, CFSTR("\""));
880 CFStringAppend(json, CFSTR("\""));
881
882 return [reinterpret_cast<const NSString *>(json) autorelease];
883 }
884
885 - (NSString *) cy$toKey {
886 const char *value([self UTF8String]);
887 size_t size(strlen(value));
888
889 if (size == 0)
890 goto cyon;
891
892 if (DigitRange_[value[0]]) {
893 ssize_t index;
894 if (!CYGetIndex(NULL, self, index) || index < 0)
895 goto cyon;
896 } else {
897 if (!WordStartRange_[value[0]])
898 goto cyon;
899 for (size_t i(1); i != size; ++i)
900 if (!WordEndRange_[value[i]])
901 goto cyon;
902 }
903
904 return self;
905
906 cyon:
907 return [self cy$toCYON];
908 }
909
910 - (void *) cy$symbol {
911 CYPool pool;
912 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
913 }
914
915 @end
916
917 @interface CYJSObject : NSDictionary {
918 JSObjectRef object_;
919 JSContextRef context_;
920 }
921
922 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
923
924 - (NSString *) cy$toJSON:(NSString *)key;
925
926 - (NSUInteger) count;
927 - (id) objectForKey:(id)key;
928 - (NSEnumerator *) keyEnumerator;
929 - (void) setObject:(id)object forKey:(id)key;
930 - (void) removeObjectForKey:(id)key;
931
932 @end
933
934 @interface CYJSArray : NSArray {
935 JSObjectRef object_;
936 JSContextRef context_;
937 }
938
939 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
940
941 - (NSUInteger) count;
942 - (id) objectAtIndex:(NSUInteger)index;
943
944 @end
945
946 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
947 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
948 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
949
950 #define CYTry \
951 @try
952 #define CYCatch \
953 @catch (id error) { \
954 CYThrow(context, error, exception); \
955 return NULL; \
956 }
957
958 void CYThrow(JSContextRef context, JSValueRef value);
959
960 apr_status_t CYPoolRelease_(void *data) {
961 id object(reinterpret_cast<id>(data));
962 [object release];
963 return APR_SUCCESS;
964 }
965
966 id CYPoolRelease(apr_pool_t *pool, id object) {
967 if (object == nil)
968 return nil;
969 else if (pool == NULL)
970 return [object autorelease];
971 else {
972 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
973 return object;
974 }
975 }
976
977 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
978 return (CFTypeRef) CYPoolRelease(pool, (id) object);
979 }
980
981 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
982 JSValueRef exception(NULL);
983 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
984 CYThrow(context, exception);
985 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
986 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
987 }
988
989 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
990 if (!JSValueIsObjectOfClass(context, object, Instance_))
991 return CYCastNSObject_(pool, context, object);
992 else {
993 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
994 return data->GetValue();
995 }
996 }
997
998 JSStringRef CYCopyJSString(id value) {
999 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
1000 }
1001
1002 JSStringRef CYCopyJSString(const char *value) {
1003 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
1004 }
1005
1006 JSStringRef CYCopyJSString(JSStringRef value) {
1007 return value == NULL ? NULL : JSStringRetain(value);
1008 }
1009
1010 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
1011 if (JSValueIsNull(context, value))
1012 return NULL;
1013 JSValueRef exception(NULL);
1014 JSStringRef string(JSValueToStringCopy(context, value, &exception));
1015 CYThrow(context, exception);
1016 return string;
1017 }
1018
1019 class CYJSString {
1020 private:
1021 JSStringRef string_;
1022
1023 void Clear_() {
1024 if (string_ != NULL)
1025 JSStringRelease(string_);
1026 }
1027
1028 public:
1029 CYJSString(const CYJSString &rhs) :
1030 string_(CYCopyJSString(rhs.string_))
1031 {
1032 }
1033
1034 template <typename Arg0_>
1035 CYJSString(Arg0_ arg0) :
1036 string_(CYCopyJSString(arg0))
1037 {
1038 }
1039
1040 template <typename Arg0_, typename Arg1_>
1041 CYJSString(Arg0_ arg0, Arg1_ arg1) :
1042 string_(CYCopyJSString(arg0, arg1))
1043 {
1044 }
1045
1046 CYJSString &operator =(const CYJSString &rhs) {
1047 Clear_();
1048 string_ = CYCopyJSString(rhs.string_);
1049 return *this;
1050 }
1051
1052 ~CYJSString() {
1053 Clear_();
1054 }
1055
1056 void Clear() {
1057 Clear_();
1058 string_ = NULL;
1059 }
1060
1061 operator JSStringRef() const {
1062 return string_;
1063 }
1064 };
1065
1066 CFStringRef CYCopyCFString(JSStringRef value) {
1067 return JSStringCopyCFString(kCFAllocatorDefault, value);
1068 }
1069
1070 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
1071 return CYCopyCFString(CYJSString(context, value));
1072 }
1073
1074 double CYCastDouble(const char *value, size_t size) {
1075 char *end;
1076 double number(strtod(value, &end));
1077 if (end != value + size)
1078 return NAN;
1079 return number;
1080 }
1081
1082 double CYCastDouble(const char *value) {
1083 return CYCastDouble(value, strlen(value));
1084 }
1085
1086 double CYCastDouble(JSContextRef context, JSValueRef value) {
1087 JSValueRef exception(NULL);
1088 double number(JSValueToNumber(context, value, &exception));
1089 CYThrow(context, exception);
1090 return number;
1091 }
1092
1093 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1094 double number(CYCastDouble(context, value));
1095 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1096 }
1097
1098 CFStringRef CYCopyCFString(const char *value) {
1099 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1100 }
1101
1102 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1103 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1104 }
1105
1106 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1107 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1108 }
1109
1110 bool CYCastBool(JSContextRef context, JSValueRef value) {
1111 return JSValueToBoolean(context, value);
1112 }
1113
1114 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1115 CFTypeRef object;
1116 bool copy;
1117
1118 switch (JSType type = JSValueGetType(context, value)) {
1119 case kJSTypeUndefined:
1120 object = [WebUndefined undefined];
1121 copy = false;
1122 break;
1123
1124 case kJSTypeNull:
1125 return NULL;
1126 break;
1127
1128 case kJSTypeBoolean:
1129 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1130 copy = false;
1131 break;
1132
1133 case kJSTypeNumber:
1134 object = CYCopyCFNumber(context, value);
1135 copy = true;
1136 break;
1137
1138 case kJSTypeString:
1139 object = CYCopyCFString(context, value);
1140 copy = true;
1141 break;
1142
1143 case kJSTypeObject:
1144 // XXX: this might could be more efficient
1145 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1146 copy = false;
1147 break;
1148
1149 default:
1150 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1151 break;
1152 }
1153
1154 if (cast != copy)
1155 return object;
1156 else if (copy)
1157 return CYPoolRelease(pool, object);
1158 else
1159 return CFRetain(object);
1160 }
1161
1162 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1163 return CYCFType(pool, context, value, true);
1164 }
1165
1166 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1167 return CYCFType(pool, context, value, false);
1168 }
1169
1170 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1171 CYPool pool;
1172 size_t size(JSPropertyNameArrayGetCount(names));
1173 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1174 for (size_t index(0); index != size; ++index)
1175 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1176 return array;
1177 }
1178
1179 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1180 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1181 }
1182
1183 void CYThrow(JSContextRef context, JSValueRef value) {
1184 if (value == NULL)
1185 return;
1186 @throw CYCastNSObject(NULL, context, value);
1187 }
1188
1189 JSValueRef CYJSNull(JSContextRef context) {
1190 return JSValueMakeNull(context);
1191 }
1192
1193 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1194 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1195 }
1196
1197 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1198 return CYCastJSValue(context, CYJSString(value));
1199 }
1200
1201 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1202 if (value == nil)
1203 return CYJSNull(context);
1204 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1205 return [value cy$JSValueInContext:context];
1206 else
1207 return CYMakeInstance(context, value, false);
1208 }
1209
1210 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1211 JSValueRef exception(NULL);
1212 JSObjectRef object(JSValueToObject(context, value, &exception));
1213 CYThrow(context, exception);
1214 return object;
1215 }
1216
1217 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
1218 JSValueRef exception(NULL);
1219 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
1220 CYThrow(context, exception);
1221 return value;
1222 }
1223
1224 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
1225 JSValueRef exception(NULL);
1226 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
1227 CYThrow(context, exception);
1228 return value;
1229 }
1230
1231 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
1232 JSValueRef exception(NULL);
1233 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
1234 CYThrow(context, exception);
1235 }
1236
1237 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1238 if (exception == NULL)
1239 throw error;
1240 *exception = CYCastJSValue(context, error);
1241 }
1242
1243 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1244 JSValueRef exception(NULL);
1245 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1246 CYThrow(context, exception);
1247 return value;
1248 }
1249
1250 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1251 // XXX: this isn't actually correct
1252 return value != NULL && JSValueIsObject(context, value);
1253 }
1254
1255 @implementation CYJSObject
1256
1257 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1258 if ((self = [super init]) != nil) {
1259 object_ = object;
1260 context_ = context;
1261 } return self;
1262 }
1263
1264 - (NSObject *) cy$toJSON:(NSString *)key {
1265 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1266 if (!CYIsCallable(context_, toJSON))
1267 return [super cy$toJSON:key];
1268 else {
1269 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1270 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1271 // XXX: do I really want an NSNull here?!
1272 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1273 }
1274 }
1275
1276 - (NSString *) cy$toCYON {
1277 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1278 if (!CYIsCallable(context_, toCYON))
1279 return [super cy$toCYON];
1280 else {
1281 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL));
1282 return CYCastNSString(NULL, CYJSString(context_, value));
1283 }
1284 }
1285
1286 - (NSUInteger) count {
1287 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1288 size_t size(JSPropertyNameArrayGetCount(names));
1289 JSPropertyNameArrayRelease(names);
1290 return size;
1291 }
1292
1293 - (id) objectForKey:(id)key {
1294 return CYCastNSObject(NULL, context_, CYGetProperty(context_, object_, CYJSString(key))) ?: [NSNull null];
1295 }
1296
1297 - (NSEnumerator *) keyEnumerator {
1298 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1299 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1300 JSPropertyNameArrayRelease(names);
1301 return enumerator;
1302 }
1303
1304 - (void) setObject:(id)object forKey:(id)key {
1305 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1306 }
1307
1308 - (void) removeObjectForKey:(id)key {
1309 JSValueRef exception(NULL);
1310 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1311 CYThrow(context_, exception);
1312 }
1313
1314 @end
1315
1316 @implementation CYJSArray
1317
1318 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1319 if ((self = [super init]) != nil) {
1320 object_ = object;
1321 context_ = context;
1322 } return self;
1323 }
1324
1325 - (NSUInteger) count {
1326 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1327 }
1328
1329 - (id) objectAtIndex:(NSUInteger)index {
1330 JSValueRef exception(NULL);
1331 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1332 CYThrow(context_, exception);
1333 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1334 }
1335
1336 @end
1337
1338 NSString *CYCopyNSCYON(id value) {
1339 Class _class(object_getClass(value));
1340 SEL sel(@selector(cy$toCYON));
1341
1342 NSString *string;
1343
1344 if (Method toCYON = class_getInstanceMethod(_class, sel))
1345 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1346 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1347 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1348 string = [value cy$toCYON];
1349 else goto fail;
1350 } else fail: {
1351 if (value == NSZombie_)
1352 string = @"_NSZombie_";
1353 else if (_class == NSZombie_)
1354 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1355 else if (value == NSMessageBuilder_ || value == Object_)
1356 string = nil;
1357 else
1358 string = [NSString stringWithFormat:@"%@", value];
1359 }
1360
1361 // XXX: frowny pants
1362 if (string == nil)
1363 string = @"undefined";
1364 return [string retain];
1365 }
1366
1367 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1368 CYTry {
1369 CYPoolTry {
1370 return CYCopyNSCYON(CYCastNSObject(NULL, context, value) ?: [NSNull null]);
1371 } CYPoolCatch(NULL)
1372 } CYCatch
1373 }
1374
1375 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1376 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1377 }
1378
1379 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1380 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1381 const char *string(CYPoolCString(pool, json));
1382 [json release];
1383 return string;
1384 } else return NULL;
1385 }
1386
1387 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1388 struct CYInternal :
1389 CYData
1390 {
1391 JSObjectRef object_;
1392
1393 CYInternal() :
1394 object_(NULL)
1395 {
1396 }
1397
1398 ~CYInternal() {
1399 // XXX: delete object_? ;(
1400 }
1401
1402 static CYInternal *Get(id self) {
1403 CYInternal *internal(NULL);
1404 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1405 // XXX: do something epic? ;P
1406 }
1407
1408 return internal;
1409 }
1410
1411 static CYInternal *Set(id self) {
1412 CYInternal *internal(NULL);
1413 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1414 if (internal == NULL) {
1415 internal = new CYInternal();
1416 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1417 }
1418 } else {
1419 // XXX: do something epic? ;P
1420 }
1421
1422 return internal;
1423 }
1424
1425 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1426 if (object_ == NULL)
1427 return NULL;
1428 return CYGetProperty(context, object_, name);
1429 }
1430
1431 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1432 if (object_ == NULL)
1433 object_ = JSObjectMake(context, NULL, NULL);
1434 CYSetProperty(context, object_, name, value);
1435 }
1436 };
1437
1438 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1439 Selector_privateData *data(new Selector_privateData(sel));
1440 return JSObjectMake(context, Selector_, data);
1441 }
1442
1443 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, JSObjectRef owner) {
1444 Pointer *data(new Pointer(pointer, type, owner));
1445 return JSObjectMake(context, Pointer_, data);
1446 }
1447
1448 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1449 Functor_privateData *data(new Functor_privateData(type, function));
1450 return JSObjectMake(context, Functor_, data);
1451 }
1452
1453 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1454 if (pool == NULL) {
1455 const char *string([CYCastNSString(NULL, value) UTF8String]);
1456 return string;
1457 } else {
1458 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1459 char *string(new(pool) char[size]);
1460 JSStringGetUTF8CString(value, string, size);
1461 return string;
1462 }
1463 }
1464
1465 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1466 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1467 }
1468
1469 bool CYGetIndex(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1470 return CYGetIndex(CYPoolCString(pool, value), index);
1471 }
1472
1473 // XXX: this macro is unhygenic
1474 #define CYCastCString(context, value) ({ \
1475 char *utf8; \
1476 if (value == NULL) \
1477 utf8 = NULL; \
1478 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1479 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1480 utf8 = reinterpret_cast<char *>(alloca(size)); \
1481 JSStringGetUTF8CString(string, utf8, size); \
1482 JSStringRelease(string); \
1483 } else \
1484 utf8 = NULL; \
1485 utf8; \
1486 })
1487
1488 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1489 switch (JSValueGetType(context, value)) {
1490 case kJSTypeNull:
1491 return NULL;
1492 /*case kJSTypeString:
1493 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1494 case kJSTypeObject:
1495 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1496 Pointer *data(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1497 return data->value_;
1498 }*/
1499 default:
1500 double number(CYCastDouble(context, value));
1501 if (std::isnan(number))
1502 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1503 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1504 }
1505 }
1506
1507 template <typename Type_>
1508 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1509 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1510 }
1511
1512 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1513 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1514 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1515 return reinterpret_cast<SEL>(data->value_);
1516 } else
1517 return CYCastPointer<SEL>(context, value);
1518 }
1519
1520 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1521 switch (type->primitive) {
1522 case sig::boolean_P:
1523 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1524 break;
1525
1526 #define CYPoolFFI_(primitive, native) \
1527 case sig::primitive ## _P: \
1528 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1529 break;
1530
1531 CYPoolFFI_(uchar, unsigned char)
1532 CYPoolFFI_(char, char)
1533 CYPoolFFI_(ushort, unsigned short)
1534 CYPoolFFI_(short, short)
1535 CYPoolFFI_(ulong, unsigned long)
1536 CYPoolFFI_(long, long)
1537 CYPoolFFI_(uint, unsigned int)
1538 CYPoolFFI_(int, int)
1539 CYPoolFFI_(ulonglong, unsigned long long)
1540 CYPoolFFI_(longlong, long long)
1541 CYPoolFFI_(float, float)
1542 CYPoolFFI_(double, double)
1543
1544 case sig::object_P:
1545 case sig::typename_P:
1546 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1547 break;
1548
1549 case sig::selector_P:
1550 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1551 break;
1552
1553 case sig::pointer_P:
1554 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1555 break;
1556
1557 case sig::string_P:
1558 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1559 break;
1560
1561 case sig::struct_P: {
1562 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1563 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1564 for (size_t index(0); index != type->data.signature.count; ++index) {
1565 sig::Element *element(&type->data.signature.elements[index]);
1566 ffi_type *field(ffi->elements[index]);
1567
1568 JSValueRef rhs;
1569 if (aggregate == NULL)
1570 rhs = value;
1571 else {
1572 rhs = CYGetProperty(context, aggregate, index);
1573 if (JSValueIsUndefined(context, rhs)) {
1574 if (element->name != NULL)
1575 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1576 else
1577 goto undefined;
1578 if (JSValueIsUndefined(context, rhs)) undefined:
1579 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1580 }
1581 }
1582
1583 CYPoolFFI(pool, context, element->type, field, base, rhs);
1584 // XXX: alignment?
1585 base += field->size;
1586 }
1587 } break;
1588
1589 case sig::void_P:
1590 break;
1591
1592 default:
1593 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1594 _assert(false);
1595 }
1596 }
1597
1598 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1599 JSValueRef value;
1600
1601 switch (type->primitive) {
1602 case sig::boolean_P:
1603 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1604 break;
1605
1606 #define CYFromFFI_(primitive, native) \
1607 case sig::primitive ## _P: \
1608 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1609 break;
1610
1611 CYFromFFI_(uchar, unsigned char)
1612 CYFromFFI_(char, char)
1613 CYFromFFI_(ushort, unsigned short)
1614 CYFromFFI_(short, short)
1615 CYFromFFI_(ulong, unsigned long)
1616 CYFromFFI_(long, long)
1617 CYFromFFI_(uint, unsigned int)
1618 CYFromFFI_(int, int)
1619 CYFromFFI_(ulonglong, unsigned long long)
1620 CYFromFFI_(longlong, long long)
1621 CYFromFFI_(float, float)
1622 CYFromFFI_(double, double)
1623
1624 case sig::object_P: {
1625 if (id object = *reinterpret_cast<id *>(data)) {
1626 value = CYCastJSValue(context, object);
1627 if (initialize)
1628 [object release];
1629 } else goto null;
1630 } break;
1631
1632 case sig::typename_P:
1633 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1634 break;
1635
1636 case sig::selector_P:
1637 if (SEL sel = *reinterpret_cast<SEL *>(data))
1638 value = CYMakeSelector(context, sel);
1639 else goto null;
1640 break;
1641
1642 case sig::pointer_P:
1643 if (void *pointer = *reinterpret_cast<void **>(data))
1644 value = CYMakePointer(context, pointer, type->data.data.type, owner);
1645 else goto null;
1646 break;
1647
1648 case sig::string_P:
1649 if (char *utf8 = *reinterpret_cast<char **>(data))
1650 value = CYCastJSValue(context, utf8);
1651 else goto null;
1652 break;
1653
1654 case sig::struct_P:
1655 value = CYMakeStruct(context, data, type, ffi, owner);
1656 break;
1657
1658 case sig::void_P:
1659 value = CYJSUndefined(context);
1660 break;
1661
1662 null:
1663 value = CYJSNull(context);
1664 break;
1665
1666 default:
1667 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1668 _assert(false);
1669 }
1670
1671 return value;
1672 }
1673
1674 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1675 CYPool pool;
1676
1677 CYTry {
1678 NSString *self(CYCastNSObject(pool, context, object));
1679 NSString *name(CYCastNSString(pool, property));
1680
1681 if (CYInternal *internal = CYInternal::Get(self))
1682 if (JSValueRef value = internal->GetProperty(context, property))
1683 return value;
1684
1685 CYPoolTry {
1686 if (NSObject *data = [self cy$getProperty:name])
1687 return CYCastJSValue(context, data);
1688 } CYPoolCatch(NULL)
1689
1690 const char *string(CYPoolCString(pool, name));
1691
1692 if (objc_property_t property = class_getProperty(object_getClass(self), string)) {
1693 PropertyAttributes attributes(property);
1694 SEL sel(sel_registerName(attributes.Getter()));
1695 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
1696 }
1697
1698 if (Ivar ivar = object_getInstanceVariable(self, string, NULL)) {
1699 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1700 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
1701 }
1702
1703 return NULL;
1704 } CYCatch
1705 }
1706
1707 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1708 CYPool pool;
1709
1710 CYTry {
1711 NSString *self(CYCastNSObject(pool, context, object));
1712 NSString *name(CYCastNSString(pool, property));
1713 NSString *data(CYCastNSObject(pool, context, value));
1714
1715 CYPoolTry {
1716 if ([self cy$setProperty:name to:data])
1717 return true;
1718 } CYPoolCatch(NULL)
1719
1720 const char *string(CYPoolCString(pool, name));
1721
1722 if (objc_property_t property = class_getProperty(object_getClass(self), string)) {
1723 PropertyAttributes attributes(property);
1724 if (const char *setter = attributes.Setter()) {
1725 SEL sel(sel_registerName(setter));
1726 JSValueRef arguments[1] = {value};
1727 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
1728 return true;
1729 }
1730 }
1731
1732 if (Ivar ivar = object_getInstanceVariable(self, string, NULL)) {
1733 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
1734 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
1735 return true;
1736 }
1737
1738 if (CYInternal *internal = CYInternal::Set(self)) {
1739 internal->SetProperty(context, property, value);
1740 return true;
1741 }
1742
1743 return false;
1744 } CYCatch
1745 }
1746
1747 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1748 CYTry {
1749 CYPoolTry {
1750 NSString *self(CYCastNSObject(NULL, context, object));
1751 NSString *name(CYCastNSString(NULL, property));
1752 return [self cy$deleteProperty:name];
1753 } CYPoolCatch(NULL)
1754 } CYCatch
1755 }
1756
1757 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1758 CYPool pool;
1759 NSString *self(CYCastNSObject(pool, context, object));
1760 Class _class(object_getClass(self));
1761
1762 {
1763 unsigned int size;
1764 objc_property_t *data(class_copyPropertyList(_class, &size));
1765 for (size_t i(0); i != size; ++i)
1766 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
1767 free(data);
1768 }
1769
1770 for (Class super(_class); super != NULL; super = class_getSuperclass(super)) {
1771 unsigned int size;
1772 Ivar *data(class_copyIvarList(super, &size));
1773 for (size_t i(0); i != size; ++i)
1774 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
1775 free(data);
1776 }
1777 }
1778
1779 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1780 CYTry {
1781 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1782 JSObjectRef value(Instance::Make(context, [data->GetValue() alloc], Instance::Uninitialized));
1783 return value;
1784 } CYCatch
1785 }
1786
1787 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1788 Type_privateData *typical(internal->type_);
1789 sig::Type *type(typical->type_);
1790 if (type == NULL)
1791 return false;
1792
1793 const char *name(CYPoolCString(pool, property));
1794 size_t length(strlen(name));
1795 double number(CYCastDouble(name, length));
1796
1797 size_t count(type->data.signature.count);
1798
1799 if (std::isnan(number)) {
1800 if (property == NULL)
1801 return false;
1802
1803 sig::Element *elements(type->data.signature.elements);
1804
1805 for (size_t local(0); local != count; ++local) {
1806 sig::Element *element(&elements[local]);
1807 if (element->name != NULL && strcmp(name, element->name) == 0) {
1808 index = local;
1809 goto base;
1810 }
1811 }
1812
1813 return false;
1814 } else {
1815 index = static_cast<ssize_t>(number);
1816 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1817 return false;
1818 }
1819
1820 base:
1821 ffi_type **elements(typical->GetFFI()->elements);
1822
1823 base = reinterpret_cast<uint8_t *>(internal->value_);
1824 for (ssize_t local(0); local != index; ++local)
1825 base += elements[local]->size;
1826
1827 return true;
1828 }
1829
1830 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1831 CYPool pool;
1832 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1833 Type_privateData *typical(internal->type_);
1834
1835 if (typical->type_ == NULL)
1836 return NULL;
1837
1838 ssize_t index;
1839 if (!CYGetIndex(pool, property, index))
1840 return NULL;
1841
1842 ffi_type *ffi(typical->GetFFI());
1843
1844 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1845 base += ffi->size * index;
1846
1847 JSObjectRef owner(internal->owner_ ?: object);
1848
1849 CYTry {
1850 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
1851 } CYCatch
1852 }
1853
1854 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1855 CYPool pool;
1856 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1857 Type_privateData *typical(internal->type_);
1858
1859 if (typical->type_ == NULL)
1860 return NULL;
1861
1862 ssize_t index;
1863 if (!CYGetIndex(pool, property, index))
1864 return NULL;
1865
1866 ffi_type *ffi(typical->GetFFI());
1867
1868 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
1869 base += ffi->size * index;
1870
1871 CYTry {
1872 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
1873 return true;
1874 } CYCatch
1875 }
1876
1877 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1878 CYPool pool;
1879 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1880 Type_privateData *typical(internal->type_);
1881
1882 ssize_t index;
1883 uint8_t *base;
1884
1885 if (!Index_(pool, internal, property, index, base))
1886 return NULL;
1887
1888 JSObjectRef owner(internal->owner_ ?: object);
1889
1890 CYTry {
1891 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
1892 } CYCatch
1893 }
1894
1895 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
1896 CYPool pool;
1897 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1898 Type_privateData *typical(internal->type_);
1899
1900 ssize_t index;
1901 uint8_t *base;
1902
1903 if (!Index_(pool, internal, property, index, base))
1904 return false;
1905
1906 CYTry {
1907 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1908 return true;
1909 } CYCatch
1910 }
1911
1912 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1913 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1914 Type_privateData *typical(internal->type_);
1915 sig::Type *type(typical->type_);
1916
1917 if (type == NULL)
1918 return;
1919
1920 size_t count(type->data.signature.count);
1921 sig::Element *elements(type->data.signature.elements);
1922
1923 char number[32];
1924
1925 for (size_t index(0); index != count; ++index) {
1926 const char *name;
1927 name = elements[index].name;
1928
1929 if (name == NULL) {
1930 sprintf(number, "%lu", index);
1931 name = number;
1932 }
1933
1934 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1935 }
1936 }
1937
1938 JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
1939 CYTry {
1940 if (setups + count != signature->count - 1)
1941 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
1942
1943 size_t size(setups + count);
1944 void *values[size];
1945 memcpy(values, setup, sizeof(void *) * setups);
1946
1947 for (size_t index(setups); index != size; ++index) {
1948 sig::Element *element(&signature->elements[index + 1]);
1949 ffi_type *ffi(cif->arg_types[index]);
1950 // XXX: alignment?
1951 values[index] = new(pool) uint8_t[ffi->size];
1952 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1953 }
1954
1955 uint8_t value[cif->rtype->size];
1956 ffi_call(cif, function, value, values);
1957
1958 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1959 } CYCatch
1960 }
1961
1962 void Closure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1963 ffoData *data(reinterpret_cast<ffoData *>(arg));
1964
1965 JSContextRef context(data->context_);
1966
1967 size_t count(data->cif_.nargs);
1968 JSValueRef values[count];
1969
1970 for (size_t index(0); index != count; ++index)
1971 values[index] = CYFromFFI(context, data->signature_.elements[1 + index].type, data->cif_.arg_types[index], arguments[index]);
1972
1973 JSValueRef value(CYCallAsFunction(context, data->function_, NULL, count, values));
1974 CYPoolFFI(NULL, context, data->signature_.elements[0].type, data->cif_.rtype, result, value);
1975 }
1976
1977 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
1978 // XXX: in case of exceptions this will leak
1979 ffoData *data(new ffoData(type));
1980
1981 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1982 NULL, sizeof(ffi_closure),
1983 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1984 -1, 0
1985 )));
1986
1987 ffi_status status(ffi_prep_closure(closure, &data->cif_, &Closure_, data));
1988 _assert(status == FFI_OK);
1989
1990 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1991
1992 data->value_ = closure;
1993
1994 data->context_ = CYGetJSContext();
1995 data->function_ = function;
1996
1997 return JSObjectMake(context, Functor_, data);
1998 }
1999
2000 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2001 CYTry {
2002 CYPool pool;
2003 NSString *name(CYCastNSString(pool, property));
2004 if (Class _class = NSClassFromString(name))
2005 return CYMakeInstance(context, _class, true);
2006 return NULL;
2007 } CYCatch
2008 }
2009
2010 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2011 size_t size(objc_getClassList(NULL, 0));
2012 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2013
2014 get:
2015 size_t writ(objc_getClassList(data, size));
2016 if (size < writ) {
2017 size = writ;
2018 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2019 data = copy;
2020 goto get;
2021 } else goto done;
2022 }
2023
2024 for (size_t i(0); i != writ; ++i)
2025 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2026
2027 done:
2028 free(data);
2029 }
2030
2031 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2032 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2033
2034 CYTry {
2035 CYPool pool;
2036 const char *name(CYPoolCString(pool, property));
2037 unsigned int size;
2038 const char **data(objc_copyClassNamesForImage(internal, &size));
2039 JSValueRef value;
2040 for (size_t i(0); i != size; ++i)
2041 if (strcmp(name, data[i]) == 0) {
2042 if (Class _class = objc_getClass(name)) {
2043 value = CYMakeInstance(context, _class, true);
2044 goto free;
2045 } else
2046 break;
2047 }
2048 value = NULL;
2049 free:
2050 free(data);
2051 return value;
2052 } CYCatch
2053 }
2054
2055 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2056 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2057 unsigned int size;
2058 const char **data(objc_copyClassNamesForImage(internal, &size));
2059 for (size_t i(0); i != size; ++i)
2060 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2061 free(data);
2062 }
2063
2064 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2065 CYTry {
2066 CYPool pool;
2067 const char *name(CYPoolCString(pool, property));
2068 unsigned int size;
2069 const char **data(objc_copyImageNames(&size));
2070 for (size_t i(0); i != size; ++i)
2071 if (strcmp(name, data[i]) == 0) {
2072 name = data[i];
2073 goto free;
2074 }
2075 name = NULL;
2076 free:
2077 free(data);
2078 if (name == NULL)
2079 return NULL;
2080 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2081 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2082 return value;
2083 } CYCatch
2084 }
2085
2086 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2087 unsigned int size;
2088 const char **data(objc_copyImageNames(&size));
2089 for (size_t i(0); i != size; ++i)
2090 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2091 free(data);
2092 }
2093
2094 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2095 CYTry {
2096 CYPool pool;
2097 NSString *name(CYCastNSString(pool, property));
2098 if (Protocol *protocol = NSProtocolFromString(name))
2099 return CYMakeInstance(context, protocol, true);
2100 return NULL;
2101 } CYCatch
2102 }
2103
2104 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2105 unsigned int size;
2106 Protocol **data(objc_copyProtocolList(&size));
2107 for (size_t i(0); i != size; ++i)
2108 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2109 free(data);
2110 }
2111
2112 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2113 CYTry {
2114 CYPool pool;
2115 NSString *name(CYCastNSString(pool, property));
2116 if (Class _class = NSClassFromString(name))
2117 return CYMakeInstance(context, _class, true);
2118 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2119 switch ([[entry objectAtIndex:0] intValue]) {
2120 case 0:
2121 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2122 case 1:
2123 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2124 case 2:
2125 // XXX: this is horrendously inefficient
2126 sig::Signature signature;
2127 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2128 ffi_cif cif;
2129 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2130 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2131 }
2132 return NULL;
2133 } CYCatch
2134 }
2135
2136 bool stret(ffi_type *ffi_type) {
2137 return ffi_type->type == FFI_TYPE_STRUCT && (
2138 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2139 struct_forward_array[ffi_type->size] != 0
2140 );
2141 }
2142
2143 extern "C" {
2144 int *_NSGetArgc(void);
2145 char ***_NSGetArgv(void);
2146 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2147 }
2148
2149 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2150 CYTry {
2151 NSLog(@"%s", CYCastCString(context, arguments[0]));
2152 return CYJSUndefined(context);
2153 } CYCatch
2154 }
2155
2156 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2157 const char *type;
2158
2159 Class _class(object_getClass(self));
2160 if (Method method = class_getInstanceMethod(_class, _cmd))
2161 type = method_getTypeEncoding(method);
2162 else {
2163 CYTry {
2164 CYPoolTry {
2165 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2166 if (method == nil)
2167 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2168 type = CYPoolCString(pool, [method _typeString]);
2169 } CYPoolCatch(NULL)
2170 } CYCatch
2171 }
2172
2173 void *setup[2];
2174 setup[0] = &self;
2175 setup[1] = &_cmd;
2176
2177 sig::Signature signature;
2178 sig::Parse(pool, &signature, type, &Structor_);
2179
2180 ffi_cif cif;
2181 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2182
2183 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2184 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2185 }
2186
2187 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2188 CYPool pool;
2189
2190 bool uninitialized;
2191
2192 id self;
2193 SEL _cmd;
2194
2195 CYTry {
2196 if (count < 2)
2197 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2198
2199 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2200 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2201 self = data->GetValue();
2202 uninitialized = data->IsUninitialized();
2203 if (uninitialized)
2204 data->value_ = nil;
2205 } else {
2206 self = CYCastNSObject(pool, context, arguments[0]);
2207 uninitialized = false;
2208 }
2209
2210 if (self == nil)
2211 return CYJSNull(context);
2212
2213 _cmd = CYCastSEL(context, arguments[1]);
2214 } CYCatch
2215
2216 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2217 }
2218
2219 MSHook(void, CYDealloc, id self, SEL sel) {
2220 CYInternal *internal;
2221 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2222 if (internal != NULL)
2223 delete internal;
2224 _CYDealloc(self, sel);
2225 }
2226
2227 MSHook(void, objc_registerClassPair, Class _class) {
2228 Class super(class_getSuperclass(_class));
2229 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2230 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2231 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2232 }
2233
2234 _objc_registerClassPair(_class);
2235 }
2236
2237 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2238 CYTry {
2239 if (count != 1)
2240 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2241 CYPool pool;
2242 Class _class(CYCastNSObject(pool, context, arguments[0]));
2243 $objc_registerClassPair(_class);
2244 return CYJSUndefined(context);
2245 } CYCatch
2246 }
2247
2248 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2249 JSValueRef setup[count + 2];
2250 setup[0] = _this;
2251 setup[1] = object;
2252 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2253 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2254 }
2255
2256 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2257 CYPool pool;
2258 Functor_privateData *data(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2259 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
2260 }
2261
2262 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2263 CYTry {
2264 if (count != 1)
2265 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2266 const char *name(CYCastCString(context, arguments[0]));
2267 return CYMakeSelector(context, sel_registerName(name));
2268 } CYCatch
2269 }
2270
2271 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2272 CYTry {
2273 if (count != 2)
2274 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2275
2276 void *value(CYCastPointer<void *>(context, arguments[0]));
2277 const char *type(CYCastCString(context, arguments[1]));
2278
2279 CYPool pool;
2280
2281 sig::Signature signature;
2282 sig::Parse(pool, &signature, type, &Structor_);
2283
2284 return CYMakePointer(context, value, signature.elements[0].type, NULL);
2285 } CYCatch
2286 }
2287
2288 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2289 Type_privateData *internal(new Type_privateData(NULL, type));
2290 return JSObjectMake(context, Type_, internal);
2291 }
2292
2293 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2294 CYTry {
2295 if (count != 1)
2296 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2297 const char *type(CYCastCString(context, arguments[0]));
2298 return CYMakeType(context, object, type);
2299 } CYCatch
2300 }
2301
2302 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2303 CYTry {
2304 if (count != 1)
2305 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2306 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2307 sig::Type *type(internal->type_);
2308 ffi_type *ffi(internal->GetFFI());
2309 // XXX: alignment?
2310 uint8_t value[ffi->size];
2311 CYPool pool;
2312 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2313 return CYFromFFI(context, type, ffi, value);
2314 } CYCatch
2315 }
2316
2317 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2318 CYTry {
2319 if (count > 1)
2320 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2321 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2322 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2323 // XXX: alignment?
2324 void *value(malloc(internal->GetFFI()->size * size));
2325 return CYMakePointer(context, value, internal->type_, NULL);
2326 } CYCatch
2327 }
2328
2329 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2330 CYTry {
2331 if (count != 2)
2332 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2333 const char *type(CYCastCString(context, arguments[1]));
2334 JSValueRef exception(NULL);
2335 if (JSValueIsInstanceOfConstructor(context, arguments[0], Function_, &exception)) {
2336 JSObjectRef function(CYCastJSObject(context, arguments[0]));
2337 return CYMakeFunctor(context, function, type);
2338 } else if (exception != NULL) {
2339 return NULL;
2340 } else {
2341 void (*function)()(CYCastPointer<void (*)()>(context, arguments[0]));
2342 return CYMakeFunctor(context, function, type);
2343 }
2344 } CYCatch
2345 }
2346
2347 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2348 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2349 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2350 }
2351
2352 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2353 return Function_;
2354 }
2355
2356 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2357 CYTry {
2358 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2359 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2360 } CYCatch
2361 }
2362
2363 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2364 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
2365 }
2366
2367 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2368 CYTry {
2369 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
2370 char string[32];
2371 sprintf(string, "%p", internal->value_);
2372 return CYCastJSValue(context, string);
2373 } CYCatch
2374 }
2375
2376 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2377 CYTry {
2378 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2379 CYPoolTry {
2380 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toCYON]));
2381 } CYPoolCatch(NULL)
2382 } CYCatch
2383 }
2384
2385 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2386 CYTry {
2387 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2388 CYPoolTry {
2389 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
2390 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
2391 } CYPoolCatch(NULL)
2392 } CYCatch
2393 }
2394
2395 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2396 CYTry {
2397 Instance *data(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
2398 CYPoolTry {
2399 return CYCastJSValue(context, CYJSString([data->GetValue() description]));
2400 } CYPoolCatch(NULL)
2401 } CYCatch
2402 }
2403
2404 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2405 CYTry {
2406 Selector_privateData *data(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2407 return CYCastJSValue(context, sel_getName(data->GetValue()));
2408 } CYCatch
2409 }
2410
2411 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2412 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
2413 }
2414
2415 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2416 CYTry {
2417 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2418 const char *name(sel_getName(internal->GetValue()));
2419 CYPoolTry {
2420 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
2421 } CYPoolCatch(NULL)
2422 } CYCatch
2423 }
2424
2425 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2426 CYTry {
2427 if (count != 1)
2428 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
2429 CYPool pool;
2430 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
2431 Class _class(CYCastNSObject(pool, context, arguments[0]));
2432 SEL sel(internal->GetValue());
2433 if (Method method = class_getInstanceMethod(_class, sel))
2434 return CYCastJSValue(context, method_getTypeEncoding(method));
2435 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
2436 return CYCastJSValue(context, CYJSString(type));
2437 else
2438 return CYJSNull(context);
2439 } CYCatch
2440 }
2441
2442 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2443 CYTry {
2444 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2445 CYPool pool;
2446 const char *type(sig::Unparse(pool, internal->type_));
2447 CYPoolTry {
2448 return CYCastJSValue(context, CYJSString(type));
2449 } CYPoolCatch(NULL)
2450 } CYCatch
2451 }
2452
2453 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2454 CYTry {
2455 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
2456 CYPool pool;
2457 const char *type(sig::Unparse(pool, internal->type_));
2458 CYPoolTry {
2459 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
2460 } CYPoolCatch(NULL)
2461 } CYCatch
2462 }
2463
2464 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2465 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
2466 }
2467
2468 static JSStaticValue CYValue_staticValues[2] = {
2469 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2470 {NULL, NULL, NULL, 0}
2471 };
2472
2473 static JSStaticFunction Pointer_staticFunctions[4] = {
2474 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2475 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2476 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2477 {NULL, NULL, 0}
2478 };
2479
2480 static JSStaticFunction Functor_staticFunctions[4] = {
2481 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2482 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2483 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2484 {NULL, NULL, 0}
2485 };
2486
2487 /*static JSStaticValue Selector_staticValues[2] = {
2488 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
2489 {NULL, NULL, NULL, 0}
2490 };*/
2491
2492 static JSStaticFunction Instance_staticFunctions[4] = {
2493 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2494 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2495 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2496 {NULL, NULL, 0}
2497 };
2498
2499 static JSStaticFunction Selector_staticFunctions[5] = {
2500 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2501 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2502 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2503 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2504 {NULL, NULL, 0}
2505 };
2506
2507 static JSStaticFunction Type_staticFunctions[5] = {
2508 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2509 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2510 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
2511 {NULL, NULL, 0}
2512 };
2513
2514 CYDriver::CYDriver(const std::string &filename) :
2515 state_(CYClear),
2516 data_(NULL),
2517 size_(0),
2518 filename_(filename),
2519 source_(NULL)
2520 {
2521 ScannerInit();
2522 }
2523
2524 CYDriver::~CYDriver() {
2525 ScannerDestroy();
2526 }
2527
2528 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
2529 CYDriver::Error error;
2530 error.location_ = location;
2531 error.message_ = message;
2532 driver.errors_.push_back(error);
2533 }
2534
2535 void CYSetArgs(int argc, const char *argv[]) {
2536 JSContextRef context(CYGetJSContext());
2537 JSValueRef args[argc];
2538 for (int i(0); i != argc; ++i)
2539 args[i] = CYCastJSValue(context, argv[i]);
2540 JSValueRef exception(NULL);
2541 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
2542 CYThrow(context, exception);
2543 CYSetProperty(context, System_, CYJSString("args"), array);
2544 }
2545
2546 JSObjectRef CYGetGlobalObject(JSContextRef context) {
2547 return JSContextGetGlobalObject(context);
2548 }
2549
2550 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
2551 JSContextRef context(CYGetJSContext());
2552 JSValueRef exception(NULL), result;
2553
2554 try {
2555 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
2556 } catch (const char *error) {
2557 return error;
2558 }
2559
2560 if (exception != NULL) { error:
2561 result = exception;
2562 exception = NULL;
2563 }
2564
2565 if (JSValueIsUndefined(context, result))
2566 return NULL;
2567
2568 const char *json(CYPoolCCYON(pool, context, result, &exception));
2569 if (exception != NULL)
2570 goto error;
2571
2572 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
2573 return json;
2574 }
2575
2576 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
2577 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
2578 data += writ;
2579 size -= writ;
2580 } else
2581 return false;
2582 return true;
2583 }
2584
2585 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
2586 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
2587 data += writ;
2588 size -= writ;
2589 } else
2590 return false;
2591 return true;
2592 }
2593
2594 static int Socket_;
2595 apr_pool_t *Pool_;
2596
2597 struct CYExecute_ {
2598 apr_pool_t *pool_;
2599 const char * volatile data_;
2600 };
2601
2602 // XXX: this is "tre lame"
2603 @interface CYClient_ : NSObject {
2604 }
2605
2606 - (void) execute:(NSValue *)value;
2607
2608 @end
2609
2610 @implementation CYClient_
2611
2612 - (void) execute:(NSValue *)value {
2613 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
2614 const char *data(execute->data_);
2615 execute->data_ = NULL;
2616 execute->data_ = CYExecute(execute->pool_, data);
2617 }
2618
2619 @end
2620
2621 struct CYClient :
2622 CYData
2623 {
2624 int socket_;
2625 apr_thread_t *thread_;
2626
2627 CYClient(int socket) :
2628 socket_(socket)
2629 {
2630 }
2631
2632 ~CYClient() {
2633 _syscall(close(socket_));
2634 }
2635
2636 void Handle() { _pooled
2637 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
2638
2639 for (;;) {
2640 size_t size;
2641 if (!CYRecvAll(socket_, &size, sizeof(size)))
2642 return;
2643
2644 CYPool pool;
2645 char *data(new(pool) char[size + 1]);
2646 if (!CYRecvAll(socket_, data, size))
2647 return;
2648 data[size] = '\0';
2649
2650 CYDriver driver("");
2651 cy::parser parser(driver);
2652
2653 driver.data_ = data;
2654 driver.size_ = size;
2655
2656 const char *json;
2657 if (parser.parse() != 0 || !driver.errors_.empty()) {
2658 json = NULL;
2659 size = _not(size_t);
2660 } else {
2661 std::ostringstream str;
2662 driver.source_->Show(str);
2663 std::string code(str.str());
2664 CYExecute_ execute = {pool, code.c_str()};
2665 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
2666 json = execute.data_;
2667 size = json == NULL ? _not(size_t) : strlen(json);
2668 }
2669
2670 if (!CYSendAll(socket_, &size, sizeof(size)))
2671 return;
2672 if (json != NULL)
2673 if (!CYSendAll(socket_, json, size))
2674 return;
2675 }
2676 }
2677 };
2678
2679 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
2680 CYClient *client(reinterpret_cast<CYClient *>(data));
2681 client->Handle();
2682 delete client;
2683 return NULL;
2684 }
2685
2686 static void * APR_THREAD_FUNC Cyrver(apr_thread_t *thread, void *data) {
2687 for (;;) {
2688 int socket(_syscall(accept(Socket_, NULL, NULL)));
2689 CYClient *client(new CYClient(socket));
2690 apr_threadattr_t *attr;
2691 _aprcall(apr_threadattr_create(&attr, Pool_));
2692 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
2693 }
2694
2695 return NULL;
2696 }
2697
2698 void Unlink() {
2699 pid_t pid(getpid());
2700 char path[104];
2701 sprintf(path, "/tmp/.s.cy.%u", pid);
2702 unlink(path);
2703 }
2704
2705 MSInitialize { _pooled
2706 _aprcall(apr_initialize());
2707 _aprcall(apr_pool_create(&Pool_, NULL));
2708
2709 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
2710
2711 NSCFBoolean_ = objc_getClass("NSCFBoolean");
2712 NSCFType_ = objc_getClass("NSCFType");
2713 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
2714 NSZombie_ = objc_getClass("_NSZombie_");
2715 Object_ = objc_getClass("Object");
2716
2717 Socket_ = _syscall(socket(PF_UNIX, SOCK_STREAM, 0));
2718
2719 struct sockaddr_un address;
2720 memset(&address, 0, sizeof(address));
2721 address.sun_family = AF_UNIX;
2722
2723 pid_t pid(getpid());
2724 sprintf(address.sun_path, "/tmp/.s.cy.%u", pid);
2725
2726 try {
2727 _syscall(bind(Socket_, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
2728 atexit(&Unlink);
2729 _syscall(listen(Socket_, 0));
2730
2731 apr_threadattr_t *attr;
2732 _aprcall(apr_threadattr_create(&attr, Pool_));
2733
2734 apr_thread_t *thread;
2735 _aprcall(apr_thread_create(&thread, attr, &Cyrver, NULL, Pool_));
2736 } catch (...) {
2737 NSLog(@"failed to setup Cyrver");
2738 }
2739 }
2740
2741 JSGlobalContextRef CYGetJSContext() {
2742 if (Context_ == NULL) {
2743 JSClassDefinition definition;
2744
2745 definition = kJSClassDefinitionEmpty;
2746 definition.className = "Functor";
2747 definition.staticFunctions = Functor_staticFunctions;
2748 definition.callAsFunction = &Functor_callAsFunction;
2749 definition.finalize = &CYData::Finalize;
2750 Functor_ = JSClassCreate(&definition);
2751
2752 definition = kJSClassDefinitionEmpty;
2753 definition.className = "Instance";
2754 definition.staticValues = CYValue_staticValues;
2755 definition.staticFunctions = Instance_staticFunctions;
2756 definition.getProperty = &Instance_getProperty;
2757 definition.setProperty = &Instance_setProperty;
2758 definition.deleteProperty = &Instance_deleteProperty;
2759 definition.getPropertyNames = &Instance_getPropertyNames;
2760 definition.callAsConstructor = &Instance_callAsConstructor;
2761 definition.finalize = &CYData::Finalize;
2762 Instance_ = JSClassCreate(&definition);
2763
2764 definition = kJSClassDefinitionEmpty;
2765 definition.className = "Pointer";
2766 definition.staticFunctions = Pointer_staticFunctions;
2767 definition.getProperty = &Pointer_getProperty;
2768 definition.setProperty = &Pointer_setProperty;
2769 definition.finalize = &CYData::Finalize;
2770 Pointer_ = JSClassCreate(&definition);
2771
2772 definition = kJSClassDefinitionEmpty;
2773 definition.className = "Selector";
2774 definition.staticValues = CYValue_staticValues;
2775 //definition.staticValues = Selector_staticValues;
2776 definition.staticFunctions = Selector_staticFunctions;
2777 definition.callAsFunction = &Selector_callAsFunction;
2778 definition.finalize = &CYData::Finalize;
2779 Selector_ = JSClassCreate(&definition);
2780
2781 definition = kJSClassDefinitionEmpty;
2782 definition.className = "Struct";
2783 definition.getProperty = &Struct_getProperty;
2784 definition.setProperty = &Struct_setProperty;
2785 definition.getPropertyNames = &Struct_getPropertyNames;
2786 definition.finalize = &CYData::Finalize;
2787 Struct_ = JSClassCreate(&definition);
2788
2789 definition = kJSClassDefinitionEmpty;
2790 definition.className = "Type";
2791 definition.staticFunctions = Type_staticFunctions;
2792 //definition.getProperty = &Type_getProperty;
2793 definition.callAsFunction = &Type_callAsFunction;
2794 definition.callAsConstructor = &Type_callAsConstructor;
2795 definition.finalize = &CYData::Finalize;
2796 Type_ = JSClassCreate(&definition);
2797
2798 definition = kJSClassDefinitionEmpty;
2799 definition.className = "Runtime";
2800 definition.getProperty = &Runtime_getProperty;
2801 Runtime_ = JSClassCreate(&definition);
2802
2803 definition = kJSClassDefinitionEmpty;
2804 definition.className = "ObjectiveC::Classes";
2805 definition.getProperty = &ObjectiveC_Classes_getProperty;
2806 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
2807 ObjectiveC_Classes_ = JSClassCreate(&definition);
2808
2809 definition = kJSClassDefinitionEmpty;
2810 definition.className = "ObjectiveC::Images";
2811 definition.getProperty = &ObjectiveC_Images_getProperty;
2812 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
2813 ObjectiveC_Images_ = JSClassCreate(&definition);
2814
2815 definition = kJSClassDefinitionEmpty;
2816 definition.className = "ObjectiveC::Image::Classes";
2817 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
2818 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
2819 definition.finalize = &CYData::Finalize;
2820 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
2821
2822 definition = kJSClassDefinitionEmpty;
2823 definition.className = "ObjectiveC::Protocols";
2824 definition.getProperty = &ObjectiveC_Protocols_getProperty;
2825 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
2826 ObjectiveC_Protocols_ = JSClassCreate(&definition);
2827
2828 definition = kJSClassDefinitionEmpty;
2829 //definition.getProperty = &Global_getProperty;
2830 JSClassRef Global(JSClassCreate(&definition));
2831
2832 JSGlobalContextRef context(JSGlobalContextCreate(Global));
2833 Context_ = context;
2834
2835 JSObjectRef global(CYGetGlobalObject(context));
2836
2837 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
2838 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
2839 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
2840
2841 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
2842 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
2843 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
2844
2845 CYSetProperty(context, global, CYJSString("Functor"), JSObjectMakeConstructor(context, Functor_, &Functor_new));
2846 CYSetProperty(context, global, CYJSString("Instance"), JSObjectMakeConstructor(context, Instance_, NULL));
2847 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
2848 CYSetProperty(context, global, CYJSString("Selector"), JSObjectMakeConstructor(context, Selector_, &Selector_new));
2849 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
2850
2851 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
2852
2853 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
2854
2855 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
2856 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
2857
2858 System_ = JSObjectMake(context, NULL, NULL);
2859 CYSetProperty(context, global, CYJSString("system"), System_);
2860 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
2861 //CYSetProperty(context, System_, CYJSString("global"), global);
2862
2863 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
2864
2865 Result_ = JSStringCreateWithUTF8CString("_");
2866
2867 length_ = JSStringCreateWithUTF8CString("length");
2868 message_ = JSStringCreateWithUTF8CString("message");
2869 name_ = JSStringCreateWithUTF8CString("name");
2870 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
2871 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
2872
2873 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
2874 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
2875 }
2876
2877 return Context_;
2878 }