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