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