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