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