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