]> git.saurik.com Git - cycript.git/blob - Execute.cpp
241ba325ab6199cd7cf9061156cade4e3d3cfa4e
[cycript.git] / Execute.cpp
1 /* Cycript - Optimizing JavaScript Compiler/Runtime
2 * Copyright (C) 2009-2013 Jay Freeman (saurik)
3 */
4
5 /* GNU General Public License, Version 3 {{{ */
6 /*
7 * Cycript is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
11 *
12 * Cycript is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Cycript. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "Internal.hpp"
23
24 #include <dlfcn.h>
25 #include <dirent.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28
29 #include "cycript.hpp"
30
31 #include "sig/parse.hpp"
32 #include "sig/ffi_type.hpp"
33
34 #include "Pooling.hpp"
35 #include "Execute.hpp"
36
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39
40 #include <iostream>
41 #include <set>
42 #include <map>
43 #include <iomanip>
44 #include <sstream>
45 #include <cmath>
46
47 #include "Parser.hpp"
48
49 #include "Decode.hpp"
50 #include "Error.hpp"
51 #include "JavaScript.hpp"
52 #include "String.hpp"
53
54 struct CYHooks *hooks_;
55
56 /* JavaScript Properties {{{ */
57 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
58 return _jsccall(JSObjectGetPropertyAtIndex, context, object, index);
59 }
60
61 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
62 return _jsccall(JSObjectGetProperty, context, object, name);
63 }
64
65 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
66 _jsccall(JSObjectSetPropertyAtIndex, context, object, index, value);
67 }
68
69 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
70 _jsccall(JSObjectSetProperty, context, object, name, value, attributes);
71 }
72
73 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
74 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
75 }
76 /* }}} */
77 /* JavaScript Strings {{{ */
78 JSStringRef CYCopyJSString(const char *value) {
79 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
80 }
81
82 JSStringRef CYCopyJSString(JSStringRef value) {
83 return value == NULL ? NULL : JSStringRetain(value);
84 }
85
86 JSStringRef CYCopyJSString(CYUTF8String value) {
87 // XXX: this is very wrong; it needs to convert to UTF16 and then create from there
88 return CYCopyJSString(value.data);
89 }
90
91 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
92 if (JSValueIsNull(context, value))
93 return NULL;
94 return _jsccall(JSValueToStringCopy, context, value);
95 }
96
97 static CYUTF16String CYCastUTF16String(JSStringRef value) {
98 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
99 }
100
101 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, JSStringRef value) {
102 return CYPoolUTF8String(pool, CYCastUTF16String(value));
103 }
104
105 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSStringRef value) {
106 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
107 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
108 return utf8.data;
109 }
110
111 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSValueRef value) {
112 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
113 }
114 /* }}} */
115 /* Index Offsets {{{ */
116 size_t CYGetIndex(CYPool &pool, JSContextRef context, JSStringRef value) {
117 return CYGetIndex(CYPoolUTF8String(pool, context, value));
118 }
119 /* }}} */
120
121 static JSClassRef All_;
122 static JSClassRef Context_;
123 JSClassRef Functor_;
124 static JSClassRef Global_;
125 static JSClassRef Pointer_;
126 static JSClassRef Struct_;
127
128 JSStringRef Array_s;
129 JSStringRef cy_s;
130 JSStringRef cyi_s;
131 JSStringRef length_s;
132 JSStringRef message_s;
133 JSStringRef name_s;
134 JSStringRef pop_s;
135 JSStringRef prototype_s;
136 JSStringRef push_s;
137 JSStringRef splice_s;
138 JSStringRef toCYON_s;
139 JSStringRef toJSON_s;
140 JSStringRef toPointer_s;
141 JSStringRef toString_s;
142
143 static JSStringRef Result_;
144
145 void CYFinalize(JSObjectRef object) {
146 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
147 _assert(internal->count_ != _not(unsigned));
148 if (--internal->count_ == 0)
149 delete internal;
150 }
151
152 void Structor_(CYPool &pool, sig::Type *&type) {
153 if (
154 type->primitive == sig::pointer_P &&
155 type->data.data.type != NULL &&
156 type->data.data.type->primitive == sig::struct_P &&
157 type->data.data.type->name != NULL &&
158 strcmp(type->data.data.type->name, "_objc_class") == 0
159 ) {
160 type->primitive = sig::typename_P;
161 type->data.data.type = NULL;
162 return;
163 }
164
165 if (type->primitive != sig::struct_P || type->name == NULL)
166 return;
167
168 size_t length(strlen(type->name));
169 char keyed[length + 2];
170 memcpy(keyed + 1, type->name, length + 1);
171
172 static const char *modes = "34";
173 for (size_t i(0); i != 2; ++i) {
174 char mode(modes[i]);
175 keyed[0] = mode;
176
177 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
178 switch (mode) {
179 case '3':
180 sig::Parse(pool, &type->data.signature, entry->value_, &Structor_);
181 break;
182
183 case '4': {
184 sig::Signature signature;
185 sig::Parse(pool, &signature, entry->value_, &Structor_);
186 type = signature.elements[0].type;
187 } break;
188 }
189 }
190 }
191
192 JSClassRef Type_privateData::Class_;
193
194 struct Context :
195 CYData
196 {
197 JSGlobalContextRef context_;
198
199 Context(JSGlobalContextRef context) :
200 context_(context)
201 {
202 }
203 };
204
205 struct Pointer :
206 CYOwned
207 {
208 Type_privateData *type_;
209 size_t length_;
210
211 Pointer(void *value, JSContextRef context, JSObjectRef owner, size_t length, sig::Type *type) :
212 CYOwned(value, context, owner),
213 type_(new(*pool_) Type_privateData(type)),
214 length_(length)
215 {
216 }
217 };
218
219 struct Struct_privateData :
220 CYOwned
221 {
222 Type_privateData *type_;
223
224 Struct_privateData(JSContextRef context, JSObjectRef owner) :
225 CYOwned(NULL, context, owner)
226 {
227 }
228 };
229
230 typedef std::map<const char *, Type_privateData *, CYCStringLess> TypeMap;
231 static TypeMap Types_;
232
233 JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
234 Struct_privateData *internal(new Struct_privateData(context, owner));
235 CYPool &pool(*internal->pool_);
236 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
237 internal->type_ = typical;
238
239 if (owner != NULL)
240 internal->value_ = data;
241 else {
242 size_t size(typical->GetFFI()->size);
243 void *copy(internal->pool_->malloc<void>(size));
244 memcpy(copy, data, size);
245 internal->value_ = copy;
246 }
247
248 return JSObjectMake(context, Struct_, internal);
249 }
250
251 static void *CYCastSymbol(const char *name) {
252 return dlsym(RTLD_DEFAULT, name);
253 }
254
255 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
256 return JSValueMakeBoolean(context, value);
257 }
258
259 JSValueRef CYCastJSValue(JSContextRef context, double value) {
260 return JSValueMakeNumber(context, value);
261 }
262
263 #define CYCastJSValue_(Type_) \
264 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
265 return JSValueMakeNumber(context, static_cast<double>(value)); \
266 }
267
268 CYCastJSValue_(int)
269 CYCastJSValue_(unsigned int)
270 CYCastJSValue_(long int)
271 CYCastJSValue_(long unsigned int)
272 CYCastJSValue_(long long int)
273 CYCastJSValue_(long long unsigned int)
274
275 JSValueRef CYJSUndefined(JSContextRef context) {
276 return JSValueMakeUndefined(context);
277 }
278
279 double CYCastDouble(JSContextRef context, JSValueRef value) {
280 return _jsccall(JSValueToNumber, context, value);
281 }
282
283 bool CYCastBool(JSContextRef context, JSValueRef value) {
284 return JSValueToBoolean(context, value);
285 }
286
287 JSValueRef CYJSNull(JSContextRef context) {
288 return JSValueMakeNull(context);
289 }
290
291 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
292 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
293 }
294
295 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
296 return CYCastJSValue(context, CYJSString(value));
297 }
298
299 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
300 return _jsccall(JSValueToObject, context, value);
301 }
302
303 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
304 return _jsccall(JSObjectCallAsFunction, context, function, _this, count, arguments);
305 }
306
307 bool CYIsCallable(JSContextRef context, JSValueRef value) {
308 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
309 }
310
311 size_t CYArrayLength(JSContextRef context, JSObjectRef array) {
312 return CYCastDouble(context, CYGetProperty(context, array, length_s));
313 }
314
315 JSValueRef CYArrayGet(JSContextRef context, JSObjectRef array, size_t index) {
316 return _jsccall(JSObjectGetPropertyAtIndex, context, array, index);
317 }
318
319 void CYArrayPush(JSContextRef context, JSObjectRef array, JSValueRef value) {
320 JSValueRef arguments[1];
321 arguments[0] = value;
322 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
323 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, push_s)), array, 1, arguments);
324 }
325
326 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
327 if (count == 0)
328 printf("\n");
329 else {
330 CYPool pool;
331 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
332 }
333
334 return CYJSUndefined(context);
335 } CYCatch(NULL) }
336
337 static size_t Nonce_(0);
338
339 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
340 CYPool pool;
341 const char *name(pool.strcat(CYPoolCString(pool, context, arguments[0]), pool.itoa(Nonce_++), NULL));
342 return CYCastJSValue(context, name);
343 } CYCatch(NULL) }
344
345 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
346 JSGarbageCollect(context);
347 return CYJSUndefined(context);
348 } CYCatch(NULL) }
349
350 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
351 switch (JSType type = JSValueGetType(context, value)) {
352 case kJSTypeUndefined:
353 return "undefined";
354 case kJSTypeNull:
355 return "null";
356 case kJSTypeBoolean:
357 return CYCastBool(context, value) ? "true" : "false";
358
359 case kJSTypeNumber: {
360 std::ostringstream str;
361 CYNumerify(str, CYCastDouble(context, value));
362 std::string value(str.str());
363 return pool.strmemdup(value.c_str(), value.size());
364 } break;
365
366 case kJSTypeString: {
367 std::ostringstream str;
368 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
369 CYStringify(str, string.data, string.size);
370 std::string value(str.str());
371 return pool.strmemdup(value.c_str(), value.size());
372 } break;
373
374 case kJSTypeObject:
375 return CYPoolCCYON(pool, context, (JSObjectRef) value);
376 default:
377 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
378 }
379 } CYCatch(NULL) }
380
381 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value) {
382 return _jsccall(CYPoolCCYON, pool, context, value);
383 }
384
385 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSObjectRef object) {
386 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
387 if (CYIsCallable(context, toCYON)) {
388 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
389 _assert(value != NULL);
390 return CYPoolCString(pool, context, value);
391 }
392
393 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
394 if (CYIsCallable(context, toJSON)) {
395 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
396 return _jsccall(CYPoolCCYON, pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments));
397 }
398
399 if (JSObjectIsFunction(context, object)) {
400 JSValueRef toString(CYGetProperty(context, object, toString_s));
401 if (CYIsCallable(context, toString)) {
402 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
403 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
404 _assert(value != NULL);
405 return CYPoolCString(pool, context, value);
406 }
407 }
408
409 std::ostringstream str;
410
411 str << '{';
412
413 // XXX: this is, sadly, going to leak
414 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
415
416 bool comma(false);
417
418 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
419 if (comma)
420 str << ',';
421 else
422 comma = true;
423
424 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
425 CYUTF8String string(CYPoolUTF8String(pool, context, name));
426
427 if (CYIsKey(string))
428 str << string.data;
429 else
430 CYStringify(str, string.data, string.size);
431
432 str << ':';
433
434 try {
435 JSValueRef value(CYGetProperty(context, object, name));
436 str << CYPoolCCYON(pool, context, value);
437 } catch (const CYException &error) {
438 str << "@error";
439 }
440 }
441
442 JSPropertyNameArrayRelease(names);
443
444 str << '}';
445
446 std::string string(str.str());
447 return pool.strmemdup(string.c_str(), string.size());
448 }
449
450 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
451 CYPool pool;
452 std::ostringstream str;
453
454 str << '[';
455
456 JSValueRef length(CYGetProperty(context, _this, length_s));
457 bool comma(false);
458
459 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
460 if (comma)
461 str << ',';
462 else
463 comma = true;
464
465 try {
466 JSValueRef value(CYGetProperty(context, _this, index));
467 if (!JSValueIsUndefined(context, value))
468 str << CYPoolCCYON(pool, context, value);
469 else {
470 str << ',';
471 comma = false;
472 }
473 } catch (const CYException &error) {
474 str << "@error";
475 }
476 }
477
478 str << ']';
479
480 std::string value(str.str());
481 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
482 } CYCatch(NULL) }
483
484 static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
485 CYPool pool;
486 std::ostringstream str;
487
488 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
489 CYStringify(str, string.data, string.size);
490
491 std::string value(str.str());
492 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
493 } CYCatch(NULL) }
494
495 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
496 Pointer *internal(new Pointer(pointer, context, owner, length, type));
497 return JSObjectMake(context, Pointer_, internal);
498 }
499
500 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const sig::Signature &signature) {
501 return JSObjectMake(context, Functor_, new cy::Functor(signature, function));
502 }
503
504 static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *encoding, void **cache) {
505 cy::Functor *internal;
506 if (*cache != NULL)
507 internal = reinterpret_cast<cy::Functor *>(*cache);
508 else {
509 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
510 if (function == NULL)
511 return NULL;
512
513 internal = new cy::Functor(encoding, function);
514 *cache = internal;
515 }
516
517 ++internal->count_;
518 return JSObjectMake(context, Functor_, internal);
519 }
520
521 static bool CYGetOffset(CYPool &pool, JSContextRef context, JSStringRef value, ssize_t &index) {
522 return CYGetOffset(CYPoolCString(pool, context, value), index);
523 }
524
525 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
526 switch (JSValueGetType(context, value)) {
527 case kJSTypeNull:
528 return NULL;
529 case kJSTypeObject: {
530 JSObjectRef object((JSObjectRef) value);
531 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
532 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
533 return internal->value_;
534 }
535 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
536 if (CYIsCallable(context, toPointer)) {
537 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
538 _assert(value != NULL);
539 return CYCastPointer_(context, value);
540 }
541 } default:
542 double number(CYCastDouble(context, value));
543 if (std::isnan(number))
544 throw CYJSError(context, "cannot convert value to pointer");
545 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
546 }
547 }
548
549 void CYPoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
550 switch (type->primitive) {
551 case sig::boolean_P:
552 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
553 break;
554
555 #define CYPoolFFI_(primitive, native) \
556 case sig::primitive ## _P: \
557 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
558 break;
559
560 CYPoolFFI_(uchar, unsigned char)
561 CYPoolFFI_(char, char)
562 CYPoolFFI_(ushort, unsigned short)
563 CYPoolFFI_(short, short)
564 CYPoolFFI_(ulong, unsigned long)
565 CYPoolFFI_(long, long)
566 CYPoolFFI_(uint, unsigned int)
567 CYPoolFFI_(int, int)
568 CYPoolFFI_(ulonglong, unsigned long long)
569 CYPoolFFI_(longlong, long long)
570 CYPoolFFI_(float, float)
571 CYPoolFFI_(double, double)
572
573 case sig::array_P: {
574 uint8_t *base(reinterpret_cast<uint8_t *>(data));
575 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
576 for (size_t index(0); index != type->data.data.size; ++index) {
577 ffi_type *field(ffi->elements[index]);
578
579 JSValueRef rhs;
580 if (aggregate == NULL)
581 rhs = value;
582 else {
583 rhs = CYGetProperty(context, aggregate, index);
584 if (JSValueIsUndefined(context, rhs))
585 throw CYJSError(context, "unable to extract array value");
586 }
587
588 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
589 // XXX: alignment?
590 base += field->size;
591 }
592 } break;
593
594 case sig::pointer_P:
595 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
596 break;
597
598 case sig::string_P:
599 _assert(pool != NULL);
600 *reinterpret_cast<const char **>(data) = CYPoolCString(*pool, context, value);
601 break;
602
603 case sig::struct_P: {
604 uint8_t *base(reinterpret_cast<uint8_t *>(data));
605 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
606 for (size_t index(0); index != type->data.signature.count; ++index) {
607 sig::Element *element(&type->data.signature.elements[index]);
608 ffi_type *field(ffi->elements[index]);
609
610 JSValueRef rhs;
611 if (aggregate == NULL)
612 rhs = value;
613 else {
614 rhs = CYGetProperty(context, aggregate, index);
615 if (JSValueIsUndefined(context, rhs)) {
616 if (element->name != NULL)
617 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
618 else
619 goto undefined;
620 if (JSValueIsUndefined(context, rhs)) undefined:
621 throw CYJSError(context, "unable to extract structure value");
622 }
623 }
624
625 CYPoolFFI(pool, context, element->type, field, base, rhs);
626 // XXX: alignment?
627 base += field->size;
628 }
629 } break;
630
631 case sig::void_P:
632 break;
633
634 default:
635 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
636 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
637 return;
638
639 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
640 }
641 }
642
643 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
644 switch (type->primitive) {
645 case sig::boolean_P:
646 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
647
648 #define CYFromFFI_(primitive, native) \
649 case sig::primitive ## _P: \
650 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
651
652 CYFromFFI_(uchar, unsigned char)
653 CYFromFFI_(char, char)
654 CYFromFFI_(ushort, unsigned short)
655 CYFromFFI_(short, short)
656 CYFromFFI_(ulong, unsigned long)
657 CYFromFFI_(long, long)
658 CYFromFFI_(uint, unsigned int)
659 CYFromFFI_(int, int)
660 CYFromFFI_(ulonglong, unsigned long long)
661 CYFromFFI_(longlong, long long)
662 CYFromFFI_(float, float)
663 CYFromFFI_(double, double)
664
665 case sig::array_P:
666 if (void *pointer = data)
667 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
668 else goto null;
669
670 case sig::pointer_P:
671 if (void *pointer = *reinterpret_cast<void **>(data))
672 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
673 else goto null;
674
675 case sig::string_P:
676 if (char *utf8 = *reinterpret_cast<char **>(data))
677 return CYCastJSValue(context, utf8);
678 else goto null;
679
680 case sig::struct_P:
681 return CYMakeStruct(context, data, type, ffi, owner);
682 case sig::void_P:
683 return CYJSUndefined(context);
684
685 null:
686 return CYJSNull(context);
687 default:
688 if (hooks_ != NULL && hooks_->FromFFI != NULL)
689 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
690 return value;
691
692 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
693 }
694 }
695
696 void CYExecuteClosure(ffi_cif *cif, void *result, void **arguments, void *arg, JSValueRef (*adapter)(JSContextRef, size_t, JSValueRef[], JSObjectRef)) {
697 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
698
699 JSContextRef context(internal->context_);
700
701 size_t count(internal->cif_.nargs);
702 JSValueRef values[count];
703
704 for (size_t index(0); index != count; ++index)
705 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
706
707 JSValueRef value(adapter(context, count, values, internal->function_));
708 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
709 }
710
711 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
712 return CYCallAsFunction(context, function, NULL, count, values);
713 }
714
715 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
716 CYExecuteClosure(cif, result, arguments, arg, &FunctionAdapter_);
717 }
718
719 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const sig::Signature &signature, void (*callback)(ffi_cif *, void *, void **, void *)) {
720 // XXX: in case of exceptions this will leak
721 // XXX: in point of fact, this may /need/ to leak :(
722 Closure_privateData *internal(new Closure_privateData(context, function, signature));
723
724 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
725 void *executable;
726 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
727
728 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, callback, internal, executable));
729 _assert(status == FFI_OK);
730
731 internal->value_ = executable;
732 #else
733 ffi_closure *closure((ffi_closure *) _syscall(mmap(
734 NULL, sizeof(ffi_closure),
735 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
736 -1, 0
737 )));
738
739 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
740 _assert(status == FFI_OK);
741
742 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
743
744 internal->value_ = closure;
745 #endif
746
747 return internal;
748 }
749
750 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const sig::Signature &signature) {
751 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &FunctionClosure_));
752 JSObjectRef object(JSObjectMake(context, Functor_, internal));
753 // XXX: see above notes about needing to leak
754 JSValueProtect(CYGetJSContext(context), object);
755 return object;
756 }
757
758 JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
759 return CYCastJSObject(context, CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name));
760 }
761
762 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const sig::Signature &signature) {
763 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
764
765 bool function(_jsccall(JSValueIsInstanceOfConstructor, context, value, Function));
766 if (function) {
767 JSObjectRef function(CYCastJSObject(context, value));
768 return CYMakeFunctor(context, function, signature);
769 } else {
770 void (*function)()(CYCastPointer<void (*)()>(context, value));
771 return CYMakeFunctor(context, function, signature);
772 }
773 }
774
775 static bool Index_(CYPool &pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
776 Type_privateData *typical(internal->type_);
777 sig::Type *type(typical->type_);
778 if (type == NULL)
779 return false;
780
781 const char *name(CYPoolCString(pool, context, property));
782 size_t length(strlen(name));
783 double number(CYCastDouble(name, length));
784
785 size_t count(type->data.signature.count);
786
787 if (std::isnan(number)) {
788 if (property == NULL)
789 return false;
790
791 sig::Element *elements(type->data.signature.elements);
792
793 for (size_t local(0); local != count; ++local) {
794 sig::Element *element(&elements[local]);
795 if (element->name != NULL && strcmp(name, element->name) == 0) {
796 index = local;
797 goto base;
798 }
799 }
800
801 return false;
802 } else {
803 index = static_cast<ssize_t>(number);
804 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
805 return false;
806 }
807
808 base:
809 ffi_type **elements(typical->GetFFI()->elements);
810
811 base = reinterpret_cast<uint8_t *>(internal->value_);
812 for (ssize_t local(0); local != index; ++local)
813 base += elements[local]->size;
814
815 return true;
816 }
817
818 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
819 CYPool pool;
820 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
821
822 if (JSStringIsEqual(property, length_s))
823 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
824
825 Type_privateData *typical(internal->type_);
826
827 if (typical->type_ == NULL)
828 return NULL;
829
830 ssize_t offset;
831 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
832 offset = 0;
833 else if (!CYGetOffset(pool, context, property, offset))
834 return NULL;
835
836 ffi_type *ffi(typical->GetFFI());
837
838 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
839 base += ffi->size * offset;
840
841 JSObjectRef owner(internal->GetOwner() ?: object);
842 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
843 } CYCatch(NULL) }
844
845 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
846 CYPool pool;
847 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
848 Type_privateData *typical(internal->type_);
849
850 if (typical->type_ == NULL)
851 return false;
852
853 ssize_t offset;
854 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
855 offset = 0;
856 else if (!CYGetOffset(pool, context, property, offset))
857 return false;
858
859 ffi_type *ffi(typical->GetFFI());
860
861 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
862 base += ffi->size * offset;
863
864 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
865 return true;
866 } CYCatch(false) }
867
868 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
869 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
870 Type_privateData *typical(internal->type_);
871 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
872 } CYCatch(NULL) }
873
874 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
875 CYPool pool;
876 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
877 Type_privateData *typical(internal->type_);
878
879 ssize_t index;
880 uint8_t *base;
881
882 if (!Index_(pool, context, internal, property, index, base))
883 return NULL;
884
885 JSObjectRef owner(internal->GetOwner() ?: object);
886
887 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
888 } CYCatch(NULL) }
889
890 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
891 CYPool pool;
892 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
893 Type_privateData *typical(internal->type_);
894
895 ssize_t index;
896 uint8_t *base;
897
898 if (!Index_(pool, context, internal, property, index, base))
899 return false;
900
901 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
902 return true;
903 } CYCatch(false) }
904
905 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
906 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
907 Type_privateData *typical(internal->type_);
908 sig::Type *type(typical->type_);
909
910 if (type == NULL)
911 return;
912
913 size_t count(type->data.signature.count);
914 sig::Element *elements(type->data.signature.elements);
915
916 char number[32];
917
918 for (size_t index(0); index != count; ++index) {
919 const char *name;
920 name = elements[index].name;
921
922 if (name == NULL) {
923 sprintf(number, "%zu", index);
924 name = number;
925 }
926
927 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
928 }
929 }
930
931 JSValueRef CYCallFunction(CYPool &pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, sig::Signature *signature, ffi_cif *cif, void (*function)()) {
932 if (setups + count != signature->count - 1)
933 throw CYJSError(context, "incorrect number of arguments to ffi function");
934
935 size_t size(setups + count);
936 void *values[size];
937 memcpy(values, setup, sizeof(void *) * setups);
938
939 for (size_t index(setups); index != size; ++index) {
940 sig::Element *element(&signature->elements[index + 1]);
941 ffi_type *ffi(cif->arg_types[index]);
942 // XXX: alignment?
943 values[index] = new(pool) uint8_t[ffi->size];
944 CYPoolFFI(&pool, context, element->type, ffi, values[index], arguments[index - setups]);
945 }
946
947 uint8_t value[cif->rtype->size];
948
949 if (hooks_ != NULL && hooks_->CallFunction != NULL)
950 (*hooks_->CallFunction)(context, cif, function, value, values);
951 else
952 ffi_call(cif, function, value, values);
953
954 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
955 }
956
957 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
958 CYPool pool;
959 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
960 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, &internal->signature_, &internal->cif_, internal->GetValue());
961 } CYCatch(NULL) }
962
963 JSObjectRef CYMakeType(JSContextRef context, const char *encoding) {
964 Type_privateData *internal(new Type_privateData(encoding));
965 return JSObjectMake(context, Type_privateData::Class_, internal);
966 }
967
968 JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
969 Type_privateData *internal(new Type_privateData(type));
970 return JSObjectMake(context, Type_privateData::Class_, internal);
971 }
972
973 JSObjectRef CYMakeType(JSContextRef context, sig::Signature *signature) {
974 CYPool pool;
975
976 sig::Type type;
977 type.name = NULL;
978 type.flags = 0;
979
980 type.primitive = sig::function_P;
981 sig::Copy(pool, type.data.signature, *signature);
982
983 return CYMakeType(context, &type);
984 }
985
986 static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
987 JSObjectRef global(CYGetGlobalObject(context));
988 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
989 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
990
991 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
992 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
993 if (JSValueRef value = CYGetProperty(context, space, property))
994 if (!JSValueIsUndefined(context, value))
995 return value;
996
997 CYPool pool;
998 CYUTF8String name(CYPoolUTF8String(pool, context, property));
999
1000 size_t length(name.size);
1001 char keyed[length + 2];
1002 memcpy(keyed + 1, name.data, length + 1);
1003
1004 static const char *modes = "0124";
1005 for (size_t i(0); i != 4; ++i) {
1006 char mode(modes[i]);
1007 keyed[0] = mode;
1008
1009 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1010 switch (mode) {
1011 case '0':
1012 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
1013
1014 case '1':
1015 return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);
1016
1017 case '2':
1018 if (void *symbol = CYCastSymbol(name.data)) {
1019 // XXX: this is horrendously inefficient
1020 sig::Signature signature;
1021 sig::Parse(pool, &signature, entry->value_, &Structor_);
1022 ffi_cif cif;
1023 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1024 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1025 } else return NULL;
1026
1027 // XXX: implement case 3
1028 case '4':
1029 return CYMakeType(context, entry->value_);
1030 }
1031 }
1032
1033 return NULL;
1034 } CYCatch(NULL) }
1035
1036 static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1037 JSObjectRef global(CYGetGlobalObject(context));
1038 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1039 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1040
1041 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1042 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1043 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1044 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1045 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1046 JSPropertyNameArrayRelease(subset);
1047 }
1048 }
1049
1050 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1051 if (count != 2)
1052 throw CYJSError(context, "incorrect number of arguments to Pointer constructor");
1053
1054 CYPool pool;
1055
1056 void *value(CYCastPointer<void *>(context, arguments[0]));
1057 const char *type(CYPoolCString(pool, context, arguments[1]));
1058
1059 sig::Signature signature;
1060 sig::Parse(pool, &signature, type, &Structor_);
1061
1062 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1063 } CYCatch(NULL) }
1064
1065 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1066 if (count != 1)
1067 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1068 CYPool pool;
1069 const char *type(CYPoolCString(pool, context, arguments[0]));
1070 return CYMakeType(context, type);
1071 } CYCatch(NULL) }
1072
1073 static JSValueRef Type_callAsFunction_$With(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], sig::Primitive primitive, JSValueRef *exception) { CYTry {
1074 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1075
1076 CYPool pool;
1077
1078 sig::Type type;
1079 type.name = NULL;
1080 type.flags = 0;
1081
1082 type.primitive = primitive;
1083 type.data.signature.elements = new(pool) sig::Element[1 + count];
1084 type.data.signature.count = 1 + count;
1085
1086 type.data.signature.elements[0].name = NULL;
1087 type.data.signature.elements[0].type = internal->type_;
1088 type.data.signature.elements[0].offset = _not(size_t);
1089
1090 for (size_t i(0); i != count; ++i) {
1091 sig::Element &element(type.data.signature.elements[i + 1]);
1092 element.name = NULL;
1093 element.offset = _not(size_t);
1094
1095 JSObjectRef object(CYCastJSObject(context, arguments[i]));
1096 _assert(JSValueIsObjectOfClass(context, object, Type_privateData::Class_));
1097 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1098
1099 element.type = internal->type_;
1100 }
1101
1102 return CYMakeType(context, &type);
1103 } CYCatch(NULL) }
1104
1105 static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1106 if (count != 1)
1107 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1108 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1109
1110 CYPool pool;
1111 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1112 if (index == _not(size_t))
1113 throw CYJSError(context, "invalid array size used with Type.arrayOf");
1114
1115 sig::Type type;
1116 type.name = NULL;
1117 type.flags = 0;
1118
1119 type.primitive = sig::array_P;
1120 type.data.data.type = internal->type_;
1121 type.data.data.size = index;
1122
1123 return CYMakeType(context, &type);
1124 } CYCatch(NULL) }
1125
1126 static JSValueRef Type_callAsFunction_blockWith(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1127 return Type_callAsFunction_$With(context, object, _this, count, arguments, sig::block_P, exception);
1128 }
1129
1130 static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1131 if (count != 0)
1132 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1133 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1134
1135 sig::Type type(*internal->type_);
1136 type.flags |= JOC_TYPE_CONST;
1137 return CYMakeType(context, &type);
1138 } CYCatch(NULL) }
1139
1140 static JSValueRef Type_callAsFunction_functionWith(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1141 return Type_callAsFunction_$With(context, object, _this, count, arguments, sig::function_P, exception);
1142 }
1143
1144 static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1145 if (count != 0)
1146 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1147 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1148
1149 sig::Type type;
1150 type.name = NULL;
1151
1152 if (internal->type_->primitive == sig::char_P) {
1153 type.flags = internal->type_->flags;
1154 type.primitive = sig::string_P;
1155 type.data.data.type = NULL;
1156 type.data.data.size = 0;
1157 } else {
1158 type.flags = 0;
1159 type.primitive = sig::pointer_P;
1160 type.data.data.type = internal->type_;
1161 type.data.data.size = 0;
1162 }
1163
1164 return CYMakeType(context, &type);
1165 } CYCatch(NULL) }
1166
1167 static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1168 if (count != 1)
1169 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1170 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1171
1172 CYPool pool;
1173 const char *name(CYPoolCString(pool, context, arguments[0]));
1174
1175 sig::Type type(*internal->type_);
1176 type.name = name;
1177 return CYMakeType(context, &type);
1178 } CYCatch(NULL) }
1179
1180 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1181 if (count != 1)
1182 throw CYJSError(context, "incorrect number of arguments to type cast function");
1183 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1184
1185 if (internal->type_->primitive == sig::function_P)
1186 return CYMakeFunctor(context, arguments[0], internal->type_->data.signature);
1187
1188 sig::Type *type(internal->type_);
1189 ffi_type *ffi(internal->GetFFI());
1190 // XXX: alignment?
1191 uint8_t value[ffi->size];
1192 CYPool pool;
1193 CYPoolFFI(&pool, context, type, ffi, value, arguments[0]);
1194 return CYFromFFI(context, type, ffi, value);
1195 } CYCatch(NULL) }
1196
1197 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1198 if (count != 0)
1199 throw CYJSError(context, "incorrect number of arguments to Type allocator");
1200 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1201
1202 sig::Type *type(internal->type_);
1203 size_t length;
1204
1205 if (type->primitive != sig::array_P)
1206 length = _not(size_t);
1207 else {
1208 length = type->data.data.size;
1209 type = type->data.data.type;
1210 }
1211
1212 void *value(calloc(1, internal->GetFFI()->size));
1213 return CYMakePointer(context, value, length, type, NULL, NULL);
1214 } CYCatch(NULL) }
1215
1216 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1217 if (count != 2)
1218 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1219 CYPool pool;
1220 const char *encoding(CYPoolCString(pool, context, arguments[1]));
1221 sig::Signature signature;
1222 sig::Parse(pool, &signature, encoding, &Structor_);
1223 return CYMakeFunctor(context, arguments[0], signature);
1224 } CYCatch(NULL) }
1225
1226 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1227 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1228 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1229 } CYCatch(NULL) }
1230
1231 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1232 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1233 }
1234
1235 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1236 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1237 char string[32];
1238 sprintf(string, "%p", internal->value_);
1239 return CYCastJSValue(context, string);
1240 } CYCatch(NULL) }
1241
1242 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1243 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1244 if (internal->length_ != _not(size_t)) {
1245 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1246 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1247 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1248 } else try {
1249 CYPool pool;
1250 return CYCastJSValue(context, pool.strcat("&", CYPoolCCYON(pool, context, CYGetProperty(context, _this, cyi_s)), NULL));
1251 } catch (const CYException &e) {
1252 char string[32];
1253 sprintf(string, "%p", internal->value_);
1254 return CYCastJSValue(context, string);
1255 }
1256 } CYCatch(NULL) }
1257
1258 static JSValueRef Pointer_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1259 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1260 return CYMakeType(context, internal->type_->type_);
1261 } CYCatch(NULL) }
1262
1263 static JSValueRef Functor_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1264 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1265 return CYMakeType(context, &internal->signature_);
1266 } CYCatch(NULL) }
1267
1268 static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1269 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1270 return CYCastJSValue(context, internal->GetFFI()->alignment);
1271 } CYCatch(NULL) }
1272
1273 static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1274 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1275 return CYCastJSValue(context, internal->type_->name);
1276 } CYCatch(NULL) }
1277
1278 static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1279 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1280 return CYCastJSValue(context, internal->GetFFI()->size);
1281 } CYCatch(NULL) }
1282
1283 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1284 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1285 CYPool pool;
1286 const char *type(sig::Unparse(pool, internal->type_));
1287 return CYCastJSValue(context, CYJSString(type));
1288 } CYCatch(NULL) }
1289
1290 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1291 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1292 CYLocalPool pool;
1293 std::ostringstream out;
1294 CYOptions options;
1295 CYOutput output(out, options);
1296 (new(pool) CYEncodedType(Decode(pool, internal->type_)))->Output(output, CYNoFlags);
1297 return CYCastJSValue(context, CYJSString(out.str().c_str()));
1298 } CYCatch(NULL) }
1299
1300 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1301 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1302 }
1303
1304 static JSStaticFunction Pointer_staticFunctions[4] = {
1305 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1306 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1307 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1308 {NULL, NULL, 0}
1309 };
1310
1311 static JSStaticValue Pointer_staticValues[2] = {
1312 {"type", &Pointer_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1313 {NULL, NULL, NULL, 0}
1314 };
1315
1316 static JSStaticFunction Struct_staticFunctions[2] = {
1317 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1318 {NULL, NULL, 0}
1319 };
1320
1321 static JSStaticFunction Functor_staticFunctions[4] = {
1322 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1323 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1324 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1325 {NULL, NULL, 0}
1326 };
1327
1328 namespace cy {
1329 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1330 }
1331
1332 static JSStaticValue Functor_staticValues[2] = {
1333 {"type", &Functor_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1334 {NULL, NULL, NULL, 0}
1335 };
1336
1337 static JSStaticValue Type_staticValues[4] = {
1338 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1339 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1340 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1341 {NULL, NULL, NULL, 0}
1342 };
1343
1344 static JSStaticFunction Type_staticFunctions[10] = {
1345 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1346 {"blockWith", &Type_callAsFunction_blockWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1347 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1348 {"functionWith", &Type_callAsFunction_functionWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1349 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1350 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1351 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1352 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1353 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1354 {NULL, NULL, 0}
1355 };
1356
1357 static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1358
1359 void CYSetArgs(int argc, const char *argv[]) {
1360 JSContextRef context(CYGetJSContext());
1361 JSValueRef args[argc];
1362 for (int i(0); i != argc; ++i)
1363 args[i] = CYCastJSValue(context, argv[i]);
1364
1365 JSObjectRef array;
1366 if (JSObjectMakeArray$ != NULL)
1367 array = _jsccall(*JSObjectMakeArray$, context, argc, args);
1368 else {
1369 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1370 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1371 array = CYCastJSObject(context, value);
1372 }
1373
1374 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1375 CYSetProperty(context, System, CYJSString("args"), array);
1376 }
1377
1378 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1379 return JSContextGetGlobalObject(context);
1380 }
1381
1382 const char *CYExecute(JSContextRef context, CYPool &pool, CYUTF8String code) {
1383 JSValueRef exception(NULL);
1384
1385 void *handle;
1386 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1387 handle = (*hooks_->ExecuteStart)(context);
1388 else
1389 handle = NULL;
1390
1391 try {
1392
1393 JSValueRef result;
1394 try {
1395 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1396 } catch (const char *error) {
1397 return error;
1398 }
1399
1400 if (exception != NULL) error:
1401 return CYPoolCString(pool, context, CYJSString(context, exception));
1402
1403 if (JSValueIsUndefined(context, result))
1404 return NULL;
1405
1406 const char *json;
1407 try {
1408 json = CYPoolCCYON(pool, context, result, &exception);
1409 } catch (const char *error) {
1410 return error;
1411 }
1412
1413 if (exception != NULL)
1414 goto error;
1415
1416 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1417
1418 return json;
1419
1420 } catch (...) {
1421 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1422 (*hooks_->ExecuteEnd)(context, handle);
1423 throw;
1424 }
1425 }
1426
1427 static bool initialized_ = false;
1428
1429 void CYInitializeDynamic() {
1430 if (!initialized_)
1431 initialized_ = true;
1432 else return;
1433
1434 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1435
1436 JSClassDefinition definition;
1437
1438 definition = kJSClassDefinitionEmpty;
1439 definition.className = "All";
1440 definition.getProperty = &All_getProperty;
1441 definition.getPropertyNames = &All_getPropertyNames;
1442 All_ = JSClassCreate(&definition);
1443
1444 definition = kJSClassDefinitionEmpty;
1445 definition.className = "Context";
1446 definition.finalize = &CYFinalize;
1447 Context_ = JSClassCreate(&definition);
1448
1449 definition = kJSClassDefinitionEmpty;
1450 definition.className = "Functor";
1451 definition.staticFunctions = cy::Functor::StaticFunctions;
1452 definition.staticValues = Functor_staticValues;
1453 definition.callAsFunction = &Functor_callAsFunction;
1454 definition.finalize = &CYFinalize;
1455 Functor_ = JSClassCreate(&definition);
1456
1457 definition = kJSClassDefinitionEmpty;
1458 definition.className = "Pointer";
1459 definition.staticFunctions = Pointer_staticFunctions;
1460 definition.staticValues = Pointer_staticValues;
1461 definition.getProperty = &Pointer_getProperty;
1462 definition.setProperty = &Pointer_setProperty;
1463 definition.finalize = &CYFinalize;
1464 Pointer_ = JSClassCreate(&definition);
1465
1466 definition = kJSClassDefinitionEmpty;
1467 definition.className = "Struct";
1468 definition.staticFunctions = Struct_staticFunctions;
1469 definition.getProperty = &Struct_getProperty;
1470 definition.setProperty = &Struct_setProperty;
1471 definition.getPropertyNames = &Struct_getPropertyNames;
1472 definition.finalize = &CYFinalize;
1473 Struct_ = JSClassCreate(&definition);
1474
1475 definition = kJSClassDefinitionEmpty;
1476 definition.className = "Type";
1477 definition.staticValues = Type_staticValues;
1478 definition.staticFunctions = Type_staticFunctions;
1479 definition.callAsFunction = &Type_callAsFunction;
1480 definition.callAsConstructor = &Type_callAsConstructor;
1481 definition.finalize = &CYFinalize;
1482 Type_privateData::Class_ = JSClassCreate(&definition);
1483
1484 definition = kJSClassDefinitionEmpty;
1485 definition.className = "Global";
1486 //definition.getProperty = &Global_getProperty;
1487 Global_ = JSClassCreate(&definition);
1488
1489 Array_s = JSStringCreateWithUTF8CString("Array");
1490 cy_s = JSStringCreateWithUTF8CString("$cy");
1491 cyi_s = JSStringCreateWithUTF8CString("$cyi");
1492 length_s = JSStringCreateWithUTF8CString("length");
1493 message_s = JSStringCreateWithUTF8CString("message");
1494 name_s = JSStringCreateWithUTF8CString("name");
1495 pop_s = JSStringCreateWithUTF8CString("pop");
1496 prototype_s = JSStringCreateWithUTF8CString("prototype");
1497 push_s = JSStringCreateWithUTF8CString("push");
1498 splice_s = JSStringCreateWithUTF8CString("splice");
1499 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1500 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
1501 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
1502 toString_s = JSStringCreateWithUTF8CString("toString");
1503
1504 Result_ = JSStringCreateWithUTF8CString("_");
1505
1506 if (hooks_ != NULL && hooks_->Initialize != NULL)
1507 (*hooks_->Initialize)();
1508 }
1509
1510 void CYThrow(JSContextRef context, JSValueRef value) {
1511 if (value != NULL)
1512 throw CYJSError(context, value);
1513 }
1514
1515 const char *CYJSError::PoolCString(CYPool &pool) const {
1516 // XXX: this used to be CYPoolCString
1517 return CYPoolCCYON(pool, context_, value_);
1518 }
1519
1520 JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1521 // XXX: what if the context is different?
1522 return value_;
1523 }
1524
1525 JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1526 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1527 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1528 return _jsccall(JSObjectCallAsConstructor, context, Error, 1, arguments);
1529 }
1530
1531 JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1532 return CYCastJSError(context, message_);
1533 }
1534
1535 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1536 _assert(context != NULL);
1537
1538 CYPool pool;
1539
1540 va_list args;
1541 va_start(args, format);
1542 // XXX: there might be a beter way to think about this
1543 const char *message(pool.vsprintf(64, format, args));
1544 va_end(args);
1545
1546 value_ = CYCastJSError(context, message);
1547 }
1548
1549 JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1550 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1551 }
1552
1553 extern "C" bool CydgetMemoryParse(const uint16_t **data, size_t *size);
1554
1555 void *CYMapFile(const char *path, size_t *psize) {
1556 int fd;
1557 _syscall(fd = open(path, O_RDONLY));
1558
1559 struct stat stat;
1560 _syscall(fstat(fd, &stat));
1561 size_t size(stat.st_size);
1562
1563 *psize = size;
1564
1565 void *base;
1566 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
1567
1568 _syscall(close(fd));
1569 return base;
1570 }
1571
1572 static void CYRunSetups(JSContextRef context) {
1573 std::string folder("/etc/cycript/setup.d");
1574 DIR *setups(opendir(folder.c_str()));
1575 if (setups == NULL)
1576 return;
1577
1578 for (;;) {
1579 dirent setup;
1580 dirent *result;
1581 _syscall(readdir_r(setups, &setup, &result));
1582
1583 if (result == NULL)
1584 break;
1585 _assert(result == &setup);
1586
1587 const char *name(setup.d_name);
1588 size_t length(strlen(name));
1589 if (length < 4)
1590 continue;
1591
1592 if (name[0] == '.')
1593 continue;
1594 if (memcmp(name + length - 3, ".cy", 3) != 0)
1595 continue;
1596
1597 std::string script(folder + "/" + name);
1598 CYUTF8String utf8;
1599 utf8.data = reinterpret_cast<char *>(CYMapFile(script.c_str(), &utf8.size));
1600
1601 CYPool pool;
1602 CYUTF16String utf16(CYPoolUTF16String(pool, utf8));
1603 munmap(const_cast<char *>(utf8.data), utf8.size);
1604
1605 // XXX: this should not be used
1606 CydgetMemoryParse(&utf16.data, &utf16.size);
1607
1608 CYExecute(context, pool, CYPoolUTF8String(pool, utf16));
1609 free(const_cast<uint16_t *>(utf16.data));
1610 }
1611
1612 _syscall(closedir(setups));
1613 }
1614
1615 static JSValueRef require(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1616 _assert(count == 1);
1617 CYPool pool;
1618
1619 Dl_info addr;
1620 _assert(dladdr(reinterpret_cast<void *>(&require), &addr) != 0);
1621 char *lib(pool.strdup(addr.dli_fname));
1622
1623 char *slash(strrchr(lib, '/'));
1624 _assert(slash != NULL);
1625 *slash = '\0';
1626
1627 CYJSString property("exports");
1628 JSObjectRef module;
1629
1630 const char *path(pool.strcat(lib, "/cycript/", CYPoolCString(pool, context, arguments[0]), ".cy", NULL));
1631 CYJSString key(path);
1632 JSObjectRef modules(CYGetCachedObject(context, CYJSString("modules")));
1633 JSValueRef cache(CYGetProperty(context, modules, key));
1634
1635 if (!JSValueIsUndefined(context, cache))
1636 module = CYCastJSObject(context, cache);
1637 else {
1638 CYUTF8String code;
1639 code.data = reinterpret_cast<char *>(CYMapFile(path, &code.size));
1640
1641 std::stringstream wrap;
1642 wrap << "(function (exports, require, module) { " << code << "\n});";
1643 code = CYPoolCode(pool, wrap.str().c_str());
1644
1645 JSValueRef value(_jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0));
1646 JSObjectRef function(CYCastJSObject(context, value));
1647
1648 module = JSObjectMake(context, NULL, NULL);
1649 JSObjectRef exports(JSObjectMake(context, NULL, NULL));
1650 CYSetProperty(context, module, property, exports);
1651
1652 JSValueRef arguments[3] = { exports, JSObjectMakeFunctionWithCallback(context, CYJSString("require"), &require), module };
1653 CYCallAsFunction(context, function, NULL, 3, arguments);
1654 CYSetProperty(context, modules, key, module);
1655 }
1656
1657 return CYGetProperty(context, module, property);
1658 } CYCatch(NULL) }
1659
1660 extern "C" void CYSetupContext(JSGlobalContextRef context) {
1661 CYInitializeDynamic();
1662
1663 JSObjectRef global(CYGetGlobalObject(context));
1664
1665 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1666 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1667
1668 /* Cache Globals {{{ */
1669 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1670 CYSetProperty(context, cy, CYJSString("Array"), Array);
1671
1672 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1673 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1674
1675 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1676 CYSetProperty(context, cy, CYJSString("Error"), Error);
1677
1678 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1679 CYSetProperty(context, cy, CYJSString("Function"), Function);
1680
1681 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1682 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1683
1684 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1685 CYSetProperty(context, cy, CYJSString("Object"), Object);
1686
1687 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1688 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1689
1690 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1691 CYSetProperty(context, cy, CYJSString("String"), String);
1692
1693 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1694 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
1695 /* }}} */
1696
1697 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1698 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1699
1700 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1701 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1702 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1703
1704 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1705 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1706 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1707
1708 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1709 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1710
1711 JSObjectRef modules(JSObjectMake(context, NULL, NULL));
1712 CYSetProperty(context, cy, CYJSString("modules"), modules);
1713
1714 JSObjectRef all(JSObjectMake(context, All_, NULL));
1715 CYSetProperty(context, cycript, CYJSString("all"), all);
1716
1717 JSObjectRef alls(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
1718 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1719
1720 if (true) {
1721 JSObjectRef last(NULL), curr(global);
1722
1723 goto next; for (JSValueRef next;;) {
1724 if (JSValueIsNull(context, next))
1725 break;
1726 last = curr;
1727 curr = CYCastJSObject(context, next);
1728 next:
1729 next = JSObjectGetPrototype(context, curr);
1730 }
1731
1732 JSObjectSetPrototype(context, last, all);
1733 }
1734
1735 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
1736
1737 JSObjectRef System(JSObjectMake(context, NULL, NULL));
1738 CYSetProperty(context, cy, CYJSString("System"), System);
1739
1740 CYSetProperty(context, all, CYJSString("require"), &require, kJSPropertyAttributeDontEnum);
1741
1742 CYSetProperty(context, global, CYJSString("system"), System);
1743 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1744 //CYSetProperty(context, System, CYJSString("global"), global);
1745 CYSetProperty(context, System, CYJSString("print"), &System_print);
1746
1747 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
1748 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
1749
1750 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1751 (*hooks_->SetupContext)(context);
1752
1753 CYArrayPush(context, alls, cycript);
1754
1755 CYRunSetups(context);
1756 }
1757
1758 JSGlobalContextRef CYGetJSContext() {
1759 CYInitializeDynamic();
1760
1761 static JSGlobalContextRef context_;
1762
1763 if (context_ == NULL) {
1764 context_ = JSGlobalContextCreate(Global_);
1765 CYSetupContext(context_);
1766 }
1767
1768 return context_;
1769 }