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