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