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