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