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