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