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