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