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