]> git.saurik.com Git - cycript.git/blame - Execute.cpp
Add a new ?gc to run GC without running a script.
[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
51b6165e
JF
345
346void CYGarbageCollect(JSContextRef context) {
9cad30fa 347 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
3fe16be7
JF
1148static JSValueRef Type_callAsFunction_functionWith(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1149 return Type_callAsFunction_$With(context, object, _this, count, arguments, sig::function_P, exception);
1150}
9a39f705 1151
85e90410
JF
1152static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1153 if (count != 0)
1154 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1155 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1156
1157 sig::Type type;
9cad30fa 1158 type.name = NULL;
9cad30fa 1159
02873b72
JF
1160 if (internal->type_->primitive == sig::char_P) {
1161 type.flags = internal->type_->flags;
1162 type.primitive = sig::string_P;
1163 type.data.data.type = NULL;
1164 type.data.data.size = 0;
1165 } else {
1166 type.flags = 0;
1167 type.primitive = sig::pointer_P;
1168 type.data.data.type = internal->type_;
1169 type.data.data.size = 0;
1170 }
9cad30fa
JF
1171
1172 return CYMakeType(context, &type);
55c6d6ab 1173} CYCatch(NULL) }
9cad30fa 1174
21d5f610
JF
1175static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1176 if (count != 1)
1177 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1178 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1179
1180 CYPool pool;
1181 const char *name(CYPoolCString(pool, context, arguments[0]));
1182
1183 sig::Type type(*internal->type_);
1184 type.name = name;
1185 return CYMakeType(context, &type);
55c6d6ab 1186} CYCatch(NULL) }
21d5f610 1187
9cad30fa 1188static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9cad30fa
JF
1189 if (count != 1)
1190 throw CYJSError(context, "incorrect number of arguments to type cast function");
1c3dd2c3
JF
1191 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1192
077756a4 1193 if (internal->type_->primitive == sig::function_P)
b48c91a5 1194 return CYMakeFunctor(context, arguments[0], internal->type_->data.signature);
077756a4 1195
9cad30fa
JF
1196 sig::Type *type(internal->type_);
1197 ffi_type *ffi(internal->GetFFI());
1198 // XXX: alignment?
1199 uint8_t value[ffi->size];
1200 CYPool pool;
b799113b 1201 CYPoolFFI(&pool, context, type, ffi, value, arguments[0]);
9cad30fa 1202 return CYFromFFI(context, type, ffi, value);
55c6d6ab 1203} CYCatch(NULL) }
9cad30fa
JF
1204
1205static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1206 if (count != 0)
767e8255 1207 throw CYJSError(context, "incorrect number of arguments to Type allocator");
9cad30fa
JF
1208 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1209
1210 sig::Type *type(internal->type_);
1211 size_t length;
1212
1213 if (type->primitive != sig::array_P)
1214 length = _not(size_t);
1215 else {
1216 length = type->data.data.size;
1217 type = type->data.data.type;
1218 }
1219
ae0a1432 1220 void *value(calloc(1, internal->GetFFI()->size));
9cad30fa 1221 return CYMakePointer(context, value, length, type, NULL, NULL);
55c6d6ab 1222} CYCatch(NULL) }
9cad30fa
JF
1223
1224static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1225 if (count != 2)
1226 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1227 CYPool pool;
67110a15
JF
1228 const char *encoding(CYPoolCString(pool, context, arguments[1]));
1229 sig::Signature signature;
1230 sig::Parse(pool, &signature, encoding, &Structor_);
1231 return CYMakeFunctor(context, arguments[0], signature);
55c6d6ab 1232} CYCatch(NULL) }
9cad30fa
JF
1233
1234static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1235 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1236 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
55c6d6ab 1237} CYCatch(NULL) }
9cad30fa
JF
1238
1239static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1240 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1241}
1242
1243static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1244 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1245 char string[32];
1246 sprintf(string, "%p", internal->value_);
1247 return CYCastJSValue(context, string);
55c6d6ab 1248} CYCatch(NULL) }
9cad30fa
JF
1249
1250static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1251 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1252 if (internal->length_ != _not(size_t)) {
3b1534c0 1253 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
9cad30fa
JF
1254 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1255 return CYCallAsFunction(context, toCYON, _this, count, arguments);
0d64cb32 1256 } else if (internal->type_->type_ == NULL) pointer: {
9cad30fa
JF
1257 char string[32];
1258 sprintf(string, "%p", internal->value_);
1259 return CYCastJSValue(context, string);
0d64cb32
JF
1260 } try {
1261 JSValueRef value(CYGetProperty(context, _this, cyi_s));
1262 if (JSValueIsUndefined(context, value))
1263 goto pointer;
1264 CYPool pool;
1265 return CYCastJSValue(context, pool.strcat("&", CYPoolCCYON(pool, context, value), NULL));
1266 } catch (const CYException &e) {
1267 goto pointer;
9cad30fa 1268 }
55c6d6ab 1269} CYCatch(NULL) }
9cad30fa 1270
9cea6cab
JF
1271static JSValueRef Pointer_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1272 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1273 return CYMakeType(context, internal->type_->type_);
1274} CYCatch(NULL) }
1275
62d94d32 1276static JSValueRef Functor_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
7d894647 1277 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
9a39f705 1278 return CYMakeType(context, &internal->signature_);
62d94d32 1279} CYCatch(NULL) }
7d894647 1280
62d94d32 1281static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
74e8c566
JF
1282 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1283 return CYCastJSValue(context, internal->GetFFI()->alignment);
62d94d32 1284} CYCatch(NULL) }
74e8c566 1285
62d94d32 1286static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
21d5f610
JF
1287 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1288 return CYCastJSValue(context, internal->type_->name);
62d94d32 1289} CYCatch(NULL) }
21d5f610 1290
62d94d32 1291static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
74e8c566
JF
1292 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1293 return CYCastJSValue(context, internal->GetFFI()->size);
62d94d32 1294} CYCatch(NULL) }
74e8c566 1295
9cad30fa
JF
1296static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1297 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1298 CYPool pool;
1299 const char *type(sig::Unparse(pool, internal->type_));
1300 return CYCastJSValue(context, CYJSString(type));
55c6d6ab 1301} CYCatch(NULL) }
9cad30fa
JF
1302
1303static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1304 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
9a39f705
JF
1305 CYLocalPool pool;
1306 std::ostringstream out;
1307 CYOptions options;
1308 CYOutput output(out, options);
1309 (new(pool) CYEncodedType(Decode(pool, internal->type_)))->Output(output, CYNoFlags);
1310 return CYCastJSValue(context, CYJSString(out.str().c_str()));
55c6d6ab 1311} CYCatch(NULL) }
9cad30fa
JF
1312
1313static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1314 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1315}
1316
1317static JSStaticFunction Pointer_staticFunctions[4] = {
1318 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1319 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1320 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1321 {NULL, NULL, 0}
1322};
1323
9cea6cab
JF
1324static JSStaticValue Pointer_staticValues[2] = {
1325 {"type", &Pointer_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1326 {NULL, NULL, NULL, 0}
1327};
1328
9cad30fa
JF
1329static JSStaticFunction Struct_staticFunctions[2] = {
1330 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1331 {NULL, NULL, 0}
1332};
1333
1334static JSStaticFunction Functor_staticFunctions[4] = {
1335 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1336 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1337 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1338 {NULL, NULL, 0}
1339};
1340
1341namespace cy {
1342 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1343}
1344
7d894647
JF
1345static JSStaticValue Functor_staticValues[2] = {
1346 {"type", &Functor_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1347 {NULL, NULL, NULL, 0}
1348};
1349
21d5f610 1350static JSStaticValue Type_staticValues[4] = {
74e8c566 1351 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1352 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
74e8c566
JF
1353 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1354 {NULL, NULL, NULL, 0}
1355};
1356
3fe16be7 1357static JSStaticFunction Type_staticFunctions[10] = {
85e90410 1358 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
3fe16be7 1359 {"blockWith", &Type_callAsFunction_blockWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
fbc17268 1360 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9a39f705 1361 {"functionWith", &Type_callAsFunction_functionWith, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
85e90410 1362 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1363 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9cad30fa
JF
1364 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1365 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1366 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1367 {NULL, NULL, 0}
1368};
1369
1370static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1371
1372void CYSetArgs(int argc, const char *argv[]) {
1373 JSContextRef context(CYGetJSContext());
1374 JSValueRef args[argc];
1375 for (int i(0); i != argc; ++i)
1376 args[i] = CYCastJSValue(context, argv[i]);
1377
1378 JSObjectRef array;
f1b5a47f
JF
1379 if (JSObjectMakeArray$ != NULL)
1380 array = _jsccall(*JSObjectMakeArray$, context, argc, args);
1381 else {
9cad30fa
JF
1382 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1383 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1384 array = CYCastJSObject(context, value);
1385 }
1386
1387 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1388 CYSetProperty(context, System, CYJSString("args"), array);
1389}
1390
1391JSObjectRef CYGetGlobalObject(JSContextRef context) {
1392 return JSContextGetGlobalObject(context);
1393}
1394
89d16b11 1395const char *CYExecute(JSContextRef context, CYPool &pool, CYUTF8String code) {
4ad7388f 1396 JSValueRef exception(NULL);
9cad30fa
JF
1397
1398 void *handle;
1399 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1400 handle = (*hooks_->ExecuteStart)(context);
1401 else
1402 handle = NULL;
1403
4ad7388f 1404 try {
9cad30fa 1405
4ad7388f 1406 JSValueRef result;
9cad30fa
JF
1407 try {
1408 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1409 } catch (const char *error) {
1410 return error;
1411 }
1412
9cc84a5a
JF
1413 if (exception != NULL) error:
1414 return CYPoolCString(pool, context, CYJSString(context, exception));
9cad30fa
JF
1415
1416 if (JSValueIsUndefined(context, result))
1417 return NULL;
1418
4ad7388f 1419 const char *json;
9cad30fa
JF
1420 try {
1421 json = CYPoolCCYON(pool, context, result, &exception);
1422 } catch (const char *error) {
1423 return error;
1424 }
1425
1426 if (exception != NULL)
1427 goto error;
1428
1429 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1430
9cad30fa 1431 return json;
4ad7388f
JF
1432
1433 } catch (...) {
1434 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1435 (*hooks_->ExecuteEnd)(context, handle);
1436 throw;
1437 }
9cad30fa
JF
1438}
1439
09eee478
JF
1440static bool initialized_ = false;
1441
9cad30fa 1442void CYInitializeDynamic() {
09eee478
JF
1443 if (!initialized_)
1444 initialized_ = true;
1445 else return;
1446
9cad30fa
JF
1447 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1448
1449 JSClassDefinition definition;
1450
1451 definition = kJSClassDefinitionEmpty;
1452 definition.className = "All";
1453 definition.getProperty = &All_getProperty;
26ef7a82 1454 definition.getPropertyNames = &All_getPropertyNames;
9cad30fa
JF
1455 All_ = JSClassCreate(&definition);
1456
1457 definition = kJSClassDefinitionEmpty;
1458 definition.className = "Context";
1459 definition.finalize = &CYFinalize;
1460 Context_ = JSClassCreate(&definition);
1461
1462 definition = kJSClassDefinitionEmpty;
1463 definition.className = "Functor";
1464 definition.staticFunctions = cy::Functor::StaticFunctions;
7d894647 1465 definition.staticValues = Functor_staticValues;
9cad30fa
JF
1466 definition.callAsFunction = &Functor_callAsFunction;
1467 definition.finalize = &CYFinalize;
1468 Functor_ = JSClassCreate(&definition);
1469
1470 definition = kJSClassDefinitionEmpty;
1471 definition.className = "Pointer";
1472 definition.staticFunctions = Pointer_staticFunctions;
9cea6cab 1473 definition.staticValues = Pointer_staticValues;
9cad30fa
JF
1474 definition.getProperty = &Pointer_getProperty;
1475 definition.setProperty = &Pointer_setProperty;
1476 definition.finalize = &CYFinalize;
1477 Pointer_ = JSClassCreate(&definition);
1478
1479 definition = kJSClassDefinitionEmpty;
1480 definition.className = "Struct";
1481 definition.staticFunctions = Struct_staticFunctions;
1482 definition.getProperty = &Struct_getProperty;
1483 definition.setProperty = &Struct_setProperty;
1484 definition.getPropertyNames = &Struct_getPropertyNames;
1485 definition.finalize = &CYFinalize;
1486 Struct_ = JSClassCreate(&definition);
1487
1488 definition = kJSClassDefinitionEmpty;
1489 definition.className = "Type";
74e8c566 1490 definition.staticValues = Type_staticValues;
9cad30fa 1491 definition.staticFunctions = Type_staticFunctions;
9cad30fa
JF
1492 definition.callAsFunction = &Type_callAsFunction;
1493 definition.callAsConstructor = &Type_callAsConstructor;
1494 definition.finalize = &CYFinalize;
1495 Type_privateData::Class_ = JSClassCreate(&definition);
1496
1497 definition = kJSClassDefinitionEmpty;
56a66df3 1498 definition.className = "Global";
9cad30fa
JF
1499 //definition.getProperty = &Global_getProperty;
1500 Global_ = JSClassCreate(&definition);
1501
1502 Array_s = JSStringCreateWithUTF8CString("Array");
1503 cy_s = JSStringCreateWithUTF8CString("$cy");
4dd55d2f 1504 cyi_s = JSStringCreateWithUTF8CString("$cyi");
9cad30fa
JF
1505 length_s = JSStringCreateWithUTF8CString("length");
1506 message_s = JSStringCreateWithUTF8CString("message");
1507 name_s = JSStringCreateWithUTF8CString("name");
1508 pop_s = JSStringCreateWithUTF8CString("pop");
1509 prototype_s = JSStringCreateWithUTF8CString("prototype");
1510 push_s = JSStringCreateWithUTF8CString("push");
1511 splice_s = JSStringCreateWithUTF8CString("splice");
1512 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1513 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
20ded97a 1514 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
4cb8aa43 1515 toString_s = JSStringCreateWithUTF8CString("toString");
9cad30fa
JF
1516
1517 Result_ = JSStringCreateWithUTF8CString("_");
1518
1519 if (hooks_ != NULL && hooks_->Initialize != NULL)
1520 (*hooks_->Initialize)();
1521}
1522
1523void CYThrow(JSContextRef context, JSValueRef value) {
1524 if (value != NULL)
1525 throw CYJSError(context, value);
1526}
1527
b799113b 1528const char *CYJSError::PoolCString(CYPool &pool) const {
9cad30fa
JF
1529 // XXX: this used to be CYPoolCString
1530 return CYPoolCCYON(pool, context_, value_);
1531}
1532
1533JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1534 // XXX: what if the context is different?
1535 return value_;
1536}
1537
1538JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1539 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
9cad30fa 1540 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
f1b5a47f 1541 return _jsccall(JSObjectCallAsConstructor, context, Error, 1, arguments);
9cad30fa
JF
1542}
1543
1544JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1545 return CYCastJSError(context, message_);
1546}
1547
1548CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1549 _assert(context != NULL);
1550
1551 CYPool pool;
1552
1553 va_list args;
1554 va_start(args, format);
0cbeddf8
JF
1555 // XXX: there might be a beter way to think about this
1556 const char *message(pool.vsprintf(64, format, args));
9cad30fa
JF
1557 va_end(args);
1558
1559 value_ = CYCastJSError(context, message);
1560}
1561
1562JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1563 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1564}
1565
d00dec14
JF
1566extern "C" bool CydgetMemoryParse(const uint16_t **data, size_t *size);
1567
1568void *CYMapFile(const char *path, size_t *psize) {
1569 int fd;
1570 _syscall(fd = open(path, O_RDONLY));
1571
1572 struct stat stat;
1573 _syscall(fstat(fd, &stat));
1574 size_t size(stat.st_size);
1575
1576 *psize = size;
1577
1578 void *base;
1579 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
1580
1581 _syscall(close(fd));
1582 return base;
1583}
1584
1585static void CYRunSetups(JSContextRef context) {
1586 std::string folder("/etc/cycript/setup.d");
1587 DIR *setups(opendir(folder.c_str()));
1588 if (setups == NULL)
1589 return;
1590
1591 for (;;) {
1592 dirent setup;
1593 dirent *result;
1594 _syscall(readdir_r(setups, &setup, &result));
1595
1596 if (result == NULL)
1597 break;
1598 _assert(result == &setup);
1599
1600 const char *name(setup.d_name);
1601 size_t length(strlen(name));
1602 if (length < 4)
1603 continue;
1604
1605 if (name[0] == '.')
1606 continue;
1607 if (memcmp(name + length - 3, ".cy", 3) != 0)
1608 continue;
1609
1610 std::string script(folder + "/" + name);
1611 CYUTF8String utf8;
1612 utf8.data = reinterpret_cast<char *>(CYMapFile(script.c_str(), &utf8.size));
1613
1614 CYPool pool;
1615 CYUTF16String utf16(CYPoolUTF16String(pool, utf8));
1616 munmap(const_cast<char *>(utf8.data), utf8.size);
1617
bf76f580
JF
1618 // XXX: this should not be used
1619 CydgetMemoryParse(&utf16.data, &utf16.size);
1620
1621 CYExecute(context, pool, CYPoolUTF8String(pool, utf16));
d00dec14
JF
1622 free(const_cast<uint16_t *>(utf16.data));
1623 }
1624
1625 _syscall(closedir(setups));
1626}
1627
c6bf437d
JF
1628static JSValueRef require(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1629 _assert(count == 1);
1630 CYPool pool;
1631
1632 Dl_info addr;
1633 _assert(dladdr(reinterpret_cast<void *>(&require), &addr) != 0);
1634 char *lib(pool.strdup(addr.dli_fname));
1635
1636 char *slash(strrchr(lib, '/'));
1637 _assert(slash != NULL);
1638 *slash = '\0';
1639
1640 CYJSString property("exports");
1641 JSObjectRef module;
1642
1643 const char *path(pool.strcat(lib, "/cycript/", CYPoolCString(pool, context, arguments[0]), ".cy", NULL));
1644 CYJSString key(path);
1645 JSObjectRef modules(CYGetCachedObject(context, CYJSString("modules")));
1646 JSValueRef cache(CYGetProperty(context, modules, key));
1647
1648 if (!JSValueIsUndefined(context, cache))
1649 module = CYCastJSObject(context, cache);
1650 else {
1651 CYUTF8String code;
1652 code.data = reinterpret_cast<char *>(CYMapFile(path, &code.size));
1653
1654 std::stringstream wrap;
1655 wrap << "(function (exports, require, module) { " << code << "\n});";
1656 code = CYPoolCode(pool, wrap.str().c_str());
1657
1658 JSValueRef value(_jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0));
1659 JSObjectRef function(CYCastJSObject(context, value));
1660
1661 module = JSObjectMake(context, NULL, NULL);
1662 JSObjectRef exports(JSObjectMake(context, NULL, NULL));
1663 CYSetProperty(context, module, property, exports);
1664
1665 JSValueRef arguments[3] = { exports, JSObjectMakeFunctionWithCallback(context, CYJSString("require"), &require), module };
1666 CYCallAsFunction(context, function, NULL, 3, arguments);
1667 CYSetProperty(context, modules, key, module);
1668 }
1669
1670 return CYGetProperty(context, module, property);
1671} CYCatch(NULL) }
1672
9cad30fa
JF
1673extern "C" void CYSetupContext(JSGlobalContextRef context) {
1674 CYInitializeDynamic();
1675
1676 JSObjectRef global(CYGetGlobalObject(context));
1677
1678 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1679 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1680
1681/* Cache Globals {{{ */
1682 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1683 CYSetProperty(context, cy, CYJSString("Array"), Array);
1684
1685 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1686 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1687
1688 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1689 CYSetProperty(context, cy, CYJSString("Error"), Error);
1690
1691 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1692 CYSetProperty(context, cy, CYJSString("Function"), Function);
1693
1694 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1695 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1696
1697 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1698 CYSetProperty(context, cy, CYJSString("Object"), Object);
1699
1700 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1701 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1702
1703 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1704 CYSetProperty(context, cy, CYJSString("String"), String);
4cb8aa43
JF
1705
1706 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1707 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
9cad30fa
JF
1708/* }}} */
1709
1710 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
4cb8aa43 1711 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1712
1713 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1714 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1715 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1716
1717 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1718 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1719 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1720
1721 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
b63701b2 1722 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
9cad30fa 1723
c6bf437d
JF
1724 JSObjectRef modules(JSObjectMake(context, NULL, NULL));
1725 CYSetProperty(context, cy, CYJSString("modules"), modules);
1726
9cad30fa
JF
1727 JSObjectRef all(JSObjectMake(context, All_, NULL));
1728 CYSetProperty(context, cycript, CYJSString("all"), all);
1729
f1b5a47f 1730 JSObjectRef alls(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
26ef7a82
JF
1731 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1732
56a66df3
JF
1733 if (true) {
1734 JSObjectRef last(NULL), curr(global);
9cad30fa 1735
56a66df3
JF
1736 goto next; for (JSValueRef next;;) {
1737 if (JSValueIsNull(context, next))
1738 break;
1739 last = curr;
1740 curr = CYCastJSObject(context, next);
1741 next:
1742 next = JSObjectGetPrototype(context, curr);
1743 }
9cad30fa 1744
56a66df3
JF
1745 JSObjectSetPrototype(context, last, all);
1746 }
9cad30fa 1747
56a66df3 1748 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1749
1750 JSObjectRef System(JSObjectMake(context, NULL, NULL));
cdc80ff2 1751 CYSetProperty(context, cy, CYJSString("System"), System);
9cad30fa 1752
c6bf437d
JF
1753 CYSetProperty(context, all, CYJSString("require"), &require, kJSPropertyAttributeDontEnum);
1754
9cad30fa
JF
1755 CYSetProperty(context, global, CYJSString("system"), System);
1756 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1757 //CYSetProperty(context, System, CYJSString("global"), global);
1758 CYSetProperty(context, System, CYJSString("print"), &System_print);
1759
a621ae76
JF
1760 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
1761 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
1762
9cad30fa
JF
1763 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1764 (*hooks_->SetupContext)(context);
26ef7a82
JF
1765
1766 CYArrayPush(context, alls, cycript);
d00dec14
JF
1767
1768 CYRunSetups(context);
9cad30fa
JF
1769}
1770
8fab8594
JF
1771static JSGlobalContextRef context_;
1772
9cad30fa
JF
1773JSGlobalContextRef CYGetJSContext() {
1774 CYInitializeDynamic();
1775
9cad30fa
JF
1776 if (context_ == NULL) {
1777 context_ = JSGlobalContextCreate(Global_);
1778 CYSetupContext(context_);
1779 }
1780
1781 return context_;
1782}
8fab8594
JF
1783
1784void CYDestroyContext() {
1785 if (context_ == NULL)
1786 return;
1787 JSGlobalContextRelease(context_);
1788 context_ = NULL;
1789}