]> git.saurik.com Git - cycript.git/blob - Library.mm
Fixed memory protection conditions (now that I finally have a GC test case) and imple...
[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 <CoreFoundation/CoreFoundation.h>
52 #include <CoreFoundation/CFLogUtilities.h>
53
54 #include <WebKit/WebScriptObject.h>
55
56 #include <sys/mman.h>
57
58 #include <iostream>
59 #include <ext/stdio_filebuf.h>
60 #include <set>
61 #include <map>
62
63 #include <sstream>
64 #include <cmath>
65
66 #include "Parser.hpp"
67 #include "Cycript.tab.hh"
68
69 #include <apr-1/apr_thread_proc.h>
70
71 #undef _assert
72 #undef _trace
73
74 #define _assert(test) do { \
75 if (!(test)) \
76 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
77 } while (false)
78
79 #define _trace() do { \
80 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
81 } while (false)
82
83 #define CYPoolTry { \
84 id _saved(nil); \
85 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
86 @try
87 #define CYPoolCatch(value) \
88 @catch (NSException *error) { \
89 _saved = [error retain]; \
90 @throw; \
91 return value; \
92 } @finally { \
93 [_pool release]; \
94 if (_saved != nil) \
95 [_saved autorelease]; \
96 } \
97 }
98
99 void CYThrow(JSContextRef context, JSValueRef value);
100
101 /* JavaScript Properties {{{ */
102 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
103 JSValueRef exception(NULL);
104 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
105 CYThrow(context, exception);
106 return value;
107 }
108
109 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
110 JSValueRef exception(NULL);
111 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
112 CYThrow(context, exception);
113 return value;
114 }
115
116 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
117 JSValueRef exception(NULL);
118 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
119 CYThrow(context, exception);
120 }
121
122 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
123 JSValueRef exception(NULL);
124 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
125 CYThrow(context, exception);
126 }
127 /* }}} */
128 /* JavaScript Strings {{{ */
129 JSStringRef CYCopyJSString(id value) {
130 // XXX: this definition scares me; is anyone using this?!
131 return value == NULL ? NULL : JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
132 }
133
134 JSStringRef CYCopyJSString(const char *value) {
135 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
136 }
137
138 JSStringRef CYCopyJSString(JSStringRef value) {
139 return value == NULL ? NULL : JSStringRetain(value);
140 }
141
142 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
143 if (JSValueIsNull(context, value))
144 return NULL;
145 JSValueRef exception(NULL);
146 JSStringRef string(JSValueToStringCopy(context, value, &exception));
147 CYThrow(context, exception);
148 return string;
149 }
150
151 class CYJSString {
152 private:
153 JSStringRef string_;
154
155 void Clear_() {
156 if (string_ != NULL)
157 JSStringRelease(string_);
158 }
159
160 public:
161 CYJSString(const CYJSString &rhs) :
162 string_(CYCopyJSString(rhs.string_))
163 {
164 }
165
166 template <typename Arg0_>
167 CYJSString(Arg0_ arg0) :
168 string_(CYCopyJSString(arg0))
169 {
170 }
171
172 template <typename Arg0_, typename Arg1_>
173 CYJSString(Arg0_ arg0, Arg1_ arg1) :
174 string_(CYCopyJSString(arg0, arg1))
175 {
176 }
177
178 CYJSString &operator =(const CYJSString &rhs) {
179 Clear_();
180 string_ = CYCopyJSString(rhs.string_);
181 return *this;
182 }
183
184 ~CYJSString() {
185 Clear_();
186 }
187
188 void Clear() {
189 Clear_();
190 string_ = NULL;
191 }
192
193 operator JSStringRef() const {
194 return string_;
195 }
196 };
197
198 CFStringRef CYCopyCFString(JSStringRef value) {
199 return JSStringCopyCFString(kCFAllocatorDefault, value);
200 }
201
202 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
203 return CYCopyCFString(CYJSString(context, value));
204 }
205
206 /* }}} */
207
208 static JSGlobalContextRef Context_;
209 static JSObjectRef System_;
210 static JSObjectRef ObjectiveC_;
211
212 static JSClassRef Functor_;
213 static JSClassRef Instance_;
214 static JSClassRef Internal_;
215 static JSClassRef Message_;
216 static JSClassRef Messages_;
217 static JSClassRef NSArrayPrototype_;
218 static JSClassRef Pointer_;
219 static JSClassRef Runtime_;
220 static JSClassRef Selector_;
221 static JSClassRef Struct_;
222 static JSClassRef Type_;
223
224 static JSClassRef ObjectiveC_Classes_;
225 static JSClassRef ObjectiveC_Image_Classes_;
226 static JSClassRef ObjectiveC_Images_;
227 static JSClassRef ObjectiveC_Protocols_;
228
229 static JSObjectRef Array_;
230 static JSObjectRef Function_;
231 static JSObjectRef String_;
232
233 static JSStringRef Result_;
234
235 static JSStringRef length_;
236 static JSStringRef message_;
237 static JSStringRef name_;
238 static JSStringRef prototype_;
239 static JSStringRef toCYON_;
240 static JSStringRef toJSON_;
241
242 static JSObjectRef Instance_prototype_;
243 static JSObjectRef Object_prototype_;
244
245 static JSObjectRef Array_prototype_;
246 static JSObjectRef Array_pop_;
247 static JSObjectRef Array_push_;
248 static JSObjectRef Array_splice_;
249
250 static Class NSArray_;
251 static Class NSCFBoolean_;
252 static Class NSCFType_;
253 static Class NSDictionary_;
254 static Class NSMessageBuilder_;
255 static Class NSZombie_;
256 static Class Object_;
257
258 static NSArray *Bridge_;
259
260 static void Finalize(JSObjectRef object) {
261 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
262 }
263
264 class Type_privateData;
265
266 struct CYValue :
267 CYData
268 {
269 void *value_;
270
271 CYValue() {
272 }
273
274 CYValue(void *value) :
275 value_(value)
276 {
277 }
278
279 CYValue(const CYValue &rhs) :
280 value_(rhs.value_)
281 {
282 }
283
284 virtual Type_privateData *GetType() const {
285 return NULL;
286 }
287 };
288
289 struct Selector_privateData :
290 CYValue
291 {
292 Selector_privateData(SEL value) :
293 CYValue(value)
294 {
295 }
296
297 SEL GetValue() const {
298 return reinterpret_cast<SEL>(value_);
299 }
300
301 virtual Type_privateData *GetType() const;
302 };
303
304 // XXX: trick this out with associated objects!
305 JSValueRef CYGetClassPrototype(JSContextRef context, id self) {
306 if (self == nil)
307 return Instance_prototype_;
308
309 // XXX: I need to think through multi-context
310 typedef std::map<Class, JSValueRef> CacheMap;
311 static CacheMap cache_;
312
313 JSValueRef &value(cache_[self]);
314 if (value != NULL)
315 return value;
316
317 JSClassRef _class(NULL);
318 JSValueRef prototype;
319
320 if (self == NSArray_)
321 prototype = Array_prototype_;
322 else if (self == NSDictionary_)
323 prototype = Object_prototype_;
324 else
325 prototype = CYGetClassPrototype(context, class_getSuperclass(self));
326
327 JSObjectRef object(JSObjectMake(context, _class, NULL));
328 JSObjectSetPrototype(context, object, prototype);
329
330 JSValueProtect(context, object);
331 value = object;
332 return object;
333 }
334
335 struct Instance :
336 CYValue
337 {
338 enum Flags {
339 None = 0,
340 Transient = (1 << 0),
341 Uninitialized = (1 << 1),
342 };
343
344 Flags flags_;
345
346 Instance(id value, Flags flags) :
347 CYValue(value),
348 flags_(flags)
349 {
350 }
351
352 virtual ~Instance() {
353 if ((flags_ & Transient) == 0)
354 // XXX: does this handle background threads correctly?
355 [GetValue() performSelector:@selector(release) withObject:nil afterDelay:0];
356 }
357
358 static JSObjectRef Make(JSContextRef context, id object, Flags flags = None) {
359 JSObjectRef value(JSObjectMake(context, Instance_, new Instance(object, flags)));
360 JSObjectSetPrototype(context, value, CYGetClassPrototype(context, object == nil ? nil : object_getClass(object)));
361 return value;
362 }
363
364 id GetValue() const {
365 return reinterpret_cast<id>(value_);
366 }
367
368 bool IsUninitialized() const {
369 return (flags_ & Uninitialized) != 0;
370 }
371
372 virtual Type_privateData *GetType() const;
373 };
374
375 struct Messages :
376 CYValue
377 {
378 Messages(Class value) :
379 CYValue(value)
380 {
381 }
382
383 static JSObjectRef Make(JSContextRef context, Class _class, bool array = false) {
384 JSObjectRef value(JSObjectMake(context, Messages_, new Messages(_class)));
385 if (_class == NSArray_)
386 array = true;
387 if (Class super = class_getSuperclass(_class))
388 JSObjectSetPrototype(context, value, Messages::Make(context, super, array));
389 /*else if (array)
390 JSObjectSetPrototype(context, value, Array_prototype_);*/
391 return value;
392 }
393
394 Class GetValue() const {
395 return reinterpret_cast<Class>(value_);
396 }
397 };
398
399 struct CYOwned :
400 CYValue
401 {
402 private:
403 JSContextRef context_;
404 JSObjectRef owner_;
405
406 public:
407 CYOwned(void *value, JSContextRef context, JSObjectRef owner) :
408 CYValue(value),
409 context_(context),
410 owner_(owner)
411 {
412 JSValueProtect(context_, owner_);
413 }
414
415 virtual ~CYOwned() {
416 JSValueUnprotect(context_, owner_);
417 }
418
419 JSObjectRef GetOwner() const {
420 return owner_;
421 }
422 };
423
424 struct Internal :
425 CYOwned
426 {
427 Internal(id value, JSContextRef context, JSObjectRef owner) :
428 CYOwned(value, context, owner)
429 {
430 }
431
432 static JSObjectRef Make(JSContextRef context, id object, JSObjectRef owner) {
433 return JSObjectMake(context, Internal_, new Internal(object, context, owner));
434 }
435
436 id GetValue() const {
437 return reinterpret_cast<id>(value_);
438 }
439 };
440
441 namespace sig {
442
443 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs);
444
445 void Copy(apr_pool_t *pool, Element &lhs, Element &rhs) {
446 lhs.name = apr_pstrdup(pool, rhs.name);
447 if (rhs.type == NULL)
448 lhs.type = NULL;
449 else {
450 lhs.type = new(pool) Type;
451 Copy(pool, *lhs.type, *rhs.type);
452 }
453 lhs.offset = rhs.offset;
454 }
455
456 void Copy(apr_pool_t *pool, Signature &lhs, Signature &rhs) {
457 size_t count(rhs.count);
458 lhs.count = count;
459 lhs.elements = new(pool) Element[count];
460 for (size_t index(0); index != count; ++index)
461 Copy(pool, lhs.elements[index], rhs.elements[index]);
462 }
463
464 void Copy(apr_pool_t *pool, Type &lhs, Type &rhs) {
465 lhs.primitive = rhs.primitive;
466 lhs.name = apr_pstrdup(pool, rhs.name);
467 lhs.flags = rhs.flags;
468
469 if (sig::IsAggregate(rhs.primitive))
470 Copy(pool, lhs.data.signature, rhs.data.signature);
471 else {
472 if (rhs.data.data.type != NULL) {
473 lhs.data.data.type = new(pool) Type;
474 Copy(pool, *lhs.data.data.type, *rhs.data.data.type);
475 }
476
477 lhs.data.data.size = rhs.data.data.size;
478 }
479 }
480
481 void Copy(apr_pool_t *pool, ffi_type &lhs, ffi_type &rhs) {
482 lhs.size = rhs.size;
483 lhs.alignment = rhs.alignment;
484 lhs.type = rhs.type;
485 if (rhs.elements == NULL)
486 lhs.elements = NULL;
487 else {
488 size_t count(0);
489 while (rhs.elements[count] != NULL)
490 ++count;
491
492 lhs.elements = new(pool) ffi_type *[count + 1];
493 lhs.elements[count] = NULL;
494
495 for (size_t index(0); index != count; ++index) {
496 // XXX: if these are libffi native then you can just take them
497 ffi_type *ffi(new(pool) ffi_type);
498 lhs.elements[index] = ffi;
499 sig::Copy(pool, *ffi, *rhs.elements[index]);
500 }
501 }
502 }
503
504 }
505
506 struct CStringMapLess :
507 std::binary_function<const char *, const char *, bool>
508 {
509 _finline bool operator ()(const char *lhs, const char *rhs) const {
510 return strcmp(lhs, rhs) < 0;
511 }
512 };
513
514 void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
515 if (name == NULL)
516 return;
517
518 CYPoolTry {
519 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:2] objectForKey:[NSString stringWithUTF8String:name]])
520 switch ([[entry objectAtIndex:0] intValue]) {
521 case 0: {
522 sig::Parse(pool, &type->data.signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
523 } break;
524
525 case 1: {
526 sig::Signature signature;
527 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String], &Structor_);
528 type = signature.elements[0].type;
529 } break;
530 }
531 } CYPoolCatch()
532 }
533
534 struct Type_privateData :
535 CYData
536 {
537 static Type_privateData *Object;
538 static Type_privateData *Selector;
539
540 ffi_type *ffi_;
541 sig::Type *type_;
542
543 void Set(sig::Type *type) {
544 type_ = new(pool_) sig::Type;
545 sig::Copy(pool_, *type_, *type);
546 }
547
548 Type_privateData(apr_pool_t *pool, const char *type) :
549 ffi_(NULL)
550 {
551 if (pool != NULL)
552 pool_ = pool;
553
554 sig::Signature signature;
555 sig::Parse(pool_, &signature, type, &Structor_);
556 type_ = signature.elements[0].type;
557 }
558
559 Type_privateData(sig::Type *type) :
560 ffi_(NULL)
561 {
562 if (type != NULL)
563 Set(type);
564 }
565
566 Type_privateData(sig::Type *type, ffi_type *ffi) {
567 ffi_ = new(pool_) ffi_type;
568 sig::Copy(pool_, *ffi_, *ffi);
569 Set(type);
570 }
571
572 ffi_type *GetFFI() {
573 if (ffi_ == NULL) {
574 ffi_ = new(pool_) ffi_type;
575
576 sig::Element element;
577 element.name = NULL;
578 element.type = type_;
579 element.offset = 0;
580
581 sig::Signature signature;
582 signature.elements = &element;
583 signature.count = 1;
584
585 ffi_cif cif;
586 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature, &cif);
587 *ffi_ = *cif.rtype;
588 }
589
590 return ffi_;
591 }
592 };
593
594 Type_privateData *Type_privateData::Object;
595 Type_privateData *Type_privateData::Selector;
596
597 Type_privateData *Instance::GetType() const {
598 return Type_privateData::Object;
599 }
600
601 Type_privateData *Selector_privateData::GetType() const {
602 return Type_privateData::Selector;
603 }
604
605 struct Pointer :
606 CYOwned
607 {
608 Type_privateData *type_;
609
610 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
611 CYOwned(value, context, owner),
612 type_(new(pool_) Type_privateData(type))
613 {
614 }
615 };
616
617 struct Struct_privateData :
618 CYOwned
619 {
620 Type_privateData *type_;
621
622 Struct_privateData(JSContextRef context, JSObjectRef owner) :
623 CYOwned(NULL, context, owner)
624 {
625 }
626 };
627
628 typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
629 static TypeMap Types_;
630
631 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
632 Struct_privateData *internal(new Struct_privateData(context, owner));
633 apr_pool_t *pool(internal->pool_);
634 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
635 internal->type_ = typical;
636
637 if (owner != NULL)
638 internal->value_ = data;
639 else {
640 size_t size(typical->GetFFI()->size);
641 void *copy(apr_palloc(internal->pool_, size));
642 memcpy(copy, data, size);
643 internal->value_ = copy;
644 }
645
646 return JSObjectMake(context, Struct_, internal);
647 }
648
649 struct Functor_privateData :
650 CYValue
651 {
652 sig::Signature signature_;
653 ffi_cif cif_;
654
655
656 Functor_privateData(const char *type, void (*value)()) :
657 CYValue(reinterpret_cast<void *>(value))
658 {
659 sig::Parse(pool_, &signature_, type, &Structor_);
660 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
661 }
662
663 void (*GetValue())() const {
664 return reinterpret_cast<void (*)()>(value_);
665 }
666 };
667
668 struct Closure_privateData :
669 Functor_privateData
670 {
671 JSContextRef context_;
672 JSObjectRef function_;
673
674 Closure_privateData(JSContextRef context, JSObjectRef function, const char *type) :
675 Functor_privateData(type, NULL),
676 context_(context),
677 function_(function)
678 {
679 JSValueProtect(context_, function_);
680 }
681
682 virtual ~Closure_privateData() {
683 JSValueUnprotect(context_, function_);
684 }
685 };
686
687 struct Message_privateData :
688 Functor_privateData
689 {
690 SEL sel_;
691
692 Message_privateData(SEL sel, const char *type, IMP value = NULL) :
693 Functor_privateData(type, reinterpret_cast<void (*)()>(value)),
694 sel_(sel)
695 {
696 }
697 };
698
699 JSObjectRef CYMakeInstance(JSContextRef context, id object, bool transient) {
700 Instance::Flags flags;
701
702 if (transient)
703 flags = Instance::Transient;
704 else {
705 flags = Instance::None;
706 object = [object retain];
707 }
708
709 return Instance::Make(context, object, flags);
710 }
711
712 const char *CYPoolCString(apr_pool_t *pool, NSString *value) {
713 if (pool == NULL)
714 return [value UTF8String];
715 else {
716 size_t size([value maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1);
717 char *string(new(pool) char[size]);
718 if (![value getCString:string maxLength:size encoding:NSUTF8StringEncoding])
719 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[NSString getCString:maxLength:encoding:] == NO" userInfo:nil];
720 return string;
721 }
722 }
723
724 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
725 return JSValueMakeBoolean(context, value);
726 }
727
728 JSValueRef CYCastJSValue(JSContextRef context, double value) {
729 return JSValueMakeNumber(context, value);
730 }
731
732 #define CYCastJSValue_(Type_) \
733 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
734 return JSValueMakeNumber(context, static_cast<double>(value)); \
735 }
736
737 CYCastJSValue_(int)
738 CYCastJSValue_(unsigned int)
739 CYCastJSValue_(long int)
740 CYCastJSValue_(long unsigned int)
741 CYCastJSValue_(long long int)
742 CYCastJSValue_(long long unsigned int)
743
744 JSValueRef CYJSUndefined(JSContextRef context) {
745 return JSValueMakeUndefined(context);
746 }
747
748 size_t CYGetIndex(const char *value) {
749 if (value[0] != '0') {
750 char *end;
751 size_t index(strtoul(value, &end, 10));
752 if (value + strlen(value) == end)
753 return index;
754 } else if (value[1] == '\0')
755 return 0;
756 return _not(size_t);
757 }
758
759 size_t CYGetIndex(apr_pool_t *pool, NSString *value) {
760 return CYGetIndex(CYPoolCString(pool, value));
761 }
762
763 bool CYGetOffset(const char *value, ssize_t &index) {
764 if (value[0] != '0') {
765 char *end;
766 index = strtol(value, &end, 10);
767 if (value + strlen(value) == end)
768 return true;
769 } else if (value[1] == '\0') {
770 index = 0;
771 return true;
772 }
773
774 return false;
775 }
776
777 bool CYGetOffset(apr_pool_t *pool, NSString *value, ssize_t &index) {
778 return CYGetOffset(CYPoolCString(pool, value), index);
779 }
780
781 NSString *CYPoolNSCYON(apr_pool_t *pool, id value);
782
783 @interface NSMethodSignature (Cycript)
784 - (NSString *) _typeString;
785 @end
786
787 @interface NSObject (Cycript)
788
789 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
790 - (JSType) cy$JSType;
791
792 - (NSObject *) cy$toJSON:(NSString *)key;
793 - (NSString *) cy$toCYON;
794 - (NSString *) cy$toKey;
795
796 - (bool) cy$hasProperty:(NSString *)name;
797 - (NSObject *) cy$getProperty:(NSString *)name;
798 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value;
799 - (bool) cy$deleteProperty:(NSString *)name;
800
801 @end
802
803 @protocol Cycript
804 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
805 @end
806
807 @interface NSString (Cycript)
808 - (void *) cy$symbol;
809 @end
810
811 struct PropertyAttributes {
812 CYPool pool_;
813
814 const char *name;
815
816 const char *variable;
817
818 const char *getter_;
819 const char *setter_;
820
821 bool readonly;
822 bool copy;
823 bool retain;
824 bool nonatomic;
825 bool dynamic;
826 bool weak;
827 bool garbage;
828
829 PropertyAttributes(objc_property_t property) :
830 variable(NULL),
831 getter_(NULL),
832 setter_(NULL),
833 readonly(false),
834 copy(false),
835 retain(false),
836 nonatomic(false),
837 dynamic(false),
838 weak(false),
839 garbage(false)
840 {
841 name = property_getName(property);
842 const char *attributes(property_getAttributes(property));
843
844 for (char *state, *token(apr_strtok(apr_pstrdup(pool_, attributes), ",", &state)); token != NULL; token = apr_strtok(NULL, ",", &state)) {
845 switch (*token) {
846 case 'R': readonly = true; break;
847 case 'C': copy = true; break;
848 case '&': retain = true; break;
849 case 'N': nonatomic = true; break;
850 case 'G': getter_ = token + 1; break;
851 case 'S': setter_ = token + 1; break;
852 case 'V': variable = token + 1; break;
853 }
854 }
855
856 /*if (variable == NULL) {
857 variable = property_getName(property);
858 size_t size(strlen(variable));
859 char *name(new(pool_) char[size + 2]);
860 name[0] = '_';
861 memcpy(name + 1, variable, size);
862 name[size + 1] = '\0';
863 variable = name;
864 }*/
865 }
866
867 const char *Getter() {
868 if (getter_ == NULL)
869 getter_ = apr_pstrdup(pool_, name);
870 return getter_;
871 }
872
873 const char *Setter() {
874 if (setter_ == NULL && !readonly) {
875 size_t length(strlen(name));
876
877 char *temp(new(pool_) char[length + 5]);
878 temp[0] = 's';
879 temp[1] = 'e';
880 temp[2] = 't';
881
882 if (length != 0) {
883 temp[3] = toupper(name[0]);
884 memcpy(temp + 4, name + 1, length - 1);
885 }
886
887 temp[length + 3] = ':';
888 temp[length + 4] = '\0';
889 setter_ = temp;
890 }
891
892 return setter_;
893 }
894
895 };
896
897 NSString *NSCFType$cy$toJSON(id self, SEL sel, NSString *key) {
898 return [(NSString *) CFCopyDescription((CFTypeRef) self) autorelease];
899 }
900
901 /* Bridge: NSArray {{{ */
902 @implementation NSArray (Cycript)
903
904 - (NSString *) cy$toCYON {
905 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
906 [json appendString:@"["];
907
908 bool comma(false);
909 for (id object in self) {
910 if (comma)
911 [json appendString:@","];
912 else
913 comma = true;
914 if (object == nil || [object cy$JSType] != kJSTypeUndefined)
915 [json appendString:CYPoolNSCYON(NULL, object)];
916 else {
917 [json appendString:@","];
918 comma = false;
919 }
920 }
921
922 [json appendString:@"]"];
923 return json;
924 }
925
926 - (bool) cy$hasProperty:(NSString *)name {
927 if ([name isEqualToString:@"length"])
928 return true;
929
930 size_t index(CYGetIndex(NULL, name));
931 if (index == _not(size_t) || index >= [self count])
932 return [super cy$hasProperty:name];
933 else
934 return true;
935 }
936
937 - (NSObject *) cy$getProperty:(NSString *)name {
938 if ([name isEqualToString:@"length"])
939 return [NSNumber numberWithUnsignedInteger:[self count]];
940
941 size_t index(CYGetIndex(NULL, name));
942 if (index == _not(size_t) || index >= [self count])
943 return [super cy$getProperty:name];
944 else
945 return [self objectAtIndex:index];
946 }
947
948 @end
949 /* }}} */
950 /* Bridge: NSDictionary {{{ */
951 @implementation NSDictionary (Cycript)
952
953 - (NSString *) cy$toCYON {
954 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
955 [json appendString:@"{"];
956
957 bool comma(false);
958 for (id key in self) {
959 if (comma)
960 [json appendString:@","];
961 else
962 comma = true;
963 [json appendString:[key cy$toKey]];
964 [json appendString:@":"];
965 NSObject *object([self objectForKey:key]);
966 [json appendString:CYPoolNSCYON(NULL, object)];
967 }
968
969 [json appendString:@"}"];
970 return json;
971 }
972
973 - (bool) cy$hasProperty:(NSString *)name {
974 return [self objectForKey:name] != nil;
975 }
976
977 - (NSObject *) cy$getProperty:(NSString *)name {
978 return [self objectForKey:name];
979 }
980
981 @end
982 /* }}} */
983 /* Bridge: NSMutableArray {{{ */
984 @implementation NSMutableArray (Cycript)
985
986 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
987 if ([name isEqualToString:@"length"]) {
988 // XXX: is this not intelligent?
989 NSUInteger size([(NSNumber *)value unsignedIntegerValue]);
990 NSUInteger count([self count]);
991 if (size < count)
992 [self removeObjectsInRange:NSMakeRange(size, count - size)];
993 else if (size != count) {
994 WebUndefined *undefined([WebUndefined undefined]);
995 for (size_t i(count); i != size; ++i)
996 [self addObject:undefined];
997 }
998 return true;
999 }
1000
1001 size_t index(CYGetIndex(NULL, name));
1002 if (index == _not(size_t))
1003 return [super cy$setProperty:name to:value];
1004
1005 id object(value ?: [NSNull null]);
1006
1007 size_t count([self count]);
1008 if (index < count)
1009 [self replaceObjectAtIndex:index withObject:object];
1010 else {
1011 if (index != count) {
1012 WebUndefined *undefined([WebUndefined undefined]);
1013 for (size_t i(count); i != index; ++i)
1014 [self addObject:undefined];
1015 }
1016
1017 [self addObject:object];
1018 }
1019
1020 return true;
1021 }
1022
1023 - (bool) cy$deleteProperty:(NSString *)name {
1024 size_t index(CYGetIndex(NULL, name));
1025 if (index == _not(size_t) || index >= [self count])
1026 return [super cy$deleteProperty:name];
1027 [self replaceObjectAtIndex:index withObject:[WebUndefined undefined]];
1028 return true;
1029 }
1030
1031 @end
1032 /* }}} */
1033 /* Bridge: NSMutableDictionary {{{ */
1034 @implementation NSMutableDictionary (Cycript)
1035
1036 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1037 [self setObject:(value ?: [NSNull null]) forKey:name];
1038 return true;
1039 }
1040
1041 - (bool) cy$deleteProperty:(NSString *)name {
1042 if ([self objectForKey:name] == nil)
1043 return false;
1044 else {
1045 [self removeObjectForKey:name];
1046 return true;
1047 }
1048 }
1049
1050 @end
1051 /* }}} */
1052 /* Bridge: NSNumber {{{ */
1053 @implementation NSNumber (Cycript)
1054
1055 - (JSType) cy$JSType {
1056 // XXX: this just seems stupid
1057 return [self class] == NSCFBoolean_ ? kJSTypeBoolean : kJSTypeNumber;
1058 }
1059
1060 - (NSObject *) cy$toJSON:(NSString *)key {
1061 return self;
1062 }
1063
1064 - (NSString *) cy$toCYON {
1065 return [self cy$JSType] != kJSTypeBoolean ? [self stringValue] : [self boolValue] ? @"true" : @"false";
1066 }
1067
1068 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1069 return [self cy$JSType] != kJSTypeBoolean ? CYCastJSValue(context, [self doubleValue]) : CYCastJSValue(context, [self boolValue]);
1070 }
1071
1072 @end
1073 /* }}} */
1074 /* Bridge: NSNull {{{ */
1075 @implementation NSNull (Cycript)
1076
1077 - (JSType) cy$JSType {
1078 return kJSTypeNull;
1079 }
1080
1081 - (NSObject *) cy$toJSON:(NSString *)key {
1082 return self;
1083 }
1084
1085 - (NSString *) cy$toCYON {
1086 return @"null";
1087 }
1088
1089 @end
1090 /* }}} */
1091 /* Bridge: NSObject {{{ */
1092 @implementation NSObject (Cycript)
1093
1094 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1095 return CYMakeInstance(context, self, false);
1096 }
1097
1098 - (JSType) cy$JSType {
1099 return kJSTypeObject;
1100 }
1101
1102 - (NSObject *) cy$toJSON:(NSString *)key {
1103 return [self description];
1104 }
1105
1106 - (NSString *) cy$toCYON {
1107 return [[self cy$toJSON:@""] cy$toCYON];
1108 }
1109
1110 - (NSString *) cy$toKey {
1111 return [self cy$toCYON];
1112 }
1113
1114 - (bool) cy$hasProperty:(NSString *)name {
1115 return false;
1116 }
1117
1118 - (NSObject *) cy$getProperty:(NSString *)name {
1119 return nil;
1120 }
1121
1122 - (bool) cy$setProperty:(NSString *)name to:(NSObject *)value {
1123 return false;
1124 }
1125
1126 - (bool) cy$deleteProperty:(NSString *)name {
1127 return false;
1128 }
1129
1130 @end
1131 /* }}} */
1132 /* Bridge: NSProxy {{{ */
1133 @implementation NSProxy (Cycript)
1134
1135 - (NSObject *) cy$toJSON:(NSString *)key {
1136 return [self description];
1137 }
1138
1139 - (NSString *) cy$toCYON {
1140 return [[self cy$toJSON:@""] cy$toCYON];
1141 }
1142
1143 @end
1144 /* }}} */
1145 /* Bridge: NSString {{{ */
1146 @implementation NSString (Cycript)
1147
1148 - (JSType) cy$JSType {
1149 return kJSTypeString;
1150 }
1151
1152 - (NSObject *) cy$toJSON:(NSString *)key {
1153 return self;
1154 }
1155
1156 - (NSString *) cy$toCYON {
1157 // XXX: this should use the better code from Output.cpp
1158 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
1159
1160 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
1161 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
1162 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
1163 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
1164 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
1165
1166 CFStringInsert(json, 0, CFSTR("\""));
1167 CFStringAppend(json, CFSTR("\""));
1168
1169 return [reinterpret_cast<const NSString *>(json) autorelease];
1170 }
1171
1172 - (NSString *) cy$toKey {
1173 const char *value([self UTF8String]);
1174 size_t size(strlen(value));
1175
1176 if (size == 0)
1177 goto cyon;
1178
1179 if (DigitRange_[value[0]]) {
1180 size_t index(CYGetIndex(NULL, self));
1181 if (index == _not(size_t))
1182 goto cyon;
1183 } else {
1184 if (!WordStartRange_[value[0]])
1185 goto cyon;
1186 for (size_t i(1); i != size; ++i)
1187 if (!WordEndRange_[value[i]])
1188 goto cyon;
1189 }
1190
1191 return self;
1192
1193 cyon:
1194 return [self cy$toCYON];
1195 }
1196
1197 - (void *) cy$symbol {
1198 CYPool pool;
1199 return dlsym(RTLD_DEFAULT, CYPoolCString(pool, self));
1200 }
1201
1202 @end
1203 /* }}} */
1204 /* Bridge: WebUndefined {{{ */
1205 @implementation WebUndefined (Cycript)
1206
1207 - (JSType) cy$JSType {
1208 return kJSTypeUndefined;
1209 }
1210
1211 - (NSObject *) cy$toJSON:(NSString *)key {
1212 return self;
1213 }
1214
1215 - (NSString *) cy$toCYON {
1216 return @"undefined";
1217 }
1218
1219 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
1220 return CYJSUndefined(context);
1221 }
1222
1223 @end
1224 /* }}} */
1225
1226 @interface CYJSObject : NSMutableDictionary {
1227 JSObjectRef object_;
1228 JSContextRef context_;
1229 }
1230
1231 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1232
1233 - (NSString *) cy$toJSON:(NSString *)key;
1234
1235 - (NSUInteger) count;
1236 - (id) objectForKey:(id)key;
1237 - (NSEnumerator *) keyEnumerator;
1238 - (void) setObject:(id)object forKey:(id)key;
1239 - (void) removeObjectForKey:(id)key;
1240
1241 @end
1242
1243 @interface CYJSArray : NSMutableArray {
1244 JSObjectRef object_;
1245 JSContextRef context_;
1246 }
1247
1248 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
1249
1250 - (NSUInteger) count;
1251 - (id) objectAtIndex:(NSUInteger)index;
1252
1253 - (void) addObject:(id)anObject;
1254 - (void) insertObject:(id)anObject atIndex:(NSUInteger)index;
1255 - (void) removeLastObject;
1256 - (void) removeObjectAtIndex:(NSUInteger)index;
1257 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
1258
1259 @end
1260
1261 CYRange DigitRange_ (0x3ff000000000000LLU, 0x000000000000000LLU); // 0-9
1262 CYRange WordStartRange_(0x000001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$
1263 CYRange WordEndRange_ (0x3ff001000000000LLU, 0x7fffffe87fffffeLLU); // A-Za-z_$0-9
1264
1265 #define CYTry \
1266 @try
1267 #define CYCatch \
1268 @catch (id error) { \
1269 CYThrow(context, error, exception); \
1270 return NULL; \
1271 }
1272
1273 apr_status_t CYPoolRelease_(void *data) {
1274 id object(reinterpret_cast<id>(data));
1275 [object release];
1276 return APR_SUCCESS;
1277 }
1278
1279 id CYPoolRelease(apr_pool_t *pool, id object) {
1280 if (object == nil)
1281 return nil;
1282 else if (pool == NULL)
1283 return [object autorelease];
1284 else {
1285 apr_pool_cleanup_register(pool, object, &CYPoolRelease_, &apr_pool_cleanup_null);
1286 return object;
1287 }
1288 }
1289
1290 CFTypeRef CYPoolRelease(apr_pool_t *pool, CFTypeRef object) {
1291 return (CFTypeRef) CYPoolRelease(pool, (id) object);
1292 }
1293
1294 id CYCastNSObject_(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1295 JSValueRef exception(NULL);
1296 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
1297 CYThrow(context, exception);
1298 id value(array ? [CYJSArray alloc] : [CYJSObject alloc]);
1299 return CYPoolRelease(pool, [value initWithJSObject:object inContext:context]);
1300 }
1301
1302 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
1303 if (!JSValueIsObjectOfClass(context, object, Instance_))
1304 return CYCastNSObject_(pool, context, object);
1305 else {
1306 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
1307 return internal->GetValue();
1308 }
1309 }
1310
1311 double CYCastDouble(const char *value, size_t size) {
1312 char *end;
1313 double number(strtod(value, &end));
1314 if (end != value + size)
1315 return NAN;
1316 return number;
1317 }
1318
1319 double CYCastDouble(const char *value) {
1320 return CYCastDouble(value, strlen(value));
1321 }
1322
1323 double CYCastDouble(JSContextRef context, JSValueRef value) {
1324 JSValueRef exception(NULL);
1325 double number(JSValueToNumber(context, value, &exception));
1326 CYThrow(context, exception);
1327 return number;
1328 }
1329
1330 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
1331 double number(CYCastDouble(context, value));
1332 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
1333 }
1334
1335 CFStringRef CYCopyCFString(const char *value) {
1336 return CFStringCreateWithCString(kCFAllocatorDefault, value, kCFStringEncodingUTF8);
1337 }
1338
1339 NSString *CYCastNSString(apr_pool_t *pool, const char *value) {
1340 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1341 }
1342
1343 NSString *CYCastNSString(apr_pool_t *pool, JSStringRef value) {
1344 return (NSString *) CYPoolRelease(pool, CYCopyCFString(value));
1345 }
1346
1347 bool CYCastBool(JSContextRef context, JSValueRef value) {
1348 return JSValueToBoolean(context, value);
1349 }
1350
1351 CFTypeRef CYCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value, bool cast) {
1352 CFTypeRef object;
1353 bool copy;
1354
1355 switch (JSType type = JSValueGetType(context, value)) {
1356 case kJSTypeUndefined:
1357 object = [WebUndefined undefined];
1358 copy = false;
1359 break;
1360
1361 case kJSTypeNull:
1362 return NULL;
1363 break;
1364
1365 case kJSTypeBoolean:
1366 object = CYCastBool(context, value) ? kCFBooleanTrue : kCFBooleanFalse;
1367 copy = false;
1368 break;
1369
1370 case kJSTypeNumber:
1371 object = CYCopyCFNumber(context, value);
1372 copy = true;
1373 break;
1374
1375 case kJSTypeString:
1376 object = CYCopyCFString(context, value);
1377 copy = true;
1378 break;
1379
1380 case kJSTypeObject:
1381 // XXX: this might could be more efficient
1382 object = (CFTypeRef) CYCastNSObject(pool, context, (JSObjectRef) value);
1383 copy = false;
1384 break;
1385
1386 default:
1387 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
1388 break;
1389 }
1390
1391 if (cast != copy)
1392 return object;
1393 else if (copy)
1394 return CYPoolRelease(pool, object);
1395 else
1396 return CFRetain(object);
1397 }
1398
1399 CFTypeRef CYCastCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1400 return CYCFType(pool, context, value, true);
1401 }
1402
1403 CFTypeRef CYCopyCFType(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1404 return CYCFType(pool, context, value, false);
1405 }
1406
1407 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
1408 CYPool pool;
1409 size_t size(JSPropertyNameArrayGetCount(names));
1410 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
1411 for (size_t index(0); index != size; ++index)
1412 [array addObject:CYCastNSString(pool, JSPropertyNameArrayGetNameAtIndex(names, index))];
1413 return array;
1414 }
1415
1416 id CYCastNSObject(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1417 return reinterpret_cast<const NSObject *>(CYCastCFType(pool, context, value));
1418 }
1419
1420 void CYThrow(JSContextRef context, JSValueRef value) {
1421 if (value == NULL)
1422 return;
1423 @throw CYCastNSObject(NULL, context, value);
1424 }
1425
1426 JSValueRef CYJSNull(JSContextRef context) {
1427 return JSValueMakeNull(context);
1428 }
1429
1430 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
1431 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
1432 }
1433
1434 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
1435 return CYCastJSValue(context, CYJSString(value));
1436 }
1437
1438 JSValueRef CYCastJSValue(JSContextRef context, id value) {
1439 if (value == nil)
1440 return CYJSNull(context);
1441 else if ([value respondsToSelector:@selector(cy$JSValueInContext:)])
1442 return [value cy$JSValueInContext:context];
1443 else
1444 return CYMakeInstance(context, value, false);
1445 }
1446
1447 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
1448 JSValueRef exception(NULL);
1449 JSObjectRef object(JSValueToObject(context, value, &exception));
1450 CYThrow(context, exception);
1451 return object;
1452 }
1453
1454 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
1455 if (exception == NULL)
1456 throw error;
1457 *exception = CYCastJSValue(context, error);
1458 }
1459
1460 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
1461 JSValueRef exception(NULL);
1462 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
1463 CYThrow(context, exception);
1464 return value;
1465 }
1466
1467 bool CYIsCallable(JSContextRef context, JSValueRef value) {
1468 // XXX: this isn't actually correct
1469 return value != NULL && JSValueIsObject(context, value);
1470 }
1471
1472 @implementation CYJSObject
1473
1474 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1475 if ((self = [super init]) != nil) {
1476 object_ = object;
1477 context_ = context;
1478 } return self;
1479 }
1480
1481 - (NSObject *) cy$toJSON:(NSString *)key {
1482 JSValueRef toJSON(CYGetProperty(context_, object_, toJSON_));
1483 if (!CYIsCallable(context_, toJSON))
1484 return [super cy$toJSON:key];
1485 else {
1486 JSValueRef arguments[1] = {CYCastJSValue(context_, key)};
1487 JSValueRef value(CYCallAsFunction(context_, (JSObjectRef) toJSON, object_, 1, arguments));
1488 // XXX: do I really want an NSNull here?!
1489 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1490 }
1491 }
1492
1493 - (NSString *) cy$toCYON {
1494 JSValueRef toCYON(CYGetProperty(context_, object_, toCYON_));
1495 if (!CYIsCallable(context_, toCYON)) super:
1496 return [super cy$toCYON];
1497 else if (JSValueRef value = CYCallAsFunction(context_, (JSObjectRef) toCYON, object_, 0, NULL))
1498 return CYCastNSString(NULL, CYJSString(context_, value));
1499 else goto super;
1500 }
1501
1502 - (NSUInteger) count {
1503 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1504 size_t size(JSPropertyNameArrayGetCount(names));
1505 JSPropertyNameArrayRelease(names);
1506 return size;
1507 }
1508
1509 - (id) objectForKey:(id)key {
1510 JSValueRef value(CYGetProperty(context_, object_, CYJSString(key)));
1511 if (JSValueIsUndefined(context_, value))
1512 return nil;
1513 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1514 }
1515
1516 - (NSEnumerator *) keyEnumerator {
1517 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
1518 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
1519 JSPropertyNameArrayRelease(names);
1520 return enumerator;
1521 }
1522
1523 - (void) setObject:(id)object forKey:(id)key {
1524 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
1525 }
1526
1527 - (void) removeObjectForKey:(id)key {
1528 JSValueRef exception(NULL);
1529 (void) JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
1530 CYThrow(context_, exception);
1531 }
1532
1533 @end
1534
1535 @implementation CYJSArray
1536
1537 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
1538 if ((self = [super init]) != nil) {
1539 object_ = object;
1540 context_ = context;
1541 } return self;
1542 }
1543
1544 - (NSUInteger) count {
1545 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
1546 }
1547
1548 - (id) objectAtIndex:(NSUInteger)index {
1549 size_t bounds([self count]);
1550 if (index >= bounds)
1551 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray objectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1552 JSValueRef exception(NULL);
1553 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
1554 CYThrow(context_, exception);
1555 return CYCastNSObject(NULL, context_, value) ?: [NSNull null];
1556 }
1557
1558 - (void) addObject:(id)object {
1559 JSValueRef exception(NULL);
1560 JSValueRef arguments[1];
1561 arguments[0] = CYCastJSValue(context_, object);
1562 JSObjectCallAsFunction(context_, Array_push_, object_, 1, arguments, &exception);
1563 CYThrow(context_, exception);
1564 }
1565
1566 - (void) insertObject:(id)object atIndex:(NSUInteger)index {
1567 size_t bounds([self count] + 1);
1568 if (index >= bounds)
1569 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray insertObject:atIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1570 JSValueRef exception(NULL);
1571 JSValueRef arguments[3];
1572 arguments[0] = CYCastJSValue(context_, index);
1573 arguments[1] = CYCastJSValue(context_, 0);
1574 arguments[2] = CYCastJSValue(context_, object);
1575 JSObjectCallAsFunction(context_, Array_splice_, object_, 3, arguments, &exception);
1576 CYThrow(context_, exception);
1577 }
1578
1579 - (void) removeLastObject {
1580 JSValueRef exception(NULL);
1581 JSObjectCallAsFunction(context_, Array_pop_, object_, 0, NULL, &exception);
1582 CYThrow(context_, exception);
1583 }
1584
1585 - (void) removeObjectAtIndex:(NSUInteger)index {
1586 size_t bounds([self count]);
1587 if (index >= bounds)
1588 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray removeObjectAtIndex:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1589 JSValueRef exception(NULL);
1590 JSValueRef arguments[2];
1591 arguments[0] = CYCastJSValue(context_, index);
1592 arguments[1] = CYCastJSValue(context_, 1);
1593 JSObjectCallAsFunction(context_, Array_splice_, object_, 2, arguments, &exception);
1594 CYThrow(context_, exception);
1595 }
1596
1597 - (void) replaceObjectAtIndex:(NSUInteger)index withObject:(id)object {
1598 size_t bounds([self count]);
1599 if (index >= bounds)
1600 @throw [NSException exceptionWithName:NSRangeException reason:[NSString stringWithFormat:@"*** -[CYJSArray replaceObjectAtIndex:withObject:]: index (%zu) beyond bounds (%zu)", index, bounds] userInfo:nil];
1601 CYSetProperty(context_, object_, index, CYCastJSValue(context_, object));
1602 }
1603
1604 @end
1605
1606 NSString *CYCopyNSCYON(id value) {
1607 NSString *string;
1608
1609 if (value == nil)
1610 string = @"nil";
1611 else {
1612 Class _class(object_getClass(value));
1613 SEL sel(@selector(cy$toCYON));
1614
1615 if (Method toCYON = class_getInstanceMethod(_class, sel))
1616 string = reinterpret_cast<NSString *(*)(id, SEL)>(method_getImplementation(toCYON))(value, sel);
1617 else if (Method methodSignatureForSelector = class_getInstanceMethod(_class, @selector(methodSignatureForSelector:))) {
1618 if (reinterpret_cast<NSMethodSignature *(*)(id, SEL, SEL)>(method_getImplementation(methodSignatureForSelector))(value, @selector(methodSignatureForSelector:), sel) != nil)
1619 string = [value cy$toCYON];
1620 else goto fail;
1621 } else fail: {
1622 if (value == NSZombie_)
1623 string = @"_NSZombie_";
1624 else if (_class == NSZombie_)
1625 string = [NSString stringWithFormat:@"<_NSZombie_: %p>", value];
1626 // XXX: frowny /in/ the pants
1627 else if (value == NSMessageBuilder_ || value == Object_)
1628 string = nil;
1629 else
1630 string = [NSString stringWithFormat:@"%@", value];
1631 }
1632
1633 // XXX: frowny pants
1634 if (string == nil)
1635 string = @"undefined";
1636 }
1637
1638 return [string retain];
1639 }
1640
1641 NSString *CYCopyNSCYON(JSContextRef context, JSValueRef value, JSValueRef *exception) {
1642 if (JSValueIsNull(context, value))
1643 return [@"null" retain];
1644
1645 CYTry {
1646 CYPoolTry {
1647 return CYCopyNSCYON(CYCastNSObject(NULL, context, value));
1648 } CYPoolCatch(NULL)
1649 } CYCatch
1650 }
1651
1652 NSString *CYPoolNSCYON(apr_pool_t *pool, id value) {
1653 return CYPoolRelease(pool, static_cast<id>(CYCopyNSCYON(value)));
1654 }
1655
1656 const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) {
1657 if (NSString *json = CYCopyNSCYON(context, value, exception)) {
1658 const char *string(CYPoolCString(pool, json));
1659 [json release];
1660 return string;
1661 } else return NULL;
1662 }
1663
1664 // XXX: use objc_getAssociatedObject and objc_setAssociatedObject on 10.6
1665 struct CYInternal :
1666 CYData
1667 {
1668 JSObjectRef object_;
1669
1670 CYInternal() :
1671 object_(NULL)
1672 {
1673 }
1674
1675 ~CYInternal() {
1676 // XXX: delete object_? ;(
1677 }
1678
1679 static CYInternal *Get(id self) {
1680 CYInternal *internal(NULL);
1681 if (object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal)) == NULL) {
1682 // XXX: do something epic? ;P
1683 }
1684
1685 return internal;
1686 }
1687
1688 static CYInternal *Set(id self) {
1689 CYInternal *internal(NULL);
1690 if (Ivar ivar = object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal))) {
1691 if (internal == NULL) {
1692 internal = new CYInternal();
1693 object_setIvar(self, ivar, reinterpret_cast<id>(internal));
1694 }
1695 } else {
1696 // XXX: do something epic? ;P
1697 }
1698
1699 return internal;
1700 }
1701
1702 bool HasProperty(JSContextRef context, JSStringRef name) {
1703 if (object_ == NULL)
1704 return false;
1705 return JSObjectHasProperty(context, object_, name);
1706 }
1707
1708 JSValueRef GetProperty(JSContextRef context, JSStringRef name) {
1709 if (object_ == NULL)
1710 return NULL;
1711 return CYGetProperty(context, object_, name);
1712 }
1713
1714 void SetProperty(JSContextRef context, JSStringRef name, JSValueRef value) {
1715 if (object_ == NULL)
1716 object_ = JSObjectMake(context, NULL, NULL);
1717 CYSetProperty(context, object_, name, value);
1718 }
1719 };
1720
1721 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
1722 Selector_privateData *internal(new Selector_privateData(sel));
1723 return JSObjectMake(context, Selector_, internal);
1724 }
1725
1726 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
1727 Pointer *internal(new Pointer(pointer, context, owner, type));
1728 return JSObjectMake(context, Pointer_, internal);
1729 }
1730
1731 JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
1732 Functor_privateData *internal(new Functor_privateData(type, function));
1733 return JSObjectMake(context, Functor_, internal);
1734 }
1735
1736 const char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
1737 if (pool == NULL) {
1738 const char *string([CYCastNSString(NULL, value) UTF8String]);
1739 return string;
1740 } else {
1741 size_t size(JSStringGetMaximumUTF8CStringSize(value));
1742 char *string(new(pool) char[size]);
1743 JSStringGetUTF8CString(value, string, size);
1744 return string;
1745 }
1746 }
1747
1748 const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
1749 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, CYJSString(context, value));
1750 }
1751
1752 bool CYGetOffset(apr_pool_t *pool, JSStringRef value, ssize_t &index) {
1753 return CYGetOffset(CYPoolCString(pool, value), index);
1754 }
1755
1756 // XXX: this macro is unhygenic
1757 #define CYCastCString(context, value) ({ \
1758 char *utf8; \
1759 if (value == NULL) \
1760 utf8 = NULL; \
1761 else if (JSStringRef string = CYCopyJSString(context, value)) { \
1762 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
1763 utf8 = reinterpret_cast<char *>(alloca(size)); \
1764 JSStringGetUTF8CString(string, utf8, size); \
1765 JSStringRelease(string); \
1766 } else \
1767 utf8 = NULL; \
1768 utf8; \
1769 })
1770
1771 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
1772 switch (JSValueGetType(context, value)) {
1773 case kJSTypeNull:
1774 return NULL;
1775 /*case kJSTypeString:
1776 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
1777 case kJSTypeObject:
1778 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
1779 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
1780 return internal->value_;
1781 }*/
1782 default:
1783 double number(CYCastDouble(context, value));
1784 if (std::isnan(number))
1785 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"cannot convert value to pointer" userInfo:nil];
1786 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
1787 }
1788 }
1789
1790 template <typename Type_>
1791 _finline Type_ CYCastPointer(JSContextRef context, JSValueRef value) {
1792 return reinterpret_cast<Type_>(CYCastPointer_(context, value));
1793 }
1794
1795 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
1796 if (JSValueIsObjectOfClass(context, value, Selector_)) {
1797 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
1798 return reinterpret_cast<SEL>(internal->value_);
1799 } else
1800 return CYCastPointer<SEL>(context, value);
1801 }
1802
1803 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
1804 switch (type->primitive) {
1805 case sig::boolean_P:
1806 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
1807 break;
1808
1809 #define CYPoolFFI_(primitive, native) \
1810 case sig::primitive ## _P: \
1811 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
1812 break;
1813
1814 CYPoolFFI_(uchar, unsigned char)
1815 CYPoolFFI_(char, char)
1816 CYPoolFFI_(ushort, unsigned short)
1817 CYPoolFFI_(short, short)
1818 CYPoolFFI_(ulong, unsigned long)
1819 CYPoolFFI_(long, long)
1820 CYPoolFFI_(uint, unsigned int)
1821 CYPoolFFI_(int, int)
1822 CYPoolFFI_(ulonglong, unsigned long long)
1823 CYPoolFFI_(longlong, long long)
1824 CYPoolFFI_(float, float)
1825 CYPoolFFI_(double, double)
1826
1827 case sig::object_P:
1828 case sig::typename_P:
1829 *reinterpret_cast<id *>(data) = CYCastNSObject(pool, context, value);
1830 break;
1831
1832 case sig::selector_P:
1833 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
1834 break;
1835
1836 case sig::pointer_P:
1837 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
1838 break;
1839
1840 case sig::string_P:
1841 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
1842 break;
1843
1844 case sig::struct_P: {
1845 uint8_t *base(reinterpret_cast<uint8_t *>(data));
1846 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
1847 for (size_t index(0); index != type->data.signature.count; ++index) {
1848 sig::Element *element(&type->data.signature.elements[index]);
1849 ffi_type *field(ffi->elements[index]);
1850
1851 JSValueRef rhs;
1852 if (aggregate == NULL)
1853 rhs = value;
1854 else {
1855 rhs = CYGetProperty(context, aggregate, index);
1856 if (JSValueIsUndefined(context, rhs)) {
1857 if (element->name != NULL)
1858 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
1859 else
1860 goto undefined;
1861 if (JSValueIsUndefined(context, rhs)) undefined:
1862 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"unable to extract structure value" userInfo:nil];
1863 }
1864 }
1865
1866 CYPoolFFI(pool, context, element->type, field, base, rhs);
1867 // XXX: alignment?
1868 base += field->size;
1869 }
1870 } break;
1871
1872 case sig::void_P:
1873 break;
1874
1875 default:
1876 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
1877 _assert(false);
1878 }
1879 }
1880
1881 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize = false, JSObjectRef owner = NULL) {
1882 JSValueRef value;
1883
1884 switch (type->primitive) {
1885 case sig::boolean_P:
1886 value = CYCastJSValue(context, *reinterpret_cast<bool *>(data));
1887 break;
1888
1889 #define CYFromFFI_(primitive, native) \
1890 case sig::primitive ## _P: \
1891 value = CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
1892 break;
1893
1894 CYFromFFI_(uchar, unsigned char)
1895 CYFromFFI_(char, char)
1896 CYFromFFI_(ushort, unsigned short)
1897 CYFromFFI_(short, short)
1898 CYFromFFI_(ulong, unsigned long)
1899 CYFromFFI_(long, long)
1900 CYFromFFI_(uint, unsigned int)
1901 CYFromFFI_(int, int)
1902 CYFromFFI_(ulonglong, unsigned long long)
1903 CYFromFFI_(longlong, long long)
1904 CYFromFFI_(float, float)
1905 CYFromFFI_(double, double)
1906
1907 case sig::object_P: {
1908 if (id object = *reinterpret_cast<id *>(data)) {
1909 value = CYCastJSValue(context, object);
1910 if (initialize)
1911 [object release];
1912 } else goto null;
1913 } break;
1914
1915 case sig::typename_P:
1916 value = CYMakeInstance(context, *reinterpret_cast<Class *>(data), true);
1917 break;
1918
1919 case sig::selector_P:
1920 if (SEL sel = *reinterpret_cast<SEL *>(data))
1921 value = CYMakeSelector(context, sel);
1922 else goto null;
1923 break;
1924
1925 case sig::pointer_P:
1926 if (void *pointer = *reinterpret_cast<void **>(data))
1927 value = CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
1928 else goto null;
1929 break;
1930
1931 case sig::string_P:
1932 if (char *utf8 = *reinterpret_cast<char **>(data))
1933 value = CYCastJSValue(context, utf8);
1934 else goto null;
1935 break;
1936
1937 case sig::struct_P:
1938 value = CYMakeStruct(context, data, type, ffi, owner);
1939 break;
1940
1941 case sig::void_P:
1942 value = CYJSUndefined(context);
1943 break;
1944
1945 null:
1946 value = CYJSNull(context);
1947 break;
1948
1949 default:
1950 NSLog(@"CYFromFFI(%c)\n", type->primitive);
1951 _assert(false);
1952 }
1953
1954 return value;
1955 }
1956
1957 static bool CYImplements(id object, Class _class, SEL selector, bool devoid) {
1958 if (Method method = class_getInstanceMethod(_class, selector)) {
1959 if (!devoid)
1960 return true;
1961 char type[16];
1962 method_getReturnType(method, type, sizeof(type));
1963 if (type[0] != 'v')
1964 return true;
1965 }
1966
1967 // XXX: possibly use a more "awesome" check?
1968 return false;
1969 }
1970
1971 const char *CYPoolTypeEncoding(apr_pool_t *pool, Class _class, SEL sel, Method method) {
1972 if (method != NULL)
1973 return method_getTypeEncoding(method);
1974 else if (NSString *type = [[Bridge_ objectAtIndex:1] objectForKey:CYCastNSString(pool, sel_getName(sel))])
1975 return CYPoolCString(pool, type);
1976 else
1977 return NULL;
1978 }
1979
1980 void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1981 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1982
1983 JSContextRef context(internal->context_);
1984
1985 size_t count(internal->cif_.nargs);
1986 JSValueRef values[count];
1987
1988 for (size_t index(0); index != count; ++index)
1989 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
1990
1991 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
1992 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
1993 }
1994
1995 void MessageClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
1996 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
1997
1998 JSContextRef context(internal->context_);
1999
2000 size_t count(internal->cif_.nargs);
2001 JSValueRef values[count];
2002
2003 for (size_t index(0); index != count; ++index)
2004 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
2005
2006 JSObjectRef _this(CYCastJSObject(context, values[0]));
2007
2008 JSValueRef value(CYCallAsFunction(context, internal->function_, _this, count - 2, values + 2));
2009 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
2010 }
2011
2012 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
2013 // XXX: in case of exceptions this will leak
2014 // XXX: in point of fact, this may /need/ to leak :(
2015 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
2016
2017 ffi_closure *closure((ffi_closure *) _syscall(mmap(
2018 NULL, sizeof(ffi_closure),
2019 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
2020 -1, 0
2021 )));
2022
2023 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
2024 _assert(status == FFI_OK);
2025
2026 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
2027
2028 internal->value_ = closure;
2029
2030 return internal;
2031 }
2032
2033 JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
2034 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
2035 return JSObjectMake(context, Functor_, internal);
2036 }
2037
2038 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
2039 JSValueRef exception(NULL);
2040 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
2041 CYThrow(context, exception);
2042
2043 if (function) {
2044 JSObjectRef function(CYCastJSObject(context, value));
2045 return CYMakeFunctor(context, function, type);
2046 } else {
2047 void (*function)()(CYCastPointer<void (*)()>(context, value));
2048 return CYMakeFunctor(context, function, type);
2049 }
2050 }
2051
2052 static JSObjectRef CYMakeMessage(JSContextRef context, SEL sel, IMP imp, const char *type) {
2053 Message_privateData *internal(new Message_privateData(sel, type, imp));
2054 return JSObjectMake(context, Message_, internal);
2055 }
2056
2057 static IMP CYMakeMessage(JSContextRef context, JSValueRef value, const char *type) {
2058 JSObjectRef function(CYCastJSObject(context, value));
2059 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &MessageClosure_));
2060 return reinterpret_cast<IMP>(internal->GetValue());
2061 }
2062
2063 static bool Messages_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2064 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2065 Class _class(internal->GetValue());
2066
2067 CYPool pool;
2068 const char *name(CYPoolCString(pool, property));
2069
2070 if (SEL sel = sel_getUid(name))
2071 if (class_getInstanceMethod(_class, sel) != NULL)
2072 return true;
2073
2074 return false;
2075 }
2076
2077 static JSValueRef Messages_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2078 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2079 Class _class(internal->GetValue());
2080
2081 CYPool pool;
2082 const char *name(CYPoolCString(pool, property));
2083
2084 if (SEL sel = sel_getUid(name))
2085 if (Method method = class_getInstanceMethod(_class, sel))
2086 return CYMakeMessage(context, sel, method_getImplementation(method), method_getTypeEncoding(method));
2087
2088 return NULL;
2089 }
2090
2091 static bool Messages_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2092 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2093 Class _class(internal->GetValue());
2094
2095 CYPool pool;
2096 const char *name(CYPoolCString(pool, property));
2097
2098 SEL sel(sel_registerName(name));
2099
2100 Method method(class_getInstanceMethod(_class, sel));
2101
2102 const char *type;
2103 IMP imp;
2104
2105 if (JSValueIsObjectOfClass(context, value, Message_)) {
2106 Message_privateData *message(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate((JSObjectRef) value)));
2107 type = sig::Unparse(pool, &message->signature_);
2108 imp = reinterpret_cast<IMP>(message->GetValue());
2109 } else {
2110 type = CYPoolTypeEncoding(pool, _class, sel, method);
2111 imp = CYMakeMessage(context, value, type);
2112 }
2113
2114 if (method != NULL)
2115 method_setImplementation(method, imp);
2116 else
2117 class_replaceMethod(_class, sel, imp, type);
2118
2119 return true;
2120 }
2121
2122 #if !__OBJC2__
2123 static bool Messages_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2124 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2125 Class _class(internal->GetValue());
2126
2127 CYPool pool;
2128 const char *name(CYPoolCString(pool, property));
2129
2130 if (SEL sel = sel_getUid(name))
2131 if (Method method = class_getInstanceMethod(_class, sel)) {
2132 objc_method_list list = {NULL, 1, {method}};
2133 class_removeMethods(_class, &list);
2134 return true;
2135 }
2136
2137 return false;
2138 }
2139 #endif
2140
2141 static void Messages_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2142 Messages *internal(reinterpret_cast<Messages *>(JSObjectGetPrivate(object)));
2143 Class _class(internal->GetValue());
2144
2145 unsigned int size;
2146 Method *data(class_copyMethodList(_class, &size));
2147 for (size_t i(0); i != size; ++i)
2148 JSPropertyNameAccumulatorAddName(names, CYJSString(sel_getName(method_getName(data[i]))));
2149 free(data);
2150 }
2151
2152 static bool Instance_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2153 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2154 id self(internal->GetValue());
2155
2156 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2157 return true;
2158
2159 CYPool pool;
2160 NSString *name(CYCastNSString(pool, property));
2161
2162 if (CYInternal *internal = CYInternal::Get(self))
2163 if (internal->HasProperty(context, property))
2164 return true;
2165
2166 Class _class(object_getClass(self));
2167
2168 CYPoolTry {
2169 // XXX: this is an evil hack to deal with NSProxy; fix elsewhere
2170 if (CYImplements(self, _class, @selector(cy$hasProperty:), false))
2171 if ([self cy$hasProperty:name])
2172 return true;
2173 } CYPoolCatch(false)
2174
2175 const char *string(CYPoolCString(pool, name));
2176
2177 if (class_getProperty(_class, string) != NULL)
2178 return true;
2179
2180 if (SEL sel = sel_getUid(string))
2181 if (CYImplements(self, _class, sel, true))
2182 return true;
2183
2184 return false;
2185 }
2186
2187 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2188 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2189 id self(internal->GetValue());
2190
2191 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
2192 return Internal::Make(context, self, object);
2193
2194 CYTry {
2195 CYPool pool;
2196 NSString *name(CYCastNSString(pool, property));
2197
2198 if (CYInternal *internal = CYInternal::Get(self))
2199 if (JSValueRef value = internal->GetProperty(context, property))
2200 return value;
2201
2202 CYPoolTry {
2203 if (NSObject *data = [self cy$getProperty:name])
2204 return CYCastJSValue(context, data);
2205 } CYPoolCatch(NULL)
2206
2207 const char *string(CYPoolCString(pool, name));
2208 Class _class(object_getClass(self));
2209
2210 if (objc_property_t property = class_getProperty(_class, string)) {
2211 PropertyAttributes attributes(property);
2212 SEL sel(sel_registerName(attributes.Getter()));
2213 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2214 }
2215
2216 if (SEL sel = sel_getUid(string))
2217 if (CYImplements(self, _class, sel, true))
2218 return CYSendMessage(pool, context, self, sel, 0, NULL, false, exception);
2219
2220 return NULL;
2221 } CYCatch
2222 }
2223
2224 static bool Instance_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2225 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2226 id self(internal->GetValue());
2227
2228 CYPool pool;
2229
2230 CYTry {
2231 NSString *name(CYCastNSString(pool, property));
2232 NSString *data(CYCastNSObject(pool, context, value));
2233
2234 CYPoolTry {
2235 if ([self cy$setProperty:name to:data])
2236 return true;
2237 } CYPoolCatch(NULL)
2238
2239 const char *string(CYPoolCString(pool, name));
2240 Class _class(object_getClass(self));
2241
2242 if (objc_property_t property = class_getProperty(_class, string)) {
2243 PropertyAttributes attributes(property);
2244 if (const char *setter = attributes.Setter()) {
2245 SEL sel(sel_registerName(setter));
2246 JSValueRef arguments[1] = {value};
2247 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2248 return true;
2249 }
2250 }
2251
2252 size_t length(strlen(string));
2253
2254 char set[length + 5];
2255
2256 set[0] = 's';
2257 set[1] = 'e';
2258 set[2] = 't';
2259
2260 if (string[0] != '\0') {
2261 set[3] = toupper(string[0]);
2262 memcpy(set + 4, string + 1, length - 1);
2263 }
2264
2265 set[length + 3] = ':';
2266 set[length + 4] = '\0';
2267
2268 if (SEL sel = sel_getUid(set))
2269 if (CYImplements(self, _class, sel, false)) {
2270 JSValueRef arguments[1] = {value};
2271 CYSendMessage(pool, context, self, sel, 1, arguments, false, exception);
2272 }
2273
2274 if (CYInternal *internal = CYInternal::Set(self)) {
2275 internal->SetProperty(context, property, value);
2276 return true;
2277 }
2278
2279 return false;
2280 } CYCatch
2281 }
2282
2283 static bool Instance_deleteProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2284 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2285 id self(internal->GetValue());
2286
2287 CYTry {
2288 CYPoolTry {
2289 NSString *name(CYCastNSString(NULL, property));
2290 return [self cy$deleteProperty:name];
2291 } CYPoolCatch(NULL)
2292 } CYCatch
2293 }
2294
2295 static void Instance_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2296 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2297 id self(internal->GetValue());
2298
2299 CYPool pool;
2300 Class _class(object_getClass(self));
2301
2302 {
2303 unsigned int size;
2304 objc_property_t *data(class_copyPropertyList(_class, &size));
2305 for (size_t i(0); i != size; ++i)
2306 JSPropertyNameAccumulatorAddName(names, CYJSString(property_getName(data[i])));
2307 free(data);
2308 }
2309 }
2310
2311 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2312 CYTry {
2313 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
2314 JSObjectRef value(Instance::Make(context, [internal->GetValue() alloc], Instance::Uninitialized));
2315 return value;
2316 } CYCatch
2317 }
2318
2319 bool CYIsClass(id self) {
2320 // XXX: this is a lame object_isClass
2321 return class_getInstanceMethod(object_getClass(self), @selector(alloc)) != NULL;
2322 }
2323
2324 static bool Instance_hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef instance, JSValueRef *exception) {
2325 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) constructor)));
2326 Class _class(internal->GetValue());
2327 if (!CYIsClass(_class))
2328 return false;
2329
2330 if (JSValueIsObjectOfClass(context, instance, Instance_)) {
2331 Instance *linternal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) instance)));
2332 // XXX: this isn't always safe
2333 CYTry {
2334 return [linternal->GetValue() isKindOfClass:_class];
2335 } CYCatch
2336 }
2337
2338 return false;
2339 }
2340
2341 static bool Internal_hasProperty(JSContextRef context, JSObjectRef object, JSStringRef property) {
2342 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2343 CYPool pool;
2344
2345 id self(internal->GetValue());
2346 const char *name(CYPoolCString(pool, property));
2347
2348 if (object_getInstanceVariable(self, name, NULL) != NULL)
2349 return true;
2350
2351 return false;
2352 }
2353
2354 static JSValueRef Internal_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2355 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2356 CYPool pool;
2357
2358 CYTry {
2359 id self(internal->GetValue());
2360 const char *name(CYPoolCString(pool, property));
2361
2362 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2363 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2364 return CYFromFFI(context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar));
2365 }
2366
2367 return NULL;
2368 } CYCatch
2369 }
2370
2371 static bool Internal_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2372 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2373 CYPool pool;
2374
2375 CYTry {
2376 id self(internal->GetValue());
2377 const char *name(CYPoolCString(pool, property));
2378
2379 if (Ivar ivar = object_getInstanceVariable(self, name, NULL)) {
2380 Type_privateData type(pool, ivar_getTypeEncoding(ivar));
2381 CYPoolFFI(pool, context, type.type_, type.GetFFI(), reinterpret_cast<uint8_t *>(self) + ivar_getOffset(ivar), value);
2382 return true;
2383 }
2384
2385 return false;
2386 } CYCatch
2387 }
2388
2389 static void Internal_getPropertyNames_(Class _class, JSPropertyNameAccumulatorRef names) {
2390 if (Class super = class_getSuperclass(_class))
2391 Internal_getPropertyNames_(super, names);
2392
2393 unsigned int size;
2394 Ivar *data(class_copyIvarList(_class, &size));
2395 for (size_t i(0); i != size; ++i)
2396 JSPropertyNameAccumulatorAddName(names, CYJSString(ivar_getName(data[i])));
2397 free(data);
2398 }
2399
2400 static void Internal_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2401 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2402 CYPool pool;
2403
2404 id self(internal->GetValue());
2405 Class _class(object_getClass(self));
2406
2407 Internal_getPropertyNames_(_class, names);
2408 }
2409
2410 static JSValueRef Internal_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2411 Internal *internal(reinterpret_cast<Internal *>(JSObjectGetPrivate(object)));
2412 return internal->GetOwner();
2413 }
2414
2415 bool Index_(apr_pool_t *pool, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
2416 Type_privateData *typical(internal->type_);
2417 sig::Type *type(typical->type_);
2418 if (type == NULL)
2419 return false;
2420
2421 const char *name(CYPoolCString(pool, property));
2422 size_t length(strlen(name));
2423 double number(CYCastDouble(name, length));
2424
2425 size_t count(type->data.signature.count);
2426
2427 if (std::isnan(number)) {
2428 if (property == NULL)
2429 return false;
2430
2431 sig::Element *elements(type->data.signature.elements);
2432
2433 for (size_t local(0); local != count; ++local) {
2434 sig::Element *element(&elements[local]);
2435 if (element->name != NULL && strcmp(name, element->name) == 0) {
2436 index = local;
2437 goto base;
2438 }
2439 }
2440
2441 return false;
2442 } else {
2443 index = static_cast<ssize_t>(number);
2444 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
2445 return false;
2446 }
2447
2448 base:
2449 ffi_type **elements(typical->GetFFI()->elements);
2450
2451 base = reinterpret_cast<uint8_t *>(internal->value_);
2452 for (ssize_t local(0); local != index; ++local)
2453 base += elements[local]->size;
2454
2455 return true;
2456 }
2457
2458 static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) {
2459 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2460 Type_privateData *typical(internal->type_);
2461
2462 ffi_type *ffi(typical->GetFFI());
2463
2464 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2465 base += ffi->size * index;
2466
2467 JSObjectRef owner(internal->GetOwner() ?: object);
2468
2469 CYTry {
2470 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
2471 } CYCatch
2472 }
2473
2474 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2475 CYPool pool;
2476 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2477 Type_privateData *typical(internal->type_);
2478
2479 if (typical->type_ == NULL)
2480 return NULL;
2481
2482 ssize_t offset;
2483 if (!CYGetOffset(pool, property, offset))
2484 return NULL;
2485
2486 return Pointer_getIndex(context, object, offset, exception);
2487 }
2488
2489 static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2490 return Pointer_getIndex(context, object, 0, exception);
2491 }
2492
2493 static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) {
2494 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2495 Type_privateData *typical(internal->type_);
2496
2497 ffi_type *ffi(typical->GetFFI());
2498
2499 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
2500 base += ffi->size * index;
2501
2502 CYTry {
2503 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
2504 return true;
2505 } CYCatch
2506 }
2507
2508 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2509 CYPool pool;
2510 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
2511 Type_privateData *typical(internal->type_);
2512
2513 if (typical->type_ == NULL)
2514 return NULL;
2515
2516 ssize_t offset;
2517 if (!CYGetOffset(pool, property, offset))
2518 return NULL;
2519
2520 return Pointer_setIndex(context, object, offset, value, exception);
2521 }
2522
2523 static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2524 return Pointer_setIndex(context, object, 0, value, exception);
2525 }
2526
2527 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2528 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
2529 Type_privateData *typical(internal->type_);
2530 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
2531 }
2532
2533 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2534 CYPool pool;
2535 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2536 Type_privateData *typical(internal->type_);
2537
2538 ssize_t index;
2539 uint8_t *base;
2540
2541 if (!Index_(pool, internal, property, index, base))
2542 return NULL;
2543
2544 JSObjectRef owner(internal->GetOwner() ?: object);
2545
2546 CYTry {
2547 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
2548 } CYCatch
2549 }
2550
2551 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
2552 CYPool pool;
2553 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2554 Type_privateData *typical(internal->type_);
2555
2556 ssize_t index;
2557 uint8_t *base;
2558
2559 if (!Index_(pool, internal, property, index, base))
2560 return false;
2561
2562 CYTry {
2563 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
2564 return true;
2565 } CYCatch
2566 }
2567
2568 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2569 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
2570 Type_privateData *typical(internal->type_);
2571 sig::Type *type(typical->type_);
2572
2573 if (type == NULL)
2574 return;
2575
2576 size_t count(type->data.signature.count);
2577 sig::Element *elements(type->data.signature.elements);
2578
2579 char number[32];
2580
2581 for (size_t index(0); index != count; ++index) {
2582 const char *name;
2583 name = elements[index].name;
2584
2585 if (name == NULL) {
2586 sprintf(number, "%lu", index);
2587 name = number;
2588 }
2589
2590 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
2591 }
2592 }
2593
2594 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)()) {
2595 CYTry {
2596 if (setups + count != signature->count - 1)
2597 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
2598
2599 size_t size(setups + count);
2600 void *values[size];
2601 memcpy(values, setup, sizeof(void *) * setups);
2602
2603 for (size_t index(setups); index != size; ++index) {
2604 sig::Element *element(&signature->elements[index + 1]);
2605 ffi_type *ffi(cif->arg_types[index]);
2606 // XXX: alignment?
2607 values[index] = new(pool) uint8_t[ffi->size];
2608 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
2609 }
2610
2611 uint8_t value[cif->rtype->size];
2612 ffi_call(cif, function, value, values);
2613
2614 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
2615 } CYCatch
2616 }
2617
2618 static JSValueRef ObjectiveC_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2619 CYTry {
2620 CYPool pool;
2621 NSString *name(CYCastNSString(pool, property));
2622 if (Class _class = NSClassFromString(name))
2623 return CYMakeInstance(context, _class, true);
2624 return NULL;
2625 } CYCatch
2626 }
2627
2628 static void ObjectiveC_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2629 size_t size(objc_getClassList(NULL, 0));
2630 Class *data(reinterpret_cast<Class *>(malloc(sizeof(Class) * size)));
2631
2632 get:
2633 size_t writ(objc_getClassList(data, size));
2634 if (size < writ) {
2635 size = writ;
2636 if (Class *copy = reinterpret_cast<Class *>(realloc(data, sizeof(Class) * writ))) {
2637 data = copy;
2638 goto get;
2639 } else goto done;
2640 }
2641
2642 for (size_t i(0); i != writ; ++i)
2643 JSPropertyNameAccumulatorAddName(names, CYJSString(class_getName(data[i])));
2644
2645 done:
2646 free(data);
2647 }
2648
2649 static JSValueRef ObjectiveC_Image_Classes_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2650 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2651
2652 CYTry {
2653 CYPool pool;
2654 const char *name(CYPoolCString(pool, property));
2655 unsigned int size;
2656 const char **data(objc_copyClassNamesForImage(internal, &size));
2657 JSValueRef value;
2658 for (size_t i(0); i != size; ++i)
2659 if (strcmp(name, data[i]) == 0) {
2660 if (Class _class = objc_getClass(name)) {
2661 value = CYMakeInstance(context, _class, true);
2662 goto free;
2663 } else
2664 break;
2665 }
2666 value = NULL;
2667 free:
2668 free(data);
2669 return value;
2670 } CYCatch
2671 }
2672
2673 static void ObjectiveC_Image_Classes_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2674 const char *internal(reinterpret_cast<const char *>(JSObjectGetPrivate(object)));
2675 unsigned int size;
2676 const char **data(objc_copyClassNamesForImage(internal, &size));
2677 for (size_t i(0); i != size; ++i)
2678 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2679 free(data);
2680 }
2681
2682 static JSValueRef ObjectiveC_Images_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2683 CYTry {
2684 CYPool pool;
2685 const char *name(CYPoolCString(pool, property));
2686 unsigned int size;
2687 const char **data(objc_copyImageNames(&size));
2688 for (size_t i(0); i != size; ++i)
2689 if (strcmp(name, data[i]) == 0) {
2690 name = data[i];
2691 goto free;
2692 }
2693 name = NULL;
2694 free:
2695 free(data);
2696 if (name == NULL)
2697 return NULL;
2698 JSObjectRef value(JSObjectMake(context, NULL, NULL));
2699 CYSetProperty(context, value, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Image_Classes_, const_cast<char *>(name)));
2700 return value;
2701 } CYCatch
2702 }
2703
2704 static void ObjectiveC_Images_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2705 unsigned int size;
2706 const char **data(objc_copyImageNames(&size));
2707 for (size_t i(0); i != size; ++i)
2708 JSPropertyNameAccumulatorAddName(names, CYJSString(data[i]));
2709 free(data);
2710 }
2711
2712 static JSValueRef ObjectiveC_Protocols_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2713 CYTry {
2714 CYPool pool;
2715 NSString *name(CYCastNSString(pool, property));
2716 if (Protocol *protocol = NSProtocolFromString(name))
2717 return CYMakeInstance(context, protocol, true);
2718 return NULL;
2719 } CYCatch
2720 }
2721
2722 static void ObjectiveC_Protocols_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
2723 unsigned int size;
2724 Protocol **data(objc_copyProtocolList(&size));
2725 for (size_t i(0); i != size; ++i)
2726 JSPropertyNameAccumulatorAddName(names, CYJSString(protocol_getName(data[i])));
2727 free(data);
2728 }
2729
2730 static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2731 if (JSStringIsEqualToUTF8CString(property, "nil"))
2732 return Instance::Make(context, nil);
2733
2734 CYTry {
2735 CYPool pool;
2736 NSString *name(CYCastNSString(pool, property));
2737 if (Class _class = NSClassFromString(name))
2738 return CYMakeInstance(context, _class, true);
2739 if (NSMutableArray *entry = [[Bridge_ objectAtIndex:0] objectForKey:name])
2740 switch ([[entry objectAtIndex:0] intValue]) {
2741 case 0:
2742 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
2743 case 1:
2744 return CYMakeFunctor(context, reinterpret_cast<void (*)()>([name cy$symbol]), CYPoolCString(pool, [entry objectAtIndex:1]));
2745 case 2:
2746 // XXX: this is horrendously inefficient
2747 sig::Signature signature;
2748 sig::Parse(pool, &signature, CYPoolCString(pool, [entry objectAtIndex:1]), &Structor_);
2749 ffi_cif cif;
2750 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2751 return CYFromFFI(context, signature.elements[0].type, cif.rtype, [name cy$symbol]);
2752 }
2753 return NULL;
2754 } CYCatch
2755 }
2756
2757 bool stret(ffi_type *ffi_type) {
2758 return ffi_type->type == FFI_TYPE_STRUCT && (
2759 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
2760 struct_forward_array[ffi_type->size] != 0
2761 );
2762 }
2763
2764 extern "C" {
2765 int *_NSGetArgc(void);
2766 char ***_NSGetArgv(void);
2767 int UIApplicationMain(int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
2768 }
2769
2770 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2771 CYTry {
2772 NSLog(@"%s", CYCastCString(context, arguments[0]));
2773 return CYJSUndefined(context);
2774 } CYCatch
2775 }
2776
2777 JSValueRef CYSendMessage(apr_pool_t *pool, JSContextRef context, id self, SEL _cmd, size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception) {
2778 const char *type;
2779
2780 Class _class(object_getClass(self));
2781 if (Method method = class_getInstanceMethod(_class, _cmd))
2782 type = method_getTypeEncoding(method);
2783 else {
2784 CYTry {
2785 CYPoolTry {
2786 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
2787 if (method == nil)
2788 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
2789 type = CYPoolCString(pool, [method _typeString]);
2790 } CYPoolCatch(NULL)
2791 } CYCatch
2792 }
2793
2794 void *setup[2];
2795 setup[0] = &self;
2796 setup[1] = &_cmd;
2797
2798 sig::Signature signature;
2799 sig::Parse(pool, &signature, type, &Structor_);
2800
2801 ffi_cif cif;
2802 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
2803
2804 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
2805 return CYCallFunction(pool, context, 2, setup, count, arguments, initialize, exception, &signature, &cif, function);
2806 }
2807
2808 static size_t Nonce_(0);
2809
2810 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2811 char name[16];
2812 sprintf(name, "%s%zu", CYCastCString(context, arguments[0]), Nonce_++);
2813 return CYCastJSValue(context, name);
2814 }
2815
2816 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2817 CYPool pool;
2818
2819 bool uninitialized;
2820
2821 id self;
2822 SEL _cmd;
2823
2824 CYTry {
2825 if (count < 2)
2826 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
2827
2828 if (JSValueIsObjectOfClass(context, arguments[0], Instance_)) {
2829 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate((JSObjectRef) arguments[0])));
2830 self = internal->GetValue();
2831 uninitialized = internal->IsUninitialized();
2832 if (uninitialized)
2833 internal->value_ = nil;
2834 } else {
2835 self = CYCastNSObject(pool, context, arguments[0]);
2836 uninitialized = false;
2837 }
2838
2839 if (self == nil)
2840 return CYJSNull(context);
2841
2842 _cmd = CYCastSEL(context, arguments[1]);
2843 } CYCatch
2844
2845 return CYSendMessage(pool, context, self, _cmd, count - 2, arguments + 2, uninitialized, exception);
2846 }
2847
2848 /* Hook: objc_registerClassPair {{{ */
2849 // XXX: replace this with associated objects
2850
2851 MSHook(void, CYDealloc, id self, SEL sel) {
2852 CYInternal *internal;
2853 object_getInstanceVariable(self, "cy$internal_", reinterpret_cast<void **>(&internal));
2854 if (internal != NULL)
2855 delete internal;
2856 _CYDealloc(self, sel);
2857 }
2858
2859 MSHook(void, objc_registerClassPair, Class _class) {
2860 Class super(class_getSuperclass(_class));
2861 if (super == NULL || class_getInstanceVariable(super, "cy$internal_") == NULL) {
2862 class_addIvar(_class, "cy$internal_", sizeof(CYInternal *), log2(sizeof(CYInternal *)), "^{CYInternal}");
2863 MSHookMessage(_class, @selector(dealloc), MSHake(CYDealloc));
2864 }
2865
2866 _objc_registerClassPair(_class);
2867 }
2868
2869 static JSValueRef objc_registerClassPair_(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2870 CYTry {
2871 if (count != 1)
2872 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to objc_registerClassPair" userInfo:nil];
2873 CYPool pool;
2874 Class _class(CYCastNSObject(pool, context, arguments[0]));
2875 $objc_registerClassPair(_class);
2876 return CYJSUndefined(context);
2877 } CYCatch
2878 }
2879 /* }}} */
2880
2881 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2882 JSValueRef setup[count + 2];
2883 setup[0] = _this;
2884 setup[1] = object;
2885 memcpy(setup + 2, arguments, sizeof(JSValueRef) * count);
2886 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
2887 }
2888
2889 static JSValueRef Message_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2890 CYPool pool;
2891 Message_privateData *internal(reinterpret_cast<Message_privateData *>(JSObjectGetPrivate(object)));
2892
2893 // XXX: handle Instance::Uninitialized?
2894 id self(CYCastNSObject(pool, context, _this));
2895
2896 void *setup[2];
2897 setup[0] = &self;
2898 setup[1] = &internal->sel_;
2899
2900 return CYCallFunction(pool, context, 2, setup, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2901 }
2902
2903 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2904 CYPool pool;
2905 Functor_privateData *internal(reinterpret_cast<Functor_privateData *>(JSObjectGetPrivate(object)));
2906 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
2907 }
2908
2909 JSObjectRef Selector_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2910 CYTry {
2911 if (count != 1)
2912 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
2913 const char *name(CYCastCString(context, arguments[0]));
2914 return CYMakeSelector(context, sel_registerName(name));
2915 } CYCatch
2916 }
2917
2918 JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2919 CYTry {
2920 if (count != 2)
2921 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2922
2923 void *value(CYCastPointer<void *>(context, arguments[0]));
2924 const char *type(CYCastCString(context, arguments[1]));
2925
2926 CYPool pool;
2927
2928 sig::Signature signature;
2929 sig::Parse(pool, &signature, type, &Structor_);
2930
2931 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
2932 } CYCatch
2933 }
2934
2935 JSObjectRef CYMakeType(JSContextRef context, JSObjectRef object, const char *type) {
2936 Type_privateData *internal(new Type_privateData(NULL, type));
2937 return JSObjectMake(context, Type_, internal);
2938 }
2939
2940 JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2941 CYTry {
2942 if (count != 1)
2943 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Type constructor" userInfo:nil];
2944 const char *type(CYCastCString(context, arguments[0]));
2945 return CYMakeType(context, object, type);
2946 } CYCatch
2947 }
2948
2949 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2950 CYTry {
2951 if (count != 1)
2952 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2953 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2954 sig::Type *type(internal->type_);
2955 ffi_type *ffi(internal->GetFFI());
2956 // XXX: alignment?
2957 uint8_t value[ffi->size];
2958 CYPool pool;
2959 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
2960 return CYFromFFI(context, type, ffi, value);
2961 } CYCatch
2962 }
2963
2964 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2965 CYTry {
2966 if (count > 1)
2967 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to type cast function" userInfo:nil];
2968 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
2969 size_t size(count == 0 ? 0 : CYCastDouble(context, arguments[0]));
2970 // XXX: alignment?
2971 void *value(malloc(internal->GetFFI()->size * size));
2972 return CYMakePointer(context, value, internal->type_, internal->ffi_, NULL);
2973 } CYCatch
2974 }
2975
2976 JSObjectRef Instance_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2977 CYTry {
2978 if (count > 1)
2979 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Instance constructor" userInfo:nil];
2980 id self(count == 0 ? nil : CYCastPointer<id>(context, arguments[0]));
2981 return Instance::Make(context, self);
2982 } CYCatch
2983 }
2984
2985 JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
2986 CYTry {
2987 if (count != 2)
2988 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
2989 const char *type(CYCastCString(context, arguments[1]));
2990 return CYMakeFunctor(context, arguments[0], type);
2991 } CYCatch
2992 }
2993
2994 JSValueRef CYValue_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
2995 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(object)));
2996 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
2997 }
2998
2999 static JSValueRef CYValue_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3000 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3001 Type_privateData *typical(internal->GetType());
3002
3003 sig::Type *type;
3004 ffi_type *ffi;
3005
3006 if (typical == NULL) {
3007 type = NULL;
3008 ffi = NULL;
3009 } else {
3010 type = typical->type_;
3011 ffi = typical->ffi_;
3012 }
3013
3014 return CYMakePointer(context, &internal->value_, type, ffi, object);
3015 }
3016
3017 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3018 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3019
3020 CYTry {
3021 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
3022 } CYCatch
3023 }
3024
3025 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3026 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
3027 }
3028
3029 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3030 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
3031 char string[32];
3032 sprintf(string, "%p", internal->value_);
3033
3034 CYTry {
3035 return CYCastJSValue(context, string);
3036 } CYCatch
3037 }
3038
3039 static JSValueRef Instance_getProperty_constructor(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3040 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3041 return Instance::Make(context, object_getClass(internal->GetValue()));
3042 }
3043
3044 static JSValueRef Instance_getProperty_protocol(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3045 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3046 id self(internal->GetValue());
3047 if (!CYIsClass(self))
3048 return CYJSUndefined(context);
3049 CYTry {
3050 return CYGetClassPrototype(context, self);
3051 } CYCatch
3052 }
3053
3054 static JSValueRef Instance_getProperty_messages(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
3055 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(object)));
3056 id self(internal->GetValue());
3057 if (class_getInstanceMethod(object_getClass(self), @selector(alloc)) == NULL)
3058 return CYJSUndefined(context);
3059 return Messages::Make(context, self);
3060 }
3061
3062 static JSValueRef Instance_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3063 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3064 return NULL;
3065
3066 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3067
3068 CYTry {
3069 CYPoolTry {
3070 return CYCastJSValue(context, CYJSString(CYPoolNSCYON(NULL, internal->GetValue())));
3071 } CYPoolCatch(NULL)
3072 } CYCatch
3073 }
3074
3075 static JSValueRef Instance_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3076 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3077 return NULL;
3078
3079 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3080
3081 CYTry {
3082 CYPoolTry {
3083 NSString *key(count == 0 ? nil : CYCastNSString(NULL, CYJSString(context, arguments[0])));
3084 // XXX: check for support of cy$toJSON?
3085 return CYCastJSValue(context, CYJSString([internal->GetValue() cy$toJSON:key]));
3086 } CYPoolCatch(NULL)
3087 } CYCatch
3088 }
3089
3090 static JSValueRef Instance_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3091 if (!JSValueIsObjectOfClass(context, _this, Instance_))
3092 return NULL;
3093
3094 Instance *internal(reinterpret_cast<Instance *>(JSObjectGetPrivate(_this)));
3095
3096 CYTry {
3097 CYPoolTry {
3098 return CYCastJSValue(context, CYJSString([internal->GetValue() description]));
3099 } CYPoolCatch(NULL)
3100 } CYCatch
3101 }
3102
3103 static JSValueRef Selector_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3104 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3105
3106 CYTry {
3107 return CYCastJSValue(context, sel_getName(internal->GetValue()));
3108 } CYCatch
3109 }
3110
3111 static JSValueRef Selector_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3112 return Selector_callAsFunction_toString(context, object, _this, count, arguments, exception);
3113 }
3114
3115 static JSValueRef Selector_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3116 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3117 const char *name(sel_getName(internal->GetValue()));
3118
3119 CYTry {
3120 CYPoolTry {
3121 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"@selector(%s)", name]));
3122 } CYPoolCatch(NULL)
3123 } CYCatch
3124 }
3125
3126 static JSValueRef Selector_callAsFunction_type(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3127 CYTry {
3128 if (count != 1)
3129 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector.type" userInfo:nil];
3130 CYPool pool;
3131 Selector_privateData *internal(reinterpret_cast<Selector_privateData *>(JSObjectGetPrivate(_this)));
3132 Class _class(CYCastNSObject(pool, context, arguments[0]));
3133 SEL sel(internal->GetValue());
3134 Method method(class_getInstanceMethod(_class, sel));
3135 const char *type(CYPoolTypeEncoding(pool, _class, sel, method));
3136 return type == NULL ? CYJSNull(context) : CYCastJSValue(context, CYJSString(type));
3137 } CYCatch
3138 }
3139
3140 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3141 CYTry {
3142 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3143 CYPool pool;
3144 const char *type(sig::Unparse(pool, internal->type_));
3145 CYPoolTry {
3146 return CYCastJSValue(context, CYJSString(type));
3147 } CYPoolCatch(NULL)
3148 } CYCatch
3149 }
3150
3151 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3152 CYTry {
3153 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
3154 CYPool pool;
3155 const char *type(sig::Unparse(pool, internal->type_));
3156 CYPoolTry {
3157 return CYCastJSValue(context, CYJSString([NSString stringWithFormat:@"new Type(%@)", [[NSString stringWithUTF8String:type] cy$toCYON]]));
3158 } CYPoolCatch(NULL)
3159 } CYCatch
3160 }
3161
3162 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
3163 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
3164 }
3165
3166 static JSStaticValue CYValue_staticValues[2] = {
3167 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
3168 {NULL, NULL, NULL, 0}
3169 };
3170
3171 static JSStaticValue Pointer_staticValues[2] = {
3172 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3173 {NULL, NULL, NULL, 0}
3174 };
3175
3176 static JSStaticFunction Pointer_staticFunctions[4] = {
3177 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3178 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3179 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3180 {NULL, NULL, 0}
3181 };
3182
3183 static JSStaticFunction Struct_staticFunctions[2] = {
3184 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3185 {NULL, NULL, 0}
3186 };
3187
3188 static JSStaticFunction Functor_staticFunctions[4] = {
3189 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3190 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3191 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3192 {NULL, NULL, 0}
3193 };
3194
3195 static JSStaticValue Instance_staticValues[5] = {
3196 {"constructor", &Instance_getProperty_constructor, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3197 {"messages", &Instance_getProperty_messages, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3198 {"prototype", &Instance_getProperty_protocol, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3199 {"value", &CYValue_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3200 {NULL, NULL, NULL, 0}
3201 };
3202
3203 static JSStaticFunction Instance_staticFunctions[5] = {
3204 {"$cya", &CYValue_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3205 {"toCYON", &Instance_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3206 {"toJSON", &Instance_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3207 {"toString", &Instance_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3208 {NULL, NULL, 0}
3209 };
3210
3211 static JSStaticFunction Internal_staticFunctions[2] = {
3212 {"$cya", &Internal_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3213 {NULL, NULL, 0}
3214 };
3215
3216 static JSStaticFunction Selector_staticFunctions[5] = {
3217 {"toCYON", &Selector_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3218 {"toJSON", &Selector_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3219 {"toString", &Selector_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3220 {"type", &Selector_callAsFunction_type, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3221 {NULL, NULL, 0}
3222 };
3223
3224 static JSStaticFunction Type_staticFunctions[4] = {
3225 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3226 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3227 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3228 {NULL, NULL, 0}
3229 };
3230
3231 CYDriver::CYDriver(const std::string &filename) :
3232 state_(CYClear),
3233 data_(NULL),
3234 size_(0),
3235 file_(NULL),
3236 filename_(filename),
3237 source_(NULL)
3238 {
3239 ScannerInit();
3240 }
3241
3242 CYDriver::~CYDriver() {
3243 ScannerDestroy();
3244 }
3245
3246 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
3247 CYDriver::Error error;
3248 error.location_ = location;
3249 error.message_ = message;
3250 driver.errors_.push_back(error);
3251 }
3252
3253 void CYSetArgs(int argc, const char *argv[]) {
3254 JSContextRef context(CYGetJSContext());
3255 JSValueRef args[argc];
3256 for (int i(0); i != argc; ++i)
3257 args[i] = CYCastJSValue(context, argv[i]);
3258 JSValueRef exception(NULL);
3259 JSObjectRef array(JSObjectMakeArray(context, argc, args, &exception));
3260 CYThrow(context, exception);
3261 CYSetProperty(context, System_, CYJSString("args"), array);
3262 }
3263
3264 JSObjectRef CYGetGlobalObject(JSContextRef context) {
3265 return JSContextGetGlobalObject(context);
3266 }
3267
3268 const char *CYExecute(apr_pool_t *pool, const char *code) { _pooled
3269 JSContextRef context(CYGetJSContext());
3270 JSValueRef exception(NULL), result;
3271
3272 try {
3273 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
3274 } catch (const char *error) {
3275 return error;
3276 }
3277
3278 if (exception != NULL) { error:
3279 result = exception;
3280 exception = NULL;
3281 }
3282
3283 if (JSValueIsUndefined(context, result))
3284 return NULL;
3285
3286 const char *json;
3287
3288 try {
3289 json = CYPoolCCYON(pool, context, result, &exception);
3290 } catch (const char *error) {
3291 return error;
3292 }
3293
3294 if (exception != NULL)
3295 goto error;
3296
3297 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
3298 return json;
3299 }
3300
3301 bool CYRecvAll_(int socket, uint8_t *data, size_t size) {
3302 while (size != 0) if (size_t writ = _syscall(recv(socket, data, size, 0))) {
3303 data += writ;
3304 size -= writ;
3305 } else
3306 return false;
3307 return true;
3308 }
3309
3310 bool CYSendAll_(int socket, const uint8_t *data, size_t size) {
3311 while (size != 0) if (size_t writ = _syscall(send(socket, data, size, 0))) {
3312 data += writ;
3313 size -= writ;
3314 } else
3315 return false;
3316 return true;
3317 }
3318
3319 apr_pool_t *Pool_;
3320
3321 struct CYExecute_ {
3322 apr_pool_t *pool_;
3323 const char * volatile data_;
3324 };
3325
3326 // XXX: this is "tre lame"
3327 @interface CYClient_ : NSObject {
3328 }
3329
3330 - (void) execute:(NSValue *)value;
3331
3332 @end
3333
3334 @implementation CYClient_
3335
3336 - (void) execute:(NSValue *)value {
3337 CYExecute_ *execute(reinterpret_cast<CYExecute_ *>([value pointerValue]));
3338 const char *data(execute->data_);
3339 execute->data_ = NULL;
3340 execute->data_ = CYExecute(execute->pool_, data);
3341 }
3342
3343 @end
3344
3345 struct CYClient :
3346 CYData
3347 {
3348 int socket_;
3349 apr_thread_t *thread_;
3350
3351 CYClient(int socket) :
3352 socket_(socket)
3353 {
3354 }
3355
3356 ~CYClient() {
3357 _syscall(close(socket_));
3358 }
3359
3360 void Handle() { _pooled
3361 CYClient_ *client = [[[CYClient_ alloc] init] autorelease];
3362
3363 for (;;) {
3364 size_t size;
3365 if (!CYRecvAll(socket_, &size, sizeof(size)))
3366 return;
3367
3368 CYPool pool;
3369 char *data(new(pool) char[size + 1]);
3370 if (!CYRecvAll(socket_, data, size))
3371 return;
3372 data[size] = '\0';
3373
3374 CYDriver driver("");
3375 cy::parser parser(driver);
3376
3377 driver.data_ = data;
3378 driver.size_ = size;
3379
3380 const char *json;
3381 if (parser.parse() != 0 || !driver.errors_.empty()) {
3382 json = NULL;
3383 size = _not(size_t);
3384 } else {
3385 std::ostringstream str;
3386 driver.source_->Show(str);
3387 std::string code(str.str());
3388 CYExecute_ execute = {pool, code.c_str()};
3389 [client performSelectorOnMainThread:@selector(execute:) withObject:[NSValue valueWithPointer:&execute] waitUntilDone:YES];
3390 json = execute.data_;
3391 size = json == NULL ? _not(size_t) : strlen(json);
3392 }
3393
3394 if (!CYSendAll(socket_, &size, sizeof(size)))
3395 return;
3396 if (json != NULL)
3397 if (!CYSendAll(socket_, json, size))
3398 return;
3399 }
3400 }
3401 };
3402
3403 static void * APR_THREAD_FUNC OnClient(apr_thread_t *thread, void *data) {
3404 CYClient *client(reinterpret_cast<CYClient *>(data));
3405 client->Handle();
3406 delete client;
3407 return NULL;
3408 }
3409
3410 extern "C" void CYHandleClient(apr_pool_t *pool, int socket) {
3411 CYClient *client(new(pool) CYClient(socket));
3412 apr_threadattr_t *attr;
3413 _aprcall(apr_threadattr_create(&attr, client->pool_));
3414 _aprcall(apr_thread_create(&client->thread_, attr, &OnClient, client, client->pool_));
3415 }
3416
3417 MSInitialize { _pooled
3418 _aprcall(apr_initialize());
3419 _aprcall(apr_pool_create(&Pool_, NULL));
3420
3421 Type_privateData::Object = new(Pool_) Type_privateData(Pool_, "@");
3422 Type_privateData::Selector = new(Pool_) Type_privateData(Pool_, ":");
3423
3424 Bridge_ = [[NSMutableArray arrayWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
3425
3426 NSArray_ = objc_getClass("NSArray");
3427 NSCFBoolean_ = objc_getClass("NSCFBoolean");
3428 NSCFType_ = objc_getClass("NSCFType");
3429 NSDictionary_ = objc_getClass("NSDictonary");
3430 NSMessageBuilder_ = objc_getClass("NSMessageBuilder");
3431 NSZombie_ = objc_getClass("_NSZombie_");
3432 Object_ = objc_getClass("Object");
3433 }
3434
3435 JSGlobalContextRef CYGetJSContext() {
3436 if (Context_ == NULL) {
3437 JSClassDefinition definition;
3438
3439 definition = kJSClassDefinitionEmpty;
3440 definition.className = "Functor";
3441 definition.staticFunctions = Functor_staticFunctions;
3442 definition.callAsFunction = &Functor_callAsFunction;
3443 definition.finalize = &Finalize;
3444 Functor_ = JSClassCreate(&definition);
3445
3446 definition = kJSClassDefinitionEmpty;
3447 definition.className = "Instance";
3448 definition.staticValues = Instance_staticValues;
3449 definition.staticFunctions = Instance_staticFunctions;
3450 definition.hasProperty = &Instance_hasProperty;
3451 definition.getProperty = &Instance_getProperty;
3452 definition.setProperty = &Instance_setProperty;
3453 definition.deleteProperty = &Instance_deleteProperty;
3454 definition.getPropertyNames = &Instance_getPropertyNames;
3455 definition.callAsConstructor = &Instance_callAsConstructor;
3456 definition.hasInstance = &Instance_hasInstance;
3457 definition.finalize = &Finalize;
3458 Instance_ = JSClassCreate(&definition);
3459
3460 definition = kJSClassDefinitionEmpty;
3461 definition.className = "Internal";
3462 definition.staticFunctions = Internal_staticFunctions;
3463 definition.hasProperty = &Internal_hasProperty;
3464 definition.getProperty = &Internal_getProperty;
3465 definition.setProperty = &Internal_setProperty;
3466 definition.getPropertyNames = &Internal_getPropertyNames;
3467 definition.finalize = &Finalize;
3468 Internal_ = JSClassCreate(&definition);
3469
3470 definition = kJSClassDefinitionEmpty;
3471 definition.className = "Message";
3472 definition.staticFunctions = Functor_staticFunctions;
3473 definition.callAsFunction = &Message_callAsFunction;
3474 definition.finalize = &Finalize;
3475 Message_ = JSClassCreate(&definition);
3476
3477 definition = kJSClassDefinitionEmpty;
3478 definition.className = "Messages";
3479 definition.hasProperty = &Messages_hasProperty;
3480 definition.getProperty = &Messages_getProperty;
3481 definition.setProperty = &Messages_setProperty;
3482 #if !__OBJC2__
3483 definition.deleteProperty = &Messages_deleteProperty;
3484 #endif
3485 definition.getPropertyNames = &Messages_getPropertyNames;
3486 definition.finalize = &Finalize;
3487 Messages_ = JSClassCreate(&definition);
3488
3489 definition = kJSClassDefinitionEmpty;
3490 definition.className = "NSArrayPrototype";
3491 //definition.hasProperty = &NSArrayPrototype_hasProperty;
3492 //definition.getProperty = &NSArrayPrototype_getProperty;
3493 //definition.setProperty = &NSArrayPrototype_setProperty;
3494 //definition.deleteProperty = &NSArrayPrototype_deleteProperty;
3495 //definition.getPropertyNames = &NSArrayPrototype_getPropertyNames;
3496 NSArrayPrototype_ = JSClassCreate(&definition);
3497
3498 definition = kJSClassDefinitionEmpty;
3499 definition.className = "Pointer";
3500 definition.staticValues = Pointer_staticValues;
3501 definition.staticFunctions = Pointer_staticFunctions;
3502 definition.getProperty = &Pointer_getProperty;
3503 definition.setProperty = &Pointer_setProperty;
3504 definition.finalize = &Finalize;
3505 Pointer_ = JSClassCreate(&definition);
3506
3507 definition = kJSClassDefinitionEmpty;
3508 definition.className = "Selector";
3509 definition.staticValues = CYValue_staticValues;
3510 definition.staticFunctions = Selector_staticFunctions;
3511 definition.callAsFunction = &Selector_callAsFunction;
3512 definition.finalize = &Finalize;
3513 Selector_ = JSClassCreate(&definition);
3514
3515 definition = kJSClassDefinitionEmpty;
3516 definition.className = "Struct";
3517 definition.staticFunctions = Struct_staticFunctions;
3518 definition.getProperty = &Struct_getProperty;
3519 definition.setProperty = &Struct_setProperty;
3520 definition.getPropertyNames = &Struct_getPropertyNames;
3521 definition.finalize = &Finalize;
3522 Struct_ = JSClassCreate(&definition);
3523
3524 definition = kJSClassDefinitionEmpty;
3525 definition.className = "Type";
3526 definition.staticFunctions = Type_staticFunctions;
3527 //definition.getProperty = &Type_getProperty;
3528 definition.callAsFunction = &Type_callAsFunction;
3529 definition.callAsConstructor = &Type_callAsConstructor;
3530 definition.finalize = &Finalize;
3531 Type_ = JSClassCreate(&definition);
3532
3533 definition = kJSClassDefinitionEmpty;
3534 definition.className = "Runtime";
3535 definition.getProperty = &Runtime_getProperty;
3536 Runtime_ = JSClassCreate(&definition);
3537
3538 definition = kJSClassDefinitionEmpty;
3539 definition.className = "ObjectiveC::Classes";
3540 definition.getProperty = &ObjectiveC_Classes_getProperty;
3541 definition.getPropertyNames = &ObjectiveC_Classes_getPropertyNames;
3542 ObjectiveC_Classes_ = JSClassCreate(&definition);
3543
3544 definition = kJSClassDefinitionEmpty;
3545 definition.className = "ObjectiveC::Images";
3546 definition.getProperty = &ObjectiveC_Images_getProperty;
3547 definition.getPropertyNames = &ObjectiveC_Images_getPropertyNames;
3548 ObjectiveC_Images_ = JSClassCreate(&definition);
3549
3550 definition = kJSClassDefinitionEmpty;
3551 definition.className = "ObjectiveC::Image::Classes";
3552 definition.getProperty = &ObjectiveC_Image_Classes_getProperty;
3553 definition.getPropertyNames = &ObjectiveC_Image_Classes_getPropertyNames;
3554 ObjectiveC_Image_Classes_ = JSClassCreate(&definition);
3555
3556 definition = kJSClassDefinitionEmpty;
3557 definition.className = "ObjectiveC::Protocols";
3558 definition.getProperty = &ObjectiveC_Protocols_getProperty;
3559 definition.getPropertyNames = &ObjectiveC_Protocols_getPropertyNames;
3560 ObjectiveC_Protocols_ = JSClassCreate(&definition);
3561
3562 definition = kJSClassDefinitionEmpty;
3563 //definition.getProperty = &Global_getProperty;
3564 JSClassRef Global(JSClassCreate(&definition));
3565
3566 JSGlobalContextRef context(JSGlobalContextCreate(Global));
3567 Context_ = context;
3568
3569 JSObjectRef global(CYGetGlobalObject(context));
3570
3571 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
3572 ObjectiveC_ = JSObjectMake(context, NULL, NULL);
3573 CYSetProperty(context, global, CYJSString("ObjectiveC"), ObjectiveC_);
3574
3575 CYSetProperty(context, ObjectiveC_, CYJSString("classes"), JSObjectMake(context, ObjectiveC_Classes_, NULL));
3576 CYSetProperty(context, ObjectiveC_, CYJSString("images"), JSObjectMake(context, ObjectiveC_Images_, NULL));
3577 CYSetProperty(context, ObjectiveC_, CYJSString("protocols"), JSObjectMake(context, ObjectiveC_Protocols_, NULL));
3578
3579 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
3580 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
3581 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
3582
3583 length_ = JSStringCreateWithUTF8CString("length");
3584 message_ = JSStringCreateWithUTF8CString("message");
3585 name_ = JSStringCreateWithUTF8CString("name");
3586 prototype_ = JSStringCreateWithUTF8CString("prototype");
3587 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
3588 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
3589
3590 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
3591 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
3592
3593 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
3594 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
3595 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
3596 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
3597
3598 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
3599 JSObjectRef Instance(JSObjectMakeConstructor(context, Instance_, &Instance_new));
3600 JSObjectRef Message(JSObjectMakeConstructor(context, Message_, NULL));
3601 JSObjectRef Selector(JSObjectMakeConstructor(context, Selector_, &Selector_new));
3602
3603 Instance_prototype_ = (JSObjectRef) CYGetProperty(context, Instance, prototype_);
3604
3605 JSValueRef function(CYGetProperty(context, Function_, prototype_));
3606 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Message, prototype_), function);
3607 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), function);
3608 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Selector, prototype_), function);
3609
3610 CYSetProperty(context, global, CYJSString("Functor"), Functor);
3611 CYSetProperty(context, global, CYJSString("Instance"), Instance);
3612 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
3613 CYSetProperty(context, global, CYJSString("Selector"), Selector);
3614 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_, &Type_new));
3615
3616 MSHookFunction(&objc_registerClassPair, MSHake(objc_registerClassPair));
3617
3618 class_addMethod(NSCFType_, @selector(cy$toJSON:), reinterpret_cast<IMP>(&NSCFType$cy$toJSON), "@12@0:4@8");
3619
3620 CYSetProperty(context, global, CYJSString("objc_registerClassPair"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_registerClassPair"), &objc_registerClassPair_));
3621 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
3622 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
3623
3624 System_ = JSObjectMake(context, NULL, NULL);
3625 CYSetProperty(context, global, CYJSString("system"), System_);
3626 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
3627 //CYSetProperty(context, System_, CYJSString("global"), global);
3628
3629 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
3630
3631 Result_ = JSStringCreateWithUTF8CString("_");
3632
3633 JSValueProtect(context, Array_);
3634 JSValueProtect(context, Function_);
3635 JSValueProtect(context, String_);
3636
3637 JSValueProtect(context, Instance_prototype_);
3638 JSValueProtect(context, Object_prototype_);
3639
3640 JSValueProtect(context, Array_prototype_);
3641 JSValueProtect(context, Array_pop_);
3642 JSValueProtect(context, Array_push_);
3643 JSValueProtect(context, Array_splice_);
3644 }
3645
3646 return Context_;
3647 }