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