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