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