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