]> git.saurik.com Git - cycript.git/blob - Execute.cpp
5669730ddb35c6ae2751a9cd3da3c8d765b2b923
[cycript.git] / Execute.cpp
1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 #include "cycript.hpp"
23
24 #include <iostream>
25 #include <set>
26 #include <map>
27 #include <iomanip>
28 #include <sstream>
29 #include <cmath>
30
31 #include <dlfcn.h>
32 #include <dirent.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include <sys/mman.h>
37 #include <sys/stat.h>
38
39 #include <sqlite3.h>
40
41 #include "sig/parse.hpp"
42 #include "sig/ffi_type.hpp"
43
44 #include "Bridge.hpp"
45 #include "Code.hpp"
46 #include "Decode.hpp"
47 #include "Error.hpp"
48 #include "Execute.hpp"
49 #include "Internal.hpp"
50 #include "JavaScript.hpp"
51 #include "Pooling.hpp"
52 #include "String.hpp"
53
54 const char *sqlite3_column_string(sqlite3_stmt *stmt, int n) {
55 return reinterpret_cast<const char *>(sqlite3_column_text(stmt, n));
56 }
57
58 char *sqlite3_column_pooled(CYPool &pool, sqlite3_stmt *stmt, int n) {
59 if (const char *value = sqlite3_column_string(stmt, n))
60 return pool.strdup(value);
61 else return NULL;
62 }
63
64 static std::vector<CYHook *> &GetHooks() {
65 static std::vector<CYHook *> hooks;
66 return hooks;
67 }
68
69 CYRegisterHook::CYRegisterHook(CYHook *hook) {
70 GetHooks().push_back(hook);
71 }
72
73 /* JavaScript Properties {{{ */
74 bool CYHasProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
75 return JSObjectHasProperty(context, object, name);
76 }
77
78 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
79 return _jsccall(JSObjectGetPropertyAtIndex, context, object, index);
80 }
81
82 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
83 return _jsccall(JSObjectGetProperty, context, object, name);
84 }
85
86 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
87 _jsccall(JSObjectSetPropertyAtIndex, context, object, index, value);
88 }
89
90 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
91 _jsccall(JSObjectSetProperty, context, object, name, value, attributes);
92 }
93
94 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
95 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
96 }
97
98 JSObjectRef CYGetPrototype(JSContextRef context, JSObjectRef object) {
99 return CYCastJSObject(context, JSObjectGetPrototype(context, object));
100 }
101
102 void CYSetPrototype(JSContextRef context, JSObjectRef object, JSValueRef value) {
103 _assert(!JSValueIsUndefined(context, value));
104 JSObjectSetPrototype(context, object, value);
105 _assert(CYIsStrictEqual(context, JSObjectGetPrototype(context, object), value));
106 }
107 /* }}} */
108 /* JavaScript Strings {{{ */
109 JSStringRef CYCopyJSString(const char *value) {
110 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
111 }
112
113 JSStringRef CYCopyJSString(JSStringRef value) {
114 return value == NULL ? NULL : JSStringRetain(value);
115 }
116
117 JSStringRef CYCopyJSString(CYUTF8String value) {
118 if (memchr(value.data, '\0', value.size) != NULL) {
119 CYPool pool;
120 return CYCopyJSString(CYPoolUTF16String(pool, value));
121 } else if (value.data[value.size] != '\0') {
122 CYPool pool;
123 return CYCopyJSString(pool.strmemdup(value.data, value.size));
124 } else {
125 return CYCopyJSString(value.data);
126 }
127 }
128
129 JSStringRef CYCopyJSString(const std::string &value) {
130 return CYCopyJSString(CYUTF8String(value.c_str(), value.size()));
131 }
132
133 JSStringRef CYCopyJSString(CYUTF16String value) {
134 return JSStringCreateWithCharacters(value.data, value.size);
135 }
136
137 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
138 if (JSValueIsNull(context, value))
139 return NULL;
140 return _jsccall(JSValueToStringCopy, context, value);
141 }
142
143 CYUTF16String CYCastUTF16String(JSStringRef value) {
144 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
145 }
146
147 const char *CYPoolCString(CYPool &pool, CYUTF8String utf8) {
148 return pool.strndup(utf8.data, utf8.size);
149 }
150
151 CYUTF8String CYPoolUTF8String(CYPool &pool, CYUTF8String utf8) {
152 return {pool.strndup(utf8.data, utf8.size), utf8.size};
153 }
154
155 _visible CYUTF8String CYPoolUTF8String(CYPool &pool, const std::string &value) {
156 return {pool.strndup(value.data(), value.size()), value.size()};
157 }
158
159 CYUTF8String CYPoolUTF8String(CYPool &pool, JSContextRef context, JSStringRef value) {
160 return CYPoolUTF8String(pool, CYCastUTF16String(value));
161 }
162
163 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSStringRef value) {
164 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
165 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
166 return utf8.data;
167 }
168
169 const char *CYPoolCString(CYPool &pool, JSContextRef context, JSValueRef value) {
170 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
171 }
172 /* }}} */
173 /* Index Offsets {{{ */
174 size_t CYGetIndex(CYPool &pool, JSContextRef context, JSStringRef value) {
175 return CYGetIndex(CYPoolUTF8String(pool, context, value));
176 }
177 /* }}} */
178
179 static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
180
181 JSObjectRef CYObjectMakeArray(JSContextRef context, size_t length, const JSValueRef values[]) {
182 if (JSObjectMakeArray$ != NULL)
183 return _jsccall(*JSObjectMakeArray$, context, length, values);
184 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
185 bool wat(length == 1 && JSValueGetType(context, values[0]) == kJSTypeNumber);
186 JSValueRef value(CYCallAsFunction(context, Array, NULL, wat ? 0 : length, values));
187 JSObjectRef object(CYCastJSObject(context, value));
188 if (wat) CYArrayPush(context, object, 1, values);
189 return object;
190 }
191
192 static JSClassRef All_;
193 JSClassRef cy::Functor::Class_;
194 static JSClassRef Global_;
195
196 JSStringRef Array_s;
197 JSStringRef constructor_s;
198 JSStringRef cy_s;
199 JSStringRef cyi_s;
200 JSStringRef cyt_s;
201 JSStringRef length_s;
202 JSStringRef message_s;
203 JSStringRef name_s;
204 JSStringRef pop_s;
205 JSStringRef prototype_s;
206 JSStringRef push_s;
207 JSStringRef splice_s;
208 JSStringRef toCYON_s;
209 JSStringRef toJSON_s;
210 JSStringRef toPointer_s;
211 JSStringRef toString_s;
212 JSStringRef weak_s;
213
214 static sqlite3 *database_;
215
216 static JSStringRef Result_;
217
218 void CYFinalize(JSObjectRef object) {
219 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
220 if (internal == NULL)
221 return;
222 _assert(internal->count_ != _not(unsigned));
223 if (--internal->count_ == 0)
224 delete internal;
225 }
226
227 sig::Type *Structor_(CYPool &pool, sig::Aggregate *aggregate) {
228 //_assert(false);
229 return aggregate;
230 }
231
232 struct Context :
233 CYRoot
234 {
235 JSGlobalContextRef context_;
236
237 Context(JSGlobalContextRef context) :
238 context_(context)
239 {
240 }
241 };
242
243 struct CArray :
244 CYRoot
245 {
246 void *value_;
247 CYProtect owner_;
248 Type_privateData *type_;
249 size_t length_;
250
251 CArray(void *value, size_t length, const sig::Type &type, ffi_type *ffi, JSContextRef context, JSObjectRef owner) :
252 value_(value),
253 owner_(context, owner),
254 type_(new(*pool_) Type_privateData(type, ffi)),
255 length_(length)
256 {
257 }
258 };
259
260 struct CString :
261 CYRoot
262 {
263 char *value_;
264 CYProtect owner_;
265
266 CString(char *value, JSContextRef context, JSObjectRef owner) :
267 value_(value),
268 owner_(context, owner)
269 {
270 }
271 };
272
273 struct Pointer :
274 CYRoot
275 {
276 void *value_;
277 CYProtect owner_;
278 Type_privateData *type_;
279
280 Pointer(void *value, const sig::Type &type, JSContextRef context, JSObjectRef owner) :
281 value_(value),
282 owner_(context, owner),
283 type_(new(*pool_) Type_privateData(type))
284 {
285 }
286
287 Pointer(void *value, const char *encoding, JSContextRef context, JSObjectRef owner) :
288 value_(value),
289 owner_(context, owner),
290 type_(new(*pool_) Type_privateData(encoding))
291 {
292 }
293 };
294
295 struct Struct_privateData :
296 CYRoot
297 {
298 void *value_;
299 CYProtect owner_;
300 Type_privateData *type_;
301
302 Struct_privateData(void *value, const sig::Type &type, ffi_type *ffi, JSContextRef context, JSObjectRef owner) :
303 value_(value),
304 owner_(context, owner),
305 type_(new(*pool_) Type_privateData(type, ffi))
306 {
307 if (owner == NULL) {
308 size_t size(ffi->size);
309 void *copy(pool_->malloc<void>(size, ffi->alignment));
310 memcpy(copy, value_, size);
311 value_ = copy;
312 }
313 }
314 };
315
316 static void *CYCastSymbol(const char *name) {
317 for (CYHook *hook : GetHooks())
318 if (hook->CastSymbol != NULL)
319 if (void *value = (*hook->CastSymbol)(name))
320 return value;
321 return dlsym(RTLD_DEFAULT, name);
322 }
323
324 JSValueRef CYCastJSValue(JSContextRef context, bool value) {
325 return JSValueMakeBoolean(context, value);
326 }
327
328 JSValueRef CYCastJSValue(JSContextRef context, double value) {
329 return JSValueMakeNumber(context, value);
330 }
331
332 #define CYCastJSValue_(Type_) \
333 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
334 _assert(static_cast<Type_>(static_cast<double>(value)) == value); \
335 return JSValueMakeNumber(context, static_cast<double>(value)); \
336 }
337
338 CYCastJSValue_(long double)
339 CYCastJSValue_(signed short int)
340 CYCastJSValue_(unsigned short int)
341 CYCastJSValue_(signed int)
342 CYCastJSValue_(unsigned int)
343 CYCastJSValue_(signed long int)
344 CYCastJSValue_(unsigned long int)
345 CYCastJSValue_(signed long long int)
346 CYCastJSValue_(unsigned long long int)
347
348 #ifdef __SIZEOF_INT128__
349 CYCastJSValue_(signed __int128)
350 CYCastJSValue_(unsigned __int128)
351 #endif
352
353 JSValueRef CYJSUndefined(JSContextRef context) {
354 return JSValueMakeUndefined(context);
355 }
356
357 double CYCastDouble(JSContextRef context, JSValueRef value) {
358 return _jsccall(JSValueToNumber, context, value);
359 }
360
361 bool CYCastBool(JSContextRef context, JSValueRef value) {
362 return JSValueToBoolean(context, value);
363 }
364
365 JSValueRef CYJSNull(JSContextRef context) {
366 return JSValueMakeNull(context);
367 }
368
369 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
370 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
371 }
372
373 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
374 return CYCastJSValue(context, CYJSString(value));
375 }
376
377 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
378 return _jsccall(JSValueToObject, context, value);
379 }
380
381 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
382 return _jsccall(JSObjectCallAsFunction, context, function, _this, count, arguments);
383 }
384
385 bool CYIsCallable(JSContextRef context, JSValueRef value) {
386 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
387 }
388
389 bool CYIsEqual(JSContextRef context, JSValueRef lhs, JSValueRef rhs) {
390 return _jsccall(JSValueIsEqual, context, lhs, rhs);
391 }
392
393 bool CYIsStrictEqual(JSContextRef context, JSValueRef lhs, JSValueRef rhs) {
394 return JSValueIsStrictEqual(context, lhs, rhs);
395 }
396
397 size_t CYArrayLength(JSContextRef context, JSObjectRef array) {
398 return CYCastDouble(context, CYGetProperty(context, array, length_s));
399 }
400
401 JSValueRef CYArrayGet(JSContextRef context, JSObjectRef array, size_t index) {
402 return _jsccall(JSObjectGetPropertyAtIndex, context, array, index);
403 }
404
405 void CYArrayPush(JSContextRef context, JSObjectRef array, size_t length, const JSValueRef arguments[]) {
406 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
407 _jsccall(JSObjectCallAsFunction, context, CYCastJSObject(context, CYGetProperty(context, Array, push_s)), array, length, arguments);
408 }
409
410 void CYArrayPush(JSContextRef context, JSObjectRef array, JSValueRef value) {
411 return CYArrayPush(context, array, 1, &value);
412 }
413
414 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
415 FILE *file(stdout);
416
417 if (count == 0)
418 fputc('\n', file);
419 else {
420 CYPool pool;
421 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
422 fwrite(string.data, string.size, 1, file);
423 }
424
425 fflush(file);
426 return CYJSUndefined(context);
427 } CYCatch(NULL) }
428
429 static JSValueRef Global_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
430 FILE *file(stdout);
431 CYPool pool;
432
433 for (size_t i(0); i != count; ++i) {
434 if (i != 0)
435 fputc(' ', file);
436 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, arguments[i])));
437 fwrite(string.data, string.size, 1, file);
438 }
439
440 fputc('\n', file);
441 fflush(file);
442 return CYJSUndefined(context);
443 } CYCatch(NULL) }
444
445 static void (*JSSynchronousGarbageCollectForDebugging$)(JSContextRef);
446
447 _visible void CYGarbageCollect(JSContextRef context) {
448 (JSSynchronousGarbageCollectForDebugging$ ?: &JSGarbageCollect)(context);
449 }
450
451 static JSValueRef Cycript_compile_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
452 CYPool pool;
453 CYUTF8String before(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
454 CYUTF8String after(CYPoolCode(pool, before));
455 return CYCastJSValue(context, CYJSString(after));
456 } CYCatch_(NULL, "SyntaxError") }
457
458 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
459 CYGarbageCollect(context);
460 return CYJSUndefined(context);
461 } CYCatch(NULL) }
462
463 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> &objects, JSValueRef *exception) { CYTry {
464 switch (JSType type = JSValueGetType(context, value)) {
465 case kJSTypeUndefined:
466 return "undefined";
467 case kJSTypeNull:
468 return "null";
469 case kJSTypeBoolean:
470 return CYCastBool(context, value) ? "true" : "false";
471
472 case kJSTypeNumber: {
473 std::ostringstream str;
474 CYNumerify(str, CYCastDouble(context, value));
475 std::string value(str.str());
476 return pool.strmemdup(value.c_str(), value.size());
477 } break;
478
479 case kJSTypeString: {
480 std::ostringstream str;
481 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
482 CYStringify(str, string.data, string.size, CYStringifyModeCycript);
483 std::string value(str.str());
484 return pool.strmemdup(value.c_str(), value.size());
485 } break;
486
487 case kJSTypeObject:
488 return CYPoolCCYON(pool, context, (JSObjectRef) value, objects);
489 default:
490 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
491 }
492 } CYCatch(NULL) }
493
494 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> &objects) {
495 return _jsccall(CYPoolCCYON, pool, context, value, objects);
496 }
497
498 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, std::set<void *> *objects) {
499 if (objects != NULL)
500 return CYPoolCCYON(pool, context, value, *objects);
501 else {
502 std::set<void *> objects;
503 return CYPoolCCYON(pool, context, value, objects);
504 }
505 }
506
507 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSObjectRef object, std::set<void *> &objects) {
508 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
509 if (CYIsCallable(context, toCYON)) {
510 // XXX: this needs to be abstracted behind some kind of function
511 JSValueRef arguments[1] = {CYCastJSValue(context, reinterpret_cast<uintptr_t>(&objects))};
512 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 1, arguments));
513 _assert(value != NULL);
514 return CYPoolCString(pool, context, value);
515 }
516
517 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
518 if (CYIsCallable(context, toJSON)) {
519 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
520 return _jsccall(CYPoolCCYON, pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), objects);
521 }
522
523 if (JSObjectIsFunction(context, object)) {
524 JSValueRef toString(CYGetProperty(context, object, toString_s));
525 if (CYIsCallable(context, toString)) {
526 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
527 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
528 _assert(value != NULL);
529 return CYPoolCString(pool, context, value);
530 }
531 }
532
533 _assert(objects.insert(object).second);
534
535 std::ostringstream str;
536
537 JSValueRef value(CYGetProperty(context, object, constructor_s));
538 if (JSValueIsObject(context, value)) {
539 JSObjectRef constructor(CYCastJSObject(context, value));
540 JSValueRef theory(CYGetProperty(context, constructor, prototype_s));
541 JSValueRef practice(JSObjectGetPrototype(context, object));
542
543 if (CYIsStrictEqual(context, theory, practice)) {
544 JSValueRef name(CYGetProperty(context, constructor, name_s));
545 if (!JSValueIsUndefined(context, name)) {
546 auto utf8(CYPoolUTF8String(pool, context, CYJSString(context, name)));
547 if (utf8 != "Object")
548 str << "new" << ' ' << utf8;
549 }
550 }
551 }
552
553 str << '{';
554
555 // XXX: this is, sadly, going to leak
556 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
557
558 bool comma(false);
559
560 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
561 if (comma)
562 str << ',';
563 else
564 comma = true;
565
566 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
567 CYUTF8String string(CYPoolUTF8String(pool, context, name));
568
569 if (CYIsKey(string))
570 str << string.data;
571 else
572 CYStringify(str, string.data, string.size, CYStringifyModeLegacy);
573
574 str << ':';
575
576 try {
577 JSValueRef value(CYGetProperty(context, object, name));
578 str << CYPoolCCYON(pool, context, value, objects);
579 } catch (const CYException &error) {
580 str << "@error";
581 }
582 }
583
584 JSPropertyNameArrayRelease(names);
585
586 str << '}';
587
588 std::string string(str.str());
589 return pool.strmemdup(string.c_str(), string.size());
590 }
591
592 std::set<void *> *CYCastObjects(JSContextRef context, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
593 if (count == 0)
594 return NULL;
595 return CYCastPointer<std::set<void *> *>(context, arguments[0]);
596 }
597
598 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
599 std::set<void *> *objects(CYCastObjects(context, _this, count, arguments));
600 // XXX: this is horribly inefficient
601 std::set<void *> backup;
602 if (objects == NULL)
603 objects = &backup;
604
605 CYPool pool;
606 std::ostringstream str;
607
608 str << '[';
609
610 JSValueRef length(CYGetProperty(context, _this, length_s));
611 bool comma(false);
612
613 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
614 if (comma)
615 str << ',';
616 else
617 comma = true;
618
619 try {
620 JSValueRef value(CYGetProperty(context, _this, index));
621 if (!JSValueIsUndefined(context, value))
622 str << CYPoolCCYON(pool, context, value, *objects);
623 else {
624 str << ',';
625 comma = false;
626 }
627 } catch (const CYException &error) {
628 str << "@error";
629 }
630 }
631
632 str << ']';
633
634 std::string value(str.str());
635 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
636 } CYCatch(NULL) }
637
638 static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
639 CYPool pool;
640 std::ostringstream str;
641
642 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
643 CYStringify(str, string.data, string.size, CYStringifyModeCycript);
644
645 std::string value(str.str());
646 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
647 } CYCatch(NULL) }
648
649 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, const sig::Type &type, ffi_type *ffi, JSObjectRef owner) {
650 return CYPrivate<Pointer>::Make(context, pointer, type, context, owner);
651 }
652
653 static JSValueRef CYMakeFunctor(JSContextRef context, void (*function)(), bool variadic, const sig::Signature &signature) {
654 if (function == NULL)
655 return CYJSNull(context);
656 return JSObjectMake(context, cy::Functor::Class_, new cy::Functor(function, variadic, signature));
657 }
658
659 // XXX: remove this, as it is really stupid
660 static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *encoding) {
661 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
662 if (function == NULL)
663 return NULL;
664
665 cy::Functor *internal(new cy::Functor(function, encoding));
666 ++internal->count_;
667 return JSObjectMake(context, cy::Functor::Class_, internal);
668 }
669
670 bool CYGetOffset(CYPool &pool, JSContextRef context, JSStringRef value, ssize_t &index) {
671 return CYGetOffset(CYPoolCString(pool, context, value), index);
672 }
673
674 // XXX: this is a horrible back added for CFType
675 void *CYCastPointerEx_(JSContextRef context, JSObjectRef value) {
676 JSObjectRef object((JSObjectRef) value);
677 if (JSValueIsObjectOfClass(context, value, CYPrivate<Pointer>::Class_)) {
678 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
679 return internal->value_;
680 }
681
682 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
683 if (CYIsCallable(context, toPointer)) {
684 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
685 _assert(value != NULL);
686 return CYCastPointer_(context, value);
687 }
688
689 return NULL;
690 }
691
692 void *CYCastPointer_(JSContextRef context, JSValueRef value, bool *guess) {
693 if (value == NULL)
694 return NULL;
695 else switch (JSValueGetType(context, value)) {
696 case kJSTypeNull:
697 return NULL;
698 case kJSTypeObject: {
699 JSObjectRef object((JSObjectRef) value);
700 if (JSValueIsObjectOfClass(context, value, CYPrivate<Pointer>::Class_)) {
701 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
702 return internal->value_;
703 }
704 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
705 if (CYIsCallable(context, toPointer)) {
706 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
707 _assert(value != NULL);
708 return CYCastPointer_(context, value, guess);
709 }
710 } default:
711 if (guess != NULL)
712 *guess = true;
713 case kJSTypeNumber:
714 double number(CYCastDouble(context, value));
715 if (!std::isnan(number))
716 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
717 if (guess == NULL)
718 throw CYJSError(context, "cannot convert value to pointer");
719 else {
720 *guess = true;
721 return NULL;
722 }
723 }
724 }
725
726 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function);
727
728 namespace sig {
729
730 // XXX: this is somehow not quite a template :/
731
732 template <>
733 void Primitive<bool>::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
734 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
735 }
736
737 #define CYPoolFFI_(Type_) \
738 template <> \
739 void Primitive<Type_>::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const { \
740 *reinterpret_cast<Type_ *>(data) = CYCastDouble(context, value); \
741 }
742
743 CYPoolFFI_(wchar_t)
744 CYPoolFFI_(float)
745 CYPoolFFI_(double)
746 CYPoolFFI_(long double)
747
748 CYPoolFFI_(signed char)
749 CYPoolFFI_(signed int)
750 CYPoolFFI_(signed long int)
751 CYPoolFFI_(signed long long int)
752 CYPoolFFI_(signed short int)
753
754 CYPoolFFI_(unsigned char)
755 CYPoolFFI_(unsigned int)
756 CYPoolFFI_(unsigned long int)
757 CYPoolFFI_(unsigned long long int)
758 CYPoolFFI_(unsigned short int)
759
760 #ifdef __SIZEOF_INT128__
761 CYPoolFFI_(signed __int128)
762 CYPoolFFI_(unsigned __int128)
763 #endif
764
765 template <>
766 void Primitive<char>::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
767 if (JSValueGetType(context, value) != kJSTypeString)
768 *reinterpret_cast<char *>(data) = CYCastDouble(context, value);
769 else {
770 CYJSString script(context, value);
771 auto string(CYCastUTF16String(script));
772 _assert(string.size == 1);
773 _assert((string.data[0] & 0xff) == string.data[0]);
774 *reinterpret_cast<char *>(data) = string.data[0];
775 }
776 }
777
778 void Void::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
779 _assert(JSValueIsUndefined(context, value));
780 }
781
782 void Unknown::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
783 _assert(false);
784 }
785
786 void String::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
787 bool guess(false);
788 *reinterpret_cast<const char **>(data) = CYCastPointer<const char *>(context, value, &guess);
789 if (guess && pool != NULL)
790 *reinterpret_cast<const char **>(data) = CYPoolCString(*pool, context, value);
791 }
792
793 void Bits::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
794 _assert(false);
795 }
796
797 static void CYArrayCopy(CYPool *pool, JSContextRef context, uint8_t *base, size_t length, const sig::Type &type, ffi_type *ffi, JSObjectRef object) {
798 for (size_t index(0); index != length; ++index) {
799 JSValueRef rhs(CYGetProperty(context, object, index));
800 if (JSValueIsUndefined(context, rhs))
801 throw CYJSError(context, "unable to extract array value");
802 type.PoolFFI(pool, context, ffi, base, rhs);
803 base += ffi->size;
804 }
805 }
806
807 void Pointer::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
808 bool guess(false);
809 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value, &guess);
810 if (!guess || pool == NULL || !JSValueIsObject(context, value))
811 return;
812
813 JSObjectRef object(CYCastJSObject(context, value));
814
815 if (sig::Function *function = dynamic_cast<sig::Function *>(&type)) {
816 _assert(!function->variadic);
817 auto internal(CYMakeFunctor_(context, object, function->signature, &FunctionAdapter_));
818 // XXX: see notes in Library.cpp about needing to leak
819 *reinterpret_cast<void (**)()>(data) = internal->value_;
820 } else if (CYHasProperty(context, object, length_s)) {
821 size_t length(CYArrayLength(context, object));
822 ffi_type *element(type.GetFFI(*pool));
823 size_t size(element->size * length);
824 uint8_t *base(pool->malloc<uint8_t>(size, element->alignment));
825 CYArrayCopy(pool, context, base, length, type, element, object);
826 *reinterpret_cast<void **>(data) = base;
827 }
828 }
829
830 void Array::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
831 if (size == 0)
832 return;
833 uint8_t *base(reinterpret_cast<uint8_t *>(data));
834 CYArrayCopy(pool, context, base, size, type, ffi->elements[0], CYCastJSObject(context, value));
835 }
836
837 void Enum::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
838 return type.PoolFFI(pool, context, ffi, data, value);
839 }
840
841 void Aggregate::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
842 _assert(!overlap);
843 _assert(signature.count != _not(size_t));
844
845 size_t offset(0);
846 uint8_t *base(reinterpret_cast<uint8_t *>(data));
847 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
848 for (size_t index(0); index != signature.count; ++index) {
849 sig::Element *element(&signature.elements[index]);
850 ffi_type *field(ffi->elements[index]);
851
852 JSValueRef rhs;
853 if (aggregate == NULL)
854 rhs = value;
855 else {
856 rhs = CYGetProperty(context, aggregate, index);
857 if (JSValueIsUndefined(context, rhs)) {
858 if (element->name != NULL)
859 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
860 else
861 goto undefined;
862 if (JSValueIsUndefined(context, rhs)) undefined:
863 throw CYJSError(context, "unable to extract structure value");
864 }
865 }
866
867 element->type->PoolFFI(pool, context, field, base + offset, rhs);
868 offset += field->size;
869 CYAlign(offset, field->alignment);
870 }
871 }
872
873 void Function::PoolFFI(CYPool *pool, JSContextRef context, ffi_type *ffi, void *data, JSValueRef value) const {
874 _assert(false);
875 }
876
877 #define CYFromFFI_(Type_) \
878 template <> \
879 JSValueRef Primitive<Type_>::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const { \
880 JSValueRef value(CYCastJSValue(context, *reinterpret_cast<Type_ *>(data))); \
881 JSObjectRef typed(_jsccall(JSObjectCallAsConstructor, context, CYGetCachedObject(context, CYJSString("Number")), 1, &value)); \
882 CYSetProperty(context, typed, cyt_s, CYMakeType(context, *this), kJSPropertyAttributeDontEnum); \
883 return typed; \
884 }
885
886 CYFromFFI_(wchar_t)
887 CYFromFFI_(float)
888 CYFromFFI_(double)
889 CYFromFFI_(long double)
890
891 CYFromFFI_(signed char)
892 CYFromFFI_(signed int)
893 CYFromFFI_(signed long int)
894 CYFromFFI_(signed long long int)
895 CYFromFFI_(signed short int)
896
897 CYFromFFI_(unsigned char)
898 CYFromFFI_(unsigned int)
899 CYFromFFI_(unsigned long int)
900 CYFromFFI_(unsigned long long int)
901 CYFromFFI_(unsigned short int)
902
903 #ifdef __SIZEOF_INT128__
904 CYFromFFI_(signed __int128)
905 CYFromFFI_(unsigned __int128)
906 #endif
907
908 template <>
909 JSValueRef Primitive<bool>::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
910 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
911 }
912
913 template <>
914 JSValueRef Primitive<char>::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
915 uint16_t string(uint8_t(*reinterpret_cast<char *>(data)));
916 JSValueRef value(CYCastJSValue(context, CYJSString(CYUTF16String(&string, 1))));
917 JSObjectRef typed(_jsccall(JSObjectCallAsConstructor, context, CYGetCachedObject(context, CYJSString("String")), 1, &value));
918 CYSetProperty(context, typed, cyt_s, CYMakeType(context, sig::Primitive<char>()), kJSPropertyAttributeDontEnum);
919 CYSetPrototype(context, typed, CYGetCachedValue(context, CYJSString("Character_prototype")));
920 return typed;
921 }
922
923 JSValueRef Void::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
924 return CYJSUndefined(context);
925 }
926
927 JSValueRef Unknown::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
928 _assert(false);
929 }
930
931 JSValueRef String::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
932 if (char *value = *reinterpret_cast<char **>(data))
933 return CYPrivate<CString>::Make(context, value, context, owner);
934 return CYJSNull(context);
935 }
936
937 JSValueRef Bits::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
938 _assert(false);
939 }
940
941 JSValueRef Pointer::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
942 if (void *value = *reinterpret_cast<void **>(data))
943 return CYMakePointer(context, value, type, NULL, owner);
944 return CYJSNull(context);
945 }
946
947 JSValueRef Array::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
948 return CYPrivate<CArray>::Make(context, data, size, type, ffi->elements[0], context, owner);
949 }
950
951 JSValueRef Enum::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
952 return type.FromFFI(context, ffi, data, initialize, owner);
953 }
954
955 JSValueRef Aggregate::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
956 _assert(!overlap);
957 _assert(signature.count != _not(size_t));
958 return CYPrivate<Struct_privateData>::Make(context, data, *this, ffi, context, owner);
959 }
960
961 JSValueRef Function::FromFFI(JSContextRef context, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) const {
962 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(data), variadic, signature);
963 }
964
965 }
966
967 void CYExecuteClosure(ffi_cif *cif, void *result, void **arguments, void *arg) {
968 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
969
970 JSContextRef context(internal->function_);
971
972 size_t count(internal->cif_.nargs);
973 JSValueRef values[count];
974
975 for (size_t index(0); index != count; ++index)
976 values[index] = internal->signature_.elements[1 + index].type->FromFFI(context, internal->cif_.arg_types[index], arguments[index]);
977
978 JSValueRef value(internal->adapter_(context, count, values, internal->function_));
979 internal->signature_.elements[0].type->PoolFFI(NULL, context, internal->cif_.rtype, result, value);
980 }
981
982 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
983 return CYCallAsFunction(context, function, NULL, count, values);
984 }
985
986 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
987 static void CYFreeFunctor(void *data) {
988 ffi_closure_free(data);
989 }
990 #else
991 static void CYFreeFunctor(void *data) {
992 _syscall(munmap(data, sizeof(ffi_closure)));
993 }
994 #endif
995
996 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const sig::Signature &signature, JSValueRef (*adapter)(JSContextRef, size_t, JSValueRef[], JSObjectRef)) {
997 // XXX: in case of exceptions this will leak
998 Closure_privateData *internal(new Closure_privateData(context, function, adapter, signature));
999
1000 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
1001 void *executable;
1002 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
1003
1004 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, &CYExecuteClosure, internal, executable));
1005 _assert(status == FFI_OK);
1006
1007 internal->pool_->atexit(&CYFreeFunctor, writable);
1008 internal->value_ = reinterpret_cast<void (*)()>(executable);
1009 #else
1010 ffi_closure *closure((ffi_closure *) _syscall(mmap(
1011 NULL, sizeof(ffi_closure),
1012 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
1013 -1, 0
1014 )));
1015
1016 ffi_status status(ffi_prep_closure(closure, &internal->cif_, &CYExecuteClosure, internal));
1017 _assert(status == FFI_OK);
1018
1019 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
1020
1021 internal->pool_->atexit(&CYFreeFunctor, closure);
1022 internal->value_ = reinterpret_cast<void (*)()>(closure);
1023 #endif
1024
1025 return internal;
1026 }
1027
1028 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const sig::Signature &signature) {
1029 Closure_privateData *internal(CYMakeFunctor_(context, function, signature, &FunctionAdapter_));
1030 JSObjectRef object(JSObjectMake(context, cy::Functor::Class_, internal));
1031 // XXX: see above notes about needing to leak
1032 JSValueProtect(CYGetJSContext(context), object);
1033 return object;
1034 }
1035
1036 JSValueRef CYGetCachedValue(JSContextRef context, JSStringRef name) {
1037 return CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name);
1038 }
1039
1040 JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
1041 return CYCastJSObject(context, CYGetCachedValue(context, name));
1042 }
1043
1044 static JSValueRef CYMakeFunctor(JSContextRef context, JSValueRef value, bool variadic, const sig::Signature &signature) {
1045 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
1046
1047 bool function(_jsccall(JSValueIsInstanceOfConstructor, context, value, Function));
1048 if (function) {
1049 JSObjectRef function(CYCastJSObject(context, value));
1050 return CYMakeFunctor(context, function, signature);
1051 } else {
1052 void (*function)()(CYCastPointer<void (*)()>(context, value));
1053 return CYMakeFunctor(context, function, variadic, signature);
1054 }
1055 }
1056
1057 static JSValueRef CString_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1058 CYPool pool;
1059 CString *internal(reinterpret_cast<CString *>(JSObjectGetPrivate(object)));
1060
1061 ssize_t offset;
1062 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1063 offset = 0;
1064 else if (!CYGetOffset(pool, context, property, offset))
1065 return NULL;
1066
1067 sig::Primitive<char> type;
1068 return type.FromFFI(context, type.GetFFI(pool), internal->value_ + offset, false, NULL);
1069 } CYCatch(NULL) }
1070
1071 static bool CString_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1072 CYPool pool;
1073 CString *internal(reinterpret_cast<CString *>(JSObjectGetPrivate(object)));
1074
1075 ssize_t offset;
1076 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1077 offset = 0;
1078 else if (!CYGetOffset(pool, context, property, offset))
1079 return false;
1080
1081 sig::Primitive<char> type;
1082 type.PoolFFI(NULL, context, type.GetFFI(pool), internal->value_ + offset, value);
1083 return true;
1084 } CYCatch(false) }
1085
1086 static bool Index_(CYPool &pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
1087 Type_privateData *typical(internal->type_);
1088 sig::Aggregate *type(static_cast<sig::Aggregate *>(typical->type_));
1089 if (type == NULL)
1090 return false;
1091
1092 const char *name(CYPoolCString(pool, context, property));
1093 size_t length(strlen(name));
1094 double number(CYCastDouble(name, length));
1095
1096 size_t count(type->signature.count);
1097
1098 if (std::isnan(number)) {
1099 if (property == NULL)
1100 return false;
1101
1102 sig::Element *elements(type->signature.elements);
1103
1104 for (size_t local(0); local != count; ++local) {
1105 sig::Element *element(&elements[local]);
1106 if (element->name != NULL && strcmp(name, element->name) == 0) {
1107 index = local;
1108 goto base;
1109 }
1110 }
1111
1112 return false;
1113 } else {
1114 index = static_cast<ssize_t>(number);
1115 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
1116 return false;
1117 }
1118
1119 base:
1120 ffi_type **elements(typical->GetFFI()->elements);
1121
1122 size_t offset(0);
1123 for (ssize_t local(0); local != index; ++local) {
1124 offset += elements[local]->size;
1125 CYAlign(offset, elements[local + 1]->alignment);
1126 }
1127
1128 base = reinterpret_cast<uint8_t *>(internal->value_) + offset;
1129 return true;
1130 }
1131
1132 static void *Offset_(CYPool &pool, JSContextRef context, JSStringRef property, void *data, ffi_type *ffi) {
1133 ssize_t offset;
1134 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
1135 offset = 0;
1136 else if (!CYGetOffset(pool, context, property, offset))
1137 return NULL;
1138 return reinterpret_cast<uint8_t *>(data) + ffi->size * offset;
1139 }
1140
1141 static JSValueRef Offset_getProperty(CYPool &pool, JSContextRef context, JSStringRef property, void *data, Type_privateData *typical, JSObjectRef owner) {
1142 ffi_type *ffi(typical->GetFFI());
1143 void *base(Offset_(pool, context, property, data, ffi));
1144 if (base == NULL)
1145 return NULL;
1146 return typical->type_->FromFFI(context, ffi, base, false, owner);
1147 }
1148
1149 static bool Offset_setProperty(CYPool &pool, JSContextRef context, JSStringRef property, void *data, Type_privateData *typical, JSValueRef value) {
1150 ffi_type *ffi(typical->GetFFI());
1151 void *base(Offset_(pool, context, property, data, ffi));
1152 if (base == NULL)
1153 return false;
1154
1155 typical->type_->PoolFFI(NULL, context, ffi, base, value);
1156 return true;
1157 }
1158
1159 static JSValueRef CArray_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1160 CYPool pool;
1161 CArray *internal(reinterpret_cast<CArray *>(JSObjectGetPrivate(object)));
1162 if (JSStringIsEqual(property, length_s))
1163 return CYCastJSValue(context, internal->length_);
1164 Type_privateData *typical(internal->type_);
1165 JSObjectRef owner(internal->owner_ ?: object);
1166 return Offset_getProperty(pool, context, property, internal->value_, typical, owner);
1167 } CYCatch(NULL) }
1168
1169 static bool CArray_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1170 CYPool pool;
1171 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1172 Type_privateData *typical(internal->type_);
1173 return Offset_setProperty(pool, context, property, internal->value_, typical, value);
1174 } CYCatch(false) }
1175
1176 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1177 CYPool pool;
1178 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1179
1180 Type_privateData *typical(internal->type_);
1181
1182 if (sig::Function *function = dynamic_cast<sig::Function *>(typical->type_)) {
1183 if (!JSStringIsEqualToUTF8CString(property, "$cyi"))
1184 return NULL;
1185 return CYMakeFunctor(context, reinterpret_cast<void (*)()>(internal->value_), function->variadic, function->signature);
1186 }
1187
1188 JSObjectRef owner(internal->owner_ ?: object);
1189 return Offset_getProperty(pool, context, property, internal->value_, typical, owner);
1190 } CYCatch(NULL) }
1191
1192 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1193 CYPool pool;
1194 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
1195 Type_privateData *typical(internal->type_);
1196 return Offset_setProperty(pool, context, property, internal->value_, typical, value);
1197 } CYCatch(false) }
1198
1199 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1200 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
1201 Type_privateData *typical(internal->type_);
1202 return CYMakePointer(context, internal->value_, *typical->type_, typical->ffi_, _this);
1203 } CYCatch(NULL) }
1204
1205 static JSValueRef Struct_getProperty_$cyt(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1206 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1207 return CYMakeType(context, *internal->type_->type_);
1208 } CYCatch(NULL) }
1209
1210 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1211 CYPool pool;
1212 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1213 Type_privateData *typical(internal->type_);
1214 sig::Aggregate *type(static_cast<sig::Aggregate *>(typical->type_));
1215
1216 ssize_t index;
1217 uint8_t *base;
1218
1219 if (!Index_(pool, context, internal, property, index, base))
1220 return NULL;
1221
1222 JSObjectRef owner(internal->owner_ ?: object);
1223
1224 return type->signature.elements[index].type->FromFFI(context, typical->GetFFI()->elements[index], base, false, owner);
1225 } CYCatch(NULL) }
1226
1227 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
1228 CYPool pool;
1229 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1230 Type_privateData *typical(internal->type_);
1231 sig::Aggregate *type(static_cast<sig::Aggregate *>(typical->type_));
1232
1233 ssize_t index;
1234 uint8_t *base;
1235
1236 if (!Index_(pool, context, internal, property, index, base))
1237 return false;
1238
1239 type->signature.elements[index].type->PoolFFI(NULL, context, typical->GetFFI()->elements[index], base, value);
1240 return true;
1241 } CYCatch(false) }
1242
1243 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1244 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1245 Type_privateData *typical(internal->type_);
1246 sig::Aggregate *type(static_cast<sig::Aggregate *>(typical->type_));
1247
1248 if (type == NULL)
1249 return;
1250
1251 size_t count(type->signature.count);
1252 sig::Element *elements(type->signature.elements);
1253
1254 char number[32];
1255
1256 for (size_t index(0); index != count; ++index) {
1257 const char *name;
1258 name = elements[index].name;
1259
1260 if (name == NULL) {
1261 sprintf(number, "%zu", index);
1262 name = number;
1263 }
1264
1265 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1266 }
1267 }
1268
1269 static sig::Void Void_;
1270 static sig::Pointer PointerToVoid_(Void_);
1271
1272 static sig::Type *CYGetType(CYPool &pool, JSContextRef context, JSValueRef value) {
1273 if (JSValueIsNull(context, value))
1274 return &PointerToVoid_;
1275 JSObjectRef object(CYCastJSObject(context, value));
1276 JSObjectRef type(CYCastJSObject(context, CYGetProperty(context, object, cyt_s)));
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 #ifndef __ANDROID__
2129 _visible void CYCancel() {
2130 cancel_ = true;
2131 }
2132 #endif
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 length_s = JSStringCreateWithUTF8CString("length");
2238 message_s = JSStringCreateWithUTF8CString("message");
2239 name_s = JSStringCreateWithUTF8CString("name");
2240 pop_s = JSStringCreateWithUTF8CString("pop");
2241 prototype_s = JSStringCreateWithUTF8CString("prototype");
2242 push_s = JSStringCreateWithUTF8CString("push");
2243 splice_s = JSStringCreateWithUTF8CString("splice");
2244 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
2245 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
2246 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
2247 toString_s = JSStringCreateWithUTF8CString("toString");
2248 weak_s = JSStringCreateWithUTF8CString("weak");
2249
2250 Result_ = JSStringCreateWithUTF8CString("_");
2251
2252 for (CYHook *hook : GetHooks())
2253 if (hook->Initialize != NULL)
2254 (*hook->Initialize)();
2255 }
2256
2257 void CYThrow(JSContextRef context, JSValueRef value) {
2258 if (value != NULL)
2259 throw CYJSError(context, value);
2260 }
2261
2262 const char *CYJSError::PoolCString(CYPool &pool) const {
2263 std::set<void *> objects;
2264 // XXX: this used to be CYPoolCString
2265 return CYPoolCCYON(pool, context_, value_, objects);
2266 }
2267
2268 JSValueRef CYJSError::CastJSValue(JSContextRef context, const char *name) const {
2269 // XXX: what if the context is different? or the name? I dunno. ("epic" :/)
2270 return value_;
2271 }
2272
2273 JSValueRef CYCastJSError(JSContextRef context, const char *name, const char *message) {
2274 JSObjectRef Error(CYGetCachedObject(context, CYJSString(name)));
2275 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
2276 return _jsccall(JSObjectCallAsConstructor, context, Error, 1, arguments);
2277 }
2278
2279 JSValueRef CYPoolError::CastJSValue(JSContextRef context, const char *name) const {
2280 return CYCastJSError(context, name, message_);
2281 }
2282
2283 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
2284 _assert(context != NULL);
2285
2286 CYPool pool;
2287
2288 va_list args;
2289 va_start(args, format);
2290 // XXX: there might be a beter way to think about this
2291 const char *message(pool.vsprintf(64, format, args));
2292 va_end(args);
2293
2294 value_ = CYCastJSError(context, "Error", message);
2295 }
2296
2297 JSGlobalContextRef CYGetJSContext(JSContextRef context) {
2298 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
2299 }
2300
2301 #ifdef __ANDROID__
2302 char *CYPoolLibraryPath_(CYPool &pool) {
2303 FILE *maps(fopen("/proc/self/maps", "r"));
2304 struct F { FILE *f; F(FILE *f) : f(f) {}
2305 ~F() { fclose(f); } } f(maps);
2306
2307 size_t function(reinterpret_cast<size_t>(&CYPoolLibraryPath));
2308
2309 for (;;) {
2310 size_t start; size_t end; char flags[8]; unsigned long long offset;
2311 int major; int minor; unsigned long long inode; char file[1024];
2312 int count(fscanf(maps, "%zx-%zx %7s %llx %x:%x %llu%[ ]%1024[^\n]\n",
2313 &start, &end, flags, &offset, &major, &minor, &inode, file, file));
2314 if (count < 8) break; else if (start <= function && function < end)
2315 return pool.strdup(file);
2316 }
2317
2318 _assert(false);
2319 }
2320 #else
2321 char *CYPoolLibraryPath_(CYPool &pool) {
2322 Dl_info addr;
2323 _assert(dladdr(reinterpret_cast<void *>(&CYPoolLibraryPath), &addr) != 0);
2324 return pool.strdup(addr.dli_fname);
2325 }
2326 #endif
2327
2328 const char *CYPoolLibraryPath(CYPool &pool) {
2329 char *lib(CYPoolLibraryPath_(pool));
2330
2331 char *slash(strrchr(lib, '/'));
2332 if (slash == NULL)
2333 return ".";
2334 *slash = '\0';
2335
2336 slash = strrchr(lib, '/');
2337 if (slash != NULL) {
2338 if (strcmp(slash, "/.libs") == 0)
2339 *slash = '\0';
2340 } else if (strcmp(lib, ".libs") == 0)
2341 return ".";
2342
2343 return lib;
2344 }
2345
2346 static JSValueRef require_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
2347 _assert(count == 1);
2348 CYPool pool;
2349
2350 CYUTF8String name(CYPoolUTF8String(pool, context, CYJSString(context, arguments[0])));
2351 if (memchr(name.data, '/', name.size) == NULL && (
2352 #ifdef __APPLE__
2353 dlopen(pool.strcat("/System/Library/Frameworks/", name.data, ".framework/", name.data, NULL), RTLD_LAZY | RTLD_GLOBAL) != NULL ||
2354 dlopen(pool.strcat("/System/Library/PrivateFrameworks/", name.data, ".framework/", name.data, NULL), RTLD_LAZY | RTLD_GLOBAL) != NULL ||
2355 #endif
2356 false))
2357 return CYJSUndefined(context);
2358
2359 CYJSString path;
2360 CYUTF8String code;
2361
2362 sqlite3_stmt *statement;
2363
2364 _sqlcall(sqlite3_prepare(database_,
2365 "select "
2366 "\"module\".\"code\", "
2367 "\"module\".\"flags\" "
2368 "from \"module\" "
2369 "where"
2370 " \"module\".\"name\" = ?"
2371 " limit 1"
2372 , -1, &statement, NULL));
2373
2374 _sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
2375
2376 if (_sqlcall(sqlite3_step(statement)) != SQLITE_DONE) {
2377 code.data = static_cast<const char *>(sqlite3_column_blob(statement, 0));
2378 code.size = sqlite3_column_bytes(statement, 0);
2379 path = CYJSString(name);
2380 code = CYPoolUTF8String(pool, code);
2381 } else {
2382 JSObjectRef resolve(CYCastJSObject(context, CYGetProperty(context, object, CYJSString("resolve"))));
2383 path = CYJSString(context, CYCallAsFunction(context, resolve, NULL, 1, arguments));
2384 }
2385
2386 _sqlcall(sqlite3_finalize(statement));
2387
2388 CYJSString property("exports");
2389
2390 JSObjectRef modules(CYGetCachedObject(context, CYJSString("modules")));
2391 JSValueRef cache(CYGetProperty(context, modules, path));
2392
2393 JSValueRef result;
2394 if (!JSValueIsUndefined(context, cache)) {
2395 JSObjectRef module(CYCastJSObject(context, cache));
2396 result = CYGetProperty(context, module, property);
2397 } else {
2398 if (code.data == NULL) {
2399 code = CYPoolFileUTF8String(pool, CYPoolCString(pool, context, path));
2400 _assert(code.data != NULL);
2401 }
2402
2403 size_t length(name.size);
2404 if (length >= 5 && strncmp(name.data + length - 5, ".json", 5) == 0) {
2405 JSObjectRef JSON(CYGetCachedObject(context, CYJSString("JSON")));
2406 JSObjectRef parse(CYCastJSObject(context, CYGetProperty(context, JSON, CYJSString("parse"))));
2407 JSValueRef arguments[1] = { CYCastJSValue(context, CYJSString(code)) };
2408 result = CYCallAsFunction(context, parse, JSON, 1, arguments);
2409 } else {
2410 JSObjectRef module(JSObjectMake(context, NULL, NULL));
2411 CYSetProperty(context, modules, path, module);
2412
2413 JSObjectRef exports(JSObjectMake(context, NULL, NULL));
2414 CYSetProperty(context, module, property, exports);
2415
2416 std::stringstream wrap;
2417 wrap << "(function (exports, require, module, __filename) { " << code << "\n});";
2418 code = CYPoolCode(pool, *wrap.rdbuf());
2419
2420 JSValueRef value(_jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0));
2421 JSObjectRef function(CYCastJSObject(context, value));
2422
2423 JSValueRef arguments[4] = { exports, object, module, CYCastJSValue(context, path) };
2424 CYCallAsFunction(context, function, NULL, 4, arguments);
2425 result = CYGetProperty(context, module, property);
2426 }
2427 }
2428
2429 return result;
2430 } CYCatch(NULL) }
2431
2432 static bool CYRunScript(JSGlobalContextRef context, const char *path) {
2433 CYPool pool;
2434 CYUTF8String code(CYPoolFileUTF8String(pool, pool.strcat(CYPoolLibraryPath(pool), path, NULL)));
2435 if (code.data == NULL)
2436 return false;
2437
2438 code = CYPoolCode(pool, code);
2439 _jsccall(JSEvaluateScript, context, CYJSString(code), NULL, NULL, 0);
2440 return true;
2441 }
2442
2443 extern "C" void CYDestroyWeak(JSWeakObjectMapRef weak, void *data) {
2444 }
2445
2446 extern "C" void CYSetupContext(JSGlobalContextRef context) {
2447 CYInitializeDynamic();
2448
2449 JSObjectRef global(CYGetGlobalObject(context));
2450
2451 JSObjectRef cy(CYPrivate<Context>::Make(context, context));
2452 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
2453
2454 /* Cache Globals {{{ */
2455 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
2456 CYSetProperty(context, cy, CYJSString("Array"), Array);
2457
2458 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
2459 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
2460
2461 JSObjectRef Boolean(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Boolean"))));
2462 CYSetProperty(context, cy, CYJSString("Boolean"), Boolean);
2463
2464 JSObjectRef Boolean_prototype(CYCastJSObject(context, CYGetProperty(context, Boolean, prototype_s)));
2465 CYSetProperty(context, cy, CYJSString("Boolean_prototype"), Boolean_prototype);
2466
2467 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
2468 CYSetProperty(context, cy, CYJSString("Error"), Error);
2469
2470 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
2471 CYSetProperty(context, cy, CYJSString("Function"), Function);
2472
2473 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
2474 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
2475
2476 JSObjectRef JSON(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("JSON"))));
2477 CYSetProperty(context, cy, CYJSString("JSON"), JSON);
2478
2479 JSObjectRef Number(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Number"))));
2480 CYSetProperty(context, cy, CYJSString("Number"), Number);
2481
2482 JSObjectRef Number_prototype(CYCastJSObject(context, CYGetProperty(context, Number, prototype_s)));
2483 CYSetProperty(context, cy, CYJSString("Number_prototype"), Number_prototype);
2484
2485 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
2486 CYSetProperty(context, cy, CYJSString("Object"), Object);
2487
2488 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
2489 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
2490
2491 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
2492 CYSetProperty(context, cy, CYJSString("String"), String);
2493
2494 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
2495 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
2496
2497 JSObjectRef SyntaxError(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("SyntaxError"))));
2498 CYSetProperty(context, cy, CYJSString("SyntaxError"), SyntaxError);
2499 /* }}} */
2500
2501 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
2502 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
2503
2504 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
2505 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
2506 CYSetProperty(context, cycript, CYJSString("compile"), &Cycript_compile_callAsFunction);
2507 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
2508
2509 JSObjectRef CArray(JSObjectMakeConstructor(context, CYPrivate<::CArray>::Class_, &CArray_new));
2510 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, CArray, prototype_s)), Array_prototype);
2511 CYSetProperty(context, cycript, CYJSString("CArray"), CArray);
2512
2513 JSObjectRef CString(JSObjectMakeConstructor(context, CYPrivate<::CString>::Class_, &CString_new));
2514 CYSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, CString, prototype_s)), String_prototype);
2515 CYSetProperty(context, cycript, CYJSString("CString"), CString);
2516
2517 JSObjectRef Functor(JSObjectMakeConstructor(context, cy::Functor::Class_, &Functor_new));
2518 JSObjectRef Functor_prototype(CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)));
2519 CYSetPrototype(context, Functor_prototype, Function_prototype);
2520 CYSetProperty(context, cy, CYJSString("Functor_prototype"), Functor_prototype);
2521 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
2522
2523 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, CYPrivate<Pointer>::Class_, &Pointer_new));
2524
2525 JSObjectRef Type(JSObjectMakeConstructor(context, CYPrivate<Type_privateData>::Class_, &Type_new));
2526 JSObjectRef Type_prototype(CYCastJSObject(context, CYGetProperty(context, Type, prototype_s)));
2527 CYSetPrototype(context, Type_prototype, Function_prototype);
2528 CYSetProperty(context, cy, CYJSString("Type_prototype"), Type_prototype);
2529 CYSetProperty(context, cycript, CYJSString("Type"), Type);
2530
2531 JSObjectRef Character_prototype(JSObjectMake(context, NULL, NULL));
2532 CYSetPrototype(context, Character_prototype, String_prototype);
2533 CYSetProperty(context, cy, CYJSString("Character_prototype"), Character_prototype);
2534 CYSetProperty(context, Character_prototype, CYJSString("valueOf"), _jsccall(JSEvaluateScript, context, CYJSString("(function(){return this.charCodeAt(0);})"), NULL, NULL, 0));
2535
2536 JSObjectRef modules(JSObjectMake(context, NULL, NULL));
2537 CYSetProperty(context, cy, CYJSString("modules"), modules);
2538
2539 JSObjectRef all(JSObjectMake(context, All_, NULL));
2540 CYSetProperty(context, cycript, CYJSString("all"), all);
2541
2542 JSObjectRef cache(JSObjectMake(context, NULL, NULL));
2543 CYSetProperty(context, cy, CYJSString("cache"), cache);
2544 CYSetPrototype(context, cache, all);
2545
2546 JSObjectRef alls(_jsccall(JSObjectCallAsConstructor, context, Array, 0, NULL));
2547 CYSetProperty(context, cycript, CYJSString("alls"), alls);
2548
2549 if (true) {
2550 JSObjectRef last(NULL), curr(global);
2551
2552 goto next; for (JSValueRef next;;) {
2553 if (JSValueIsNull(context, next))
2554 break;
2555 last = curr;
2556 curr = CYCastJSObject(context, next);
2557 next:
2558 next = JSObjectGetPrototype(context, curr);
2559 }
2560
2561 CYSetPrototype(context, last, cache);
2562 }
2563
2564 #ifdef __APPLE__
2565 if (&JSWeakObjectMapCreate != NULL) {
2566 JSWeakObjectMapRef weak(JSWeakObjectMapCreate(context, NULL, &CYDestroyWeak));
2567 CYSetProperty(context, cy, weak_s, CYCastJSValue(context, reinterpret_cast<uintptr_t>(weak)));
2568 }
2569 #endif
2570
2571 CYSetProperty(context, String_prototype, cyt_s, CYMakeType(context, sig::String(true)), kJSPropertyAttributeDontEnum);
2572
2573 CYSetProperty(context, cache, CYJSString("dlerror"), CYMakeFunctor(context, "dlerror", "*"), kJSPropertyAttributeDontEnum);
2574 CYSetProperty(context, cache, CYJSString("RTLD_DEFAULT"), CYCastJSValue(context, reinterpret_cast<intptr_t>(RTLD_DEFAULT)), kJSPropertyAttributeDontEnum);
2575 CYSetProperty(context, cache, CYJSString("dlsym"), CYMakeFunctor(context, "dlsym", "^v^v*"), kJSPropertyAttributeDontEnum);
2576
2577 CYSetProperty(context, cache, CYJSString("NULL"), CYJSNull(context), kJSPropertyAttributeDontEnum);
2578
2579 CYSetProperty(context, cache, CYJSString("bool"), CYMakeType(context, sig::Primitive<bool>()), kJSPropertyAttributeDontEnum);
2580 CYSetProperty(context, cache, CYJSString("char"), CYMakeType(context, sig::Primitive<char>()), kJSPropertyAttributeDontEnum);
2581 CYSetProperty(context, cache, CYJSString("schar"), CYMakeType(context, sig::Primitive<signed char>()), kJSPropertyAttributeDontEnum);
2582 CYSetProperty(context, cache, CYJSString("uchar"), CYMakeType(context, sig::Primitive<unsigned char>()), kJSPropertyAttributeDontEnum);
2583
2584 CYSetProperty(context, cache, CYJSString("short"), CYMakeType(context, sig::Primitive<short>()), kJSPropertyAttributeDontEnum);
2585 CYSetProperty(context, cache, CYJSString("int"), CYMakeType(context, sig::Primitive<int>()), kJSPropertyAttributeDontEnum);
2586 CYSetProperty(context, cache, CYJSString("long"), CYMakeType(context, sig::Primitive<long>()), kJSPropertyAttributeDontEnum);
2587 CYSetProperty(context, cache, CYJSString("longlong"), CYMakeType(context, sig::Primitive<long long>()), kJSPropertyAttributeDontEnum);
2588
2589 CYSetProperty(context, cache, CYJSString("ushort"), CYMakeType(context, sig::Primitive<unsigned short>()), kJSPropertyAttributeDontEnum);
2590 CYSetProperty(context, cache, CYJSString("uint"), CYMakeType(context, sig::Primitive<unsigned int>()), kJSPropertyAttributeDontEnum);
2591 CYSetProperty(context, cache, CYJSString("ulong"), CYMakeType(context, sig::Primitive<unsigned long>()), kJSPropertyAttributeDontEnum);
2592 CYSetProperty(context, cache, CYJSString("ulonglong"), CYMakeType(context, sig::Primitive<unsigned long long>()), kJSPropertyAttributeDontEnum);
2593
2594 #ifdef __SIZEOF_INT128__
2595 CYSetProperty(context, cache, CYJSString("int128"), CYMakeType(context, sig::Primitive<__int128>()), kJSPropertyAttributeDontEnum);
2596 CYSetProperty(context, cache, CYJSString("uint128"), CYMakeType(context, sig::Primitive<unsigned __int128>()), kJSPropertyAttributeDontEnum);
2597 #endif
2598
2599 CYSetProperty(context, cache, CYJSString("float"), CYMakeType(context, sig::Primitive<float>()), kJSPropertyAttributeDontEnum);
2600 CYSetProperty(context, cache, CYJSString("double"), CYMakeType(context, sig::Primitive<double>()), kJSPropertyAttributeDontEnum);
2601 CYSetProperty(context, cache, CYJSString("longdouble"), CYMakeType(context, sig::Primitive<long double>()), kJSPropertyAttributeDontEnum);
2602
2603 CYSetProperty(context, global, CYJSString("require"), &require_callAsFunction, kJSPropertyAttributeDontEnum);
2604
2605 JSObjectRef System(JSObjectMake(context, NULL, NULL));
2606 CYSetProperty(context, all, CYJSString("system"), System);
2607 System = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("system")));
2608 CYSetProperty(context, cy, CYJSString("System"), System);
2609
2610 JSObjectRef process(JSObjectMake(context, NULL, NULL));
2611 CYSetProperty(context, global, CYJSString("process"), process);
2612 CYSetProperty(context, cy, CYJSString("process"), process);
2613
2614 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
2615 CYSetProperty(context, System, CYJSString("print"), &System_print);
2616
2617 CYSetProperty(context, global, CYJSString("global"), global);
2618 CYSetProperty(context, global, CYJSString("print"), &Global_print);
2619
2620 for (CYHook *hook : GetHooks())
2621 if (hook->SetupContext != NULL)
2622 (*hook->SetupContext)(context);
2623
2624 CYArrayPush(context, alls, cycript);
2625
2626 CYRunScript(context, "/libcycript.cy");
2627 }
2628
2629 static JSGlobalContextRef context_;
2630
2631 _visible JSGlobalContextRef CYGetJSContext() {
2632 CYInitializeDynamic();
2633
2634 if (context_ == NULL) {
2635 context_ = JSGlobalContextCreate(Global_);
2636 CYSetupContext(context_);
2637 }
2638
2639 return context_;
2640 }
2641
2642 _visible void CYDestroyContext() {
2643 if (context_ == NULL)
2644 return;
2645 JSGlobalContextRelease(context_);
2646 context_ = NULL;
2647 }