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