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