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