]> git.saurik.com Git - cycript.git/blob - Execute.cpp
When CYONifying fields, @error encode exceptions.
[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
26 #include "cycript.hpp"
27
28 #include "sig/parse.hpp"
29 #include "sig/ffi_type.hpp"
30
31 #include "Pooling.hpp"
32 #include "Execute.hpp"
33
34 #include <sys/mman.h>
35
36 #include <iostream>
37 #include <set>
38 #include <map>
39 #include <iomanip>
40 #include <sstream>
41 #include <cmath>
42
43 #include "Parser.hpp"
44
45 #include "Error.hpp"
46 #include "JavaScript.hpp"
47 #include "String.hpp"
48
49 struct CYHooks *hooks_;
50
51 /* JavaScript Properties {{{ */
52 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
53 JSValueRef exception(NULL);
54 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
55 CYThrow(context, exception);
56 return value;
57 }
58
59 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
60 JSValueRef exception(NULL);
61 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
62 CYThrow(context, exception);
63 return value;
64 }
65
66 void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
67 JSValueRef exception(NULL);
68 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
69 CYThrow(context, exception);
70 }
71
72 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
73 JSValueRef exception(NULL);
74 JSObjectSetProperty(context, object, name, value, attributes, &exception);
75 CYThrow(context, exception);
76 }
77
78 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
79 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
80 }
81 /* }}} */
82 /* JavaScript Strings {{{ */
83 JSStringRef CYCopyJSString(const char *value) {
84 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
85 }
86
87 JSStringRef CYCopyJSString(JSStringRef value) {
88 return value == NULL ? NULL : JSStringRetain(value);
89 }
90
91 JSStringRef CYCopyJSString(CYUTF8String value) {
92 // XXX: this is very wrong; it needs to convert to UTF16 and then create from there
93 return CYCopyJSString(value.data);
94 }
95
96 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
97 if (JSValueIsNull(context, value))
98 return NULL;
99 JSValueRef exception(NULL);
100 JSStringRef string(JSValueToStringCopy(context, value, &exception));
101 CYThrow(context, exception);
102 return string;
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 length_s;
139 JSStringRef message_s;
140 JSStringRef name_s;
141 JSStringRef pop_s;
142 JSStringRef prototype_s;
143 JSStringRef push_s;
144 JSStringRef splice_s;
145 JSStringRef toCYON_s;
146 JSStringRef toJSON_s;
147 JSStringRef toPointer_s;
148 JSStringRef toString_s;
149
150 static JSStringRef Result_;
151
152 void CYFinalize(JSObjectRef object) {
153 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
154 _assert(internal->count_ != _not(unsigned));
155 if (--internal->count_ == 0)
156 delete internal;
157 }
158
159 void Structor_(CYPool &pool, sig::Type *&type) {
160 if (
161 type->primitive == sig::pointer_P &&
162 type->data.data.type != NULL &&
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 JSValueRef exception(NULL);
288 double number(JSValueToNumber(context, value, &exception));
289 CYThrow(context, exception);
290 return number;
291 }
292
293 bool CYCastBool(JSContextRef context, JSValueRef value) {
294 return JSValueToBoolean(context, value);
295 }
296
297 JSValueRef CYJSNull(JSContextRef context) {
298 return JSValueMakeNull(context);
299 }
300
301 JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
302 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
303 }
304
305 JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
306 return CYCastJSValue(context, CYJSString(value));
307 }
308
309 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
310 JSValueRef exception(NULL);
311 JSObjectRef object(JSValueToObject(context, value, &exception));
312 CYThrow(context, exception);
313 return object;
314 }
315
316 JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
317 JSValueRef exception(NULL);
318 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
319 CYThrow(context, exception);
320 return value;
321 }
322
323 bool CYIsCallable(JSContextRef context, JSValueRef value) {
324 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
325 }
326
327 size_t CYArrayLength(JSContextRef context, JSObjectRef array) {
328 return CYCastDouble(context, CYGetProperty(context, array, length_s));
329 }
330
331 JSValueRef CYArrayGet(JSContextRef context, JSObjectRef array, size_t index) {
332 JSValueRef exception(NULL);
333 JSValueRef value(JSObjectGetPropertyAtIndex(context, array, index, &exception));
334 CYThrow(context, exception);
335 return value;
336 }
337
338 void CYArrayPush(JSContextRef context, JSObjectRef array, JSValueRef value) {
339 JSValueRef exception(NULL);
340 JSValueRef arguments[1];
341 arguments[0] = value;
342 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
343 JSObjectCallAsFunction(context, CYCastJSObject(context, CYGetProperty(context, Array, push_s)), array, 1, arguments, &exception);
344 CYThrow(context, exception);
345 }
346
347 static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
348 if (count == 0)
349 printf("\n");
350 else {
351 CYPool pool;
352 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
353 }
354
355 return CYJSUndefined(context);
356 } CYCatch(NULL) }
357
358 static size_t Nonce_(0);
359
360 static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
361 CYPool pool;
362 const char *name(pool.strcat(CYPoolCString(pool, context, arguments[0]), pool.itoa(Nonce_++), NULL));
363 return CYCastJSValue(context, name);
364 } CYCatch(NULL) }
365
366 static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
367 JSGarbageCollect(context);
368 return CYJSUndefined(context);
369 } CYCatch(NULL) }
370
371 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
372 switch (JSType type = JSValueGetType(context, value)) {
373 case kJSTypeUndefined:
374 return "undefined";
375 case kJSTypeNull:
376 return "null";
377 case kJSTypeBoolean:
378 return CYCastBool(context, value) ? "true" : "false";
379
380 case kJSTypeNumber: {
381 std::ostringstream str;
382 CYNumerify(str, CYCastDouble(context, value));
383 std::string value(str.str());
384 return pool.strmemdup(value.c_str(), value.size());
385 } break;
386
387 case kJSTypeString: {
388 std::ostringstream str;
389 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
390 CYStringify(str, string.data, string.size);
391 std::string value(str.str());
392 return pool.strmemdup(value.c_str(), value.size());
393 } break;
394
395 case kJSTypeObject:
396 return CYPoolCCYON(pool, context, (JSObjectRef) value);
397 default:
398 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
399 }
400 } CYCatch(NULL) }
401
402 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSValueRef value) {
403 JSValueRef exception(NULL);
404 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
405 CYThrow(context, exception);
406 return cyon;
407 }
408
409 const char *CYPoolCCYON(CYPool &pool, JSContextRef context, JSObjectRef object) {
410 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
411 if (CYIsCallable(context, toCYON)) {
412 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
413 _assert(value != NULL);
414 return CYPoolCString(pool, context, value);
415 }
416
417 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
418 if (CYIsCallable(context, toJSON)) {
419 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
420 JSValueRef exception(NULL);
421 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
422 CYThrow(context, exception);
423 return cyon;
424 }
425
426 if (JSObjectIsFunction(context, object)) {
427 JSValueRef toString(CYGetProperty(context, object, toString_s));
428 if (CYIsCallable(context, toString)) {
429 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
430 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
431 _assert(value != NULL);
432 return CYPoolCString(pool, context, value);
433 }
434 }
435
436 std::ostringstream str;
437
438 str << '{';
439
440 // XXX: this is, sadly, going to leak
441 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
442
443 bool comma(false);
444
445 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
446 if (comma)
447 str << ',';
448 else
449 comma = true;
450
451 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
452 CYUTF8String string(CYPoolUTF8String(pool, context, name));
453
454 if (CYIsKey(string))
455 str << string.data;
456 else
457 CYStringify(str, string.data, string.size);
458
459 str << ':';
460
461 try {
462 JSValueRef value(CYGetProperty(context, object, name));
463 str << CYPoolCCYON(pool, context, value);
464 } catch (const CYException &error) {
465 str << "@error";
466 }
467 }
468
469 JSPropertyNameArrayRelease(names);
470
471 str << '}';
472
473 std::string string(str.str());
474 return pool.strmemdup(string.c_str(), string.size());
475 }
476
477 static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
478 CYPool pool;
479 std::ostringstream str;
480
481 str << '[';
482
483 JSValueRef length(CYGetProperty(context, _this, length_s));
484 bool comma(false);
485
486 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
487 JSValueRef value(CYGetProperty(context, _this, index));
488
489 if (comma)
490 str << ',';
491 else
492 comma = true;
493
494 if (!JSValueIsUndefined(context, value))
495 str << CYPoolCCYON(pool, context, value);
496 else {
497 str << ',';
498 comma = false;
499 }
500 }
501
502 str << ']';
503
504 std::string value(str.str());
505 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
506 } CYCatch(NULL) }
507
508 static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
509 CYPool pool;
510 std::ostringstream str;
511
512 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
513 CYStringify(str, string.data, string.size);
514
515 std::string value(str.str());
516 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
517 } CYCatch(NULL) }
518
519 JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
520 Pointer *internal(new Pointer(pointer, context, owner, length, type));
521 return JSObjectMake(context, Pointer_, internal);
522 }
523
524 static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
525 return JSObjectMake(context, Functor_, new cy::Functor(type, function));
526 }
527
528 static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *type, void **cache) {
529 cy::Functor *internal;
530 if (*cache != NULL)
531 internal = reinterpret_cast<cy::Functor *>(*cache);
532 else {
533 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
534 if (function == NULL)
535 return NULL;
536
537 internal = new cy::Functor(type, function);
538 *cache = internal;
539 }
540
541 ++internal->count_;
542 return JSObjectMake(context, Functor_, internal);
543 }
544
545 static bool CYGetOffset(CYPool &pool, JSContextRef context, JSStringRef value, ssize_t &index) {
546 return CYGetOffset(CYPoolCString(pool, context, value), index);
547 }
548
549 void *CYCastPointer_(JSContextRef context, JSValueRef value) {
550 switch (JSValueGetType(context, value)) {
551 case kJSTypeNull:
552 return NULL;
553 case kJSTypeObject: {
554 JSObjectRef object((JSObjectRef) value);
555 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
556 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
557 return internal->value_;
558 }
559 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
560 if (CYIsCallable(context, toPointer)) {
561 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
562 _assert(value != NULL);
563 return CYCastPointer_(context, value);
564 }
565 } default:
566 double number(CYCastDouble(context, value));
567 if (std::isnan(number))
568 throw CYJSError(context, "cannot convert value to pointer");
569 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
570 }
571 }
572
573 void CYPoolFFI(CYPool *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
574 switch (type->primitive) {
575 case sig::boolean_P:
576 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
577 break;
578
579 #define CYPoolFFI_(primitive, native) \
580 case sig::primitive ## _P: \
581 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
582 break;
583
584 CYPoolFFI_(uchar, unsigned char)
585 CYPoolFFI_(char, char)
586 CYPoolFFI_(ushort, unsigned short)
587 CYPoolFFI_(short, short)
588 CYPoolFFI_(ulong, unsigned long)
589 CYPoolFFI_(long, long)
590 CYPoolFFI_(uint, unsigned int)
591 CYPoolFFI_(int, int)
592 CYPoolFFI_(ulonglong, unsigned long long)
593 CYPoolFFI_(longlong, long long)
594 CYPoolFFI_(float, float)
595 CYPoolFFI_(double, double)
596
597 case sig::array_P: {
598 uint8_t *base(reinterpret_cast<uint8_t *>(data));
599 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
600 for (size_t index(0); index != type->data.data.size; ++index) {
601 ffi_type *field(ffi->elements[index]);
602
603 JSValueRef rhs;
604 if (aggregate == NULL)
605 rhs = value;
606 else {
607 rhs = CYGetProperty(context, aggregate, index);
608 if (JSValueIsUndefined(context, rhs))
609 throw CYJSError(context, "unable to extract array value");
610 }
611
612 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
613 // XXX: alignment?
614 base += field->size;
615 }
616 } break;
617
618 case sig::pointer_P:
619 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
620 break;
621
622 case sig::string_P:
623 _assert(pool != NULL);
624 *reinterpret_cast<const char **>(data) = CYPoolCString(*pool, context, value);
625 break;
626
627 case sig::struct_P: {
628 uint8_t *base(reinterpret_cast<uint8_t *>(data));
629 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
630 for (size_t index(0); index != type->data.signature.count; ++index) {
631 sig::Element *element(&type->data.signature.elements[index]);
632 ffi_type *field(ffi->elements[index]);
633
634 JSValueRef rhs;
635 if (aggregate == NULL)
636 rhs = value;
637 else {
638 rhs = CYGetProperty(context, aggregate, index);
639 if (JSValueIsUndefined(context, rhs)) {
640 if (element->name != NULL)
641 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
642 else
643 goto undefined;
644 if (JSValueIsUndefined(context, rhs)) undefined:
645 throw CYJSError(context, "unable to extract structure value");
646 }
647 }
648
649 CYPoolFFI(pool, context, element->type, field, base, rhs);
650 // XXX: alignment?
651 base += field->size;
652 }
653 } break;
654
655 case sig::void_P:
656 break;
657
658 default:
659 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
660 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
661 return;
662
663 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
664 }
665 }
666
667 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
668 switch (type->primitive) {
669 case sig::boolean_P:
670 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
671
672 #define CYFromFFI_(primitive, native) \
673 case sig::primitive ## _P: \
674 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
675
676 CYFromFFI_(uchar, unsigned char)
677 CYFromFFI_(char, char)
678 CYFromFFI_(ushort, unsigned short)
679 CYFromFFI_(short, short)
680 CYFromFFI_(ulong, unsigned long)
681 CYFromFFI_(long, long)
682 CYFromFFI_(uint, unsigned int)
683 CYFromFFI_(int, int)
684 CYFromFFI_(ulonglong, unsigned long long)
685 CYFromFFI_(longlong, long long)
686 CYFromFFI_(float, float)
687 CYFromFFI_(double, double)
688
689 case sig::array_P:
690 if (void *pointer = data)
691 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
692 else goto null;
693
694 case sig::pointer_P:
695 if (void *pointer = *reinterpret_cast<void **>(data))
696 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
697 else goto null;
698
699 case sig::string_P:
700 if (char *utf8 = *reinterpret_cast<char **>(data))
701 return CYCastJSValue(context, utf8);
702 else goto null;
703
704 case sig::struct_P:
705 return CYMakeStruct(context, data, type, ffi, owner);
706 case sig::void_P:
707 return CYJSUndefined(context);
708
709 null:
710 return CYJSNull(context);
711 default:
712 if (hooks_ != NULL && hooks_->FromFFI != NULL)
713 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
714 return value;
715
716 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
717 }
718 }
719
720 void CYExecuteClosure(ffi_cif *cif, void *result, void **arguments, void *arg, JSValueRef (*adapter)(JSContextRef, size_t, JSValueRef[], JSObjectRef)) {
721 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
722
723 JSContextRef context(internal->context_);
724
725 size_t count(internal->cif_.nargs);
726 JSValueRef values[count];
727
728 for (size_t index(0); index != count; ++index)
729 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
730
731 JSValueRef value(adapter(context, count, values, internal->function_));
732 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
733 }
734
735 static JSValueRef FunctionAdapter_(JSContextRef context, size_t count, JSValueRef values[], JSObjectRef function) {
736 return CYCallAsFunction(context, function, NULL, count, values);
737 }
738
739 static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
740 CYExecuteClosure(cif, result, arguments, arg, &FunctionAdapter_);
741 }
742
743 Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
744 // XXX: in case of exceptions this will leak
745 // XXX: in point of fact, this may /need/ to leak :(
746 Closure_privateData *internal(new Closure_privateData(context, function, type));
747
748 #if defined(__APPLE__) && defined(__arm__)
749 void *executable;
750 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
751
752 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, callback, internal, executable));
753 _assert(status == FFI_OK);
754
755 internal->value_ = executable;
756 #else
757 ffi_closure *closure((ffi_closure *) _syscall(mmap(
758 NULL, sizeof(ffi_closure),
759 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
760 -1, 0
761 )));
762
763 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
764 _assert(status == FFI_OK);
765
766 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
767
768 internal->value_ = closure;
769 #endif
770
771 return internal;
772 }
773
774 static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
775 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
776 JSObjectRef object(JSObjectMake(context, Functor_, internal));
777 // XXX: see above notes about needing to leak
778 JSValueProtect(CYGetJSContext(context), object);
779 return object;
780 }
781
782 JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
783 return CYCastJSObject(context, CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name));
784 }
785
786 static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
787 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
788
789 JSValueRef exception(NULL);
790 bool function(JSValueIsInstanceOfConstructor(context, value, Function, &exception));
791 CYThrow(context, exception);
792
793 if (function) {
794 JSObjectRef function(CYCastJSObject(context, value));
795 return CYMakeFunctor(context, function, type);
796 } else {
797 void (*function)()(CYCastPointer<void (*)()>(context, value));
798 return CYMakeFunctor(context, function, type);
799 }
800 }
801
802 static bool Index_(CYPool &pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
803 Type_privateData *typical(internal->type_);
804 sig::Type *type(typical->type_);
805 if (type == NULL)
806 return false;
807
808 const char *name(CYPoolCString(pool, context, property));
809 size_t length(strlen(name));
810 double number(CYCastDouble(name, length));
811
812 size_t count(type->data.signature.count);
813
814 if (std::isnan(number)) {
815 if (property == NULL)
816 return false;
817
818 sig::Element *elements(type->data.signature.elements);
819
820 for (size_t local(0); local != count; ++local) {
821 sig::Element *element(&elements[local]);
822 if (element->name != NULL && strcmp(name, element->name) == 0) {
823 index = local;
824 goto base;
825 }
826 }
827
828 return false;
829 } else {
830 index = static_cast<ssize_t>(number);
831 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
832 return false;
833 }
834
835 base:
836 ffi_type **elements(typical->GetFFI()->elements);
837
838 base = reinterpret_cast<uint8_t *>(internal->value_);
839 for (ssize_t local(0); local != index; ++local)
840 base += elements[local]->size;
841
842 return true;
843 }
844
845 static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
846 CYPool pool;
847 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
848
849 if (JSStringIsEqual(property, length_s))
850 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
851
852 Type_privateData *typical(internal->type_);
853
854 if (typical->type_ == NULL)
855 return NULL;
856
857 ssize_t offset;
858 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
859 offset = 0;
860 else if (!CYGetOffset(pool, context, property, offset))
861 return NULL;
862
863 ffi_type *ffi(typical->GetFFI());
864
865 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
866 base += ffi->size * offset;
867
868 JSObjectRef owner(internal->GetOwner() ?: object);
869 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
870 } CYCatch(NULL) }
871
872 static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
873 CYPool pool;
874 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
875 Type_privateData *typical(internal->type_);
876
877 if (typical->type_ == NULL)
878 return false;
879
880 ssize_t offset;
881 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
882 offset = 0;
883 else if (!CYGetOffset(pool, context, property, offset))
884 return false;
885
886 ffi_type *ffi(typical->GetFFI());
887
888 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
889 base += ffi->size * offset;
890
891 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
892 return true;
893 } CYCatch(false) }
894
895 static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
896 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
897 Type_privateData *typical(internal->type_);
898 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
899 } CYCatch(NULL) }
900
901 static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
902 CYPool pool;
903 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
904 Type_privateData *typical(internal->type_);
905
906 ssize_t index;
907 uint8_t *base;
908
909 if (!Index_(pool, context, internal, property, index, base))
910 return NULL;
911
912 JSObjectRef owner(internal->GetOwner() ?: object);
913
914 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
915 } CYCatch(NULL) }
916
917 static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
918 CYPool pool;
919 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
920 Type_privateData *typical(internal->type_);
921
922 ssize_t index;
923 uint8_t *base;
924
925 if (!Index_(pool, context, internal, property, index, base))
926 return false;
927
928 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
929 return true;
930 } CYCatch(false) }
931
932 static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
933 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
934 Type_privateData *typical(internal->type_);
935 sig::Type *type(typical->type_);
936
937 if (type == NULL)
938 return;
939
940 size_t count(type->data.signature.count);
941 sig::Element *elements(type->data.signature.elements);
942
943 char number[32];
944
945 for (size_t index(0); index != count; ++index) {
946 const char *name;
947 name = elements[index].name;
948
949 if (name == NULL) {
950 sprintf(number, "%zu", index);
951 name = number;
952 }
953
954 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
955 }
956 }
957
958 JSValueRef CYCallFunction(CYPool &pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { CYTry {
959 if (setups + count != signature->count - 1)
960 throw CYJSError(context, "incorrect number of arguments to ffi function");
961
962 size_t size(setups + count);
963 void *values[size];
964 memcpy(values, setup, sizeof(void *) * setups);
965
966 for (size_t index(setups); index != size; ++index) {
967 sig::Element *element(&signature->elements[index + 1]);
968 ffi_type *ffi(cif->arg_types[index]);
969 // XXX: alignment?
970 values[index] = new(pool) uint8_t[ffi->size];
971 CYPoolFFI(&pool, context, element->type, ffi, values[index], arguments[index - setups]);
972 }
973
974 uint8_t value[cif->rtype->size];
975
976 if (hooks_ != NULL && hooks_->CallFunction != NULL)
977 (*hooks_->CallFunction)(context, cif, function, value, values);
978 else
979 ffi_call(cif, function, value, values);
980
981 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
982 } CYCatch(NULL) }
983
984 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
985 CYPool pool;
986 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
987 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
988 } CYCatch(NULL) }
989
990 JSObjectRef CYMakeType(JSContextRef context, const char *type) {
991 Type_privateData *internal(new Type_privateData(type));
992 return JSObjectMake(context, Type_privateData::Class_, internal);
993 }
994
995 JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
996 Type_privateData *internal(new Type_privateData(type));
997 return JSObjectMake(context, Type_privateData::Class_, internal);
998 }
999
1000 static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1001 JSObjectRef global(CYGetGlobalObject(context));
1002 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1003 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1004
1005 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1006 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
1007 if (JSValueRef value = CYGetProperty(context, space, property))
1008 if (!JSValueIsUndefined(context, value))
1009 return value;
1010
1011 CYPool pool;
1012 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1013
1014 size_t length(name.size);
1015 char keyed[length + 2];
1016 memcpy(keyed + 1, name.data, length + 1);
1017
1018 static const char *modes = "0124";
1019 for (size_t i(0); i != 4; ++i) {
1020 char mode(modes[i]);
1021 keyed[0] = mode;
1022
1023 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
1024 switch (mode) {
1025 case '0':
1026 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
1027
1028 case '1':
1029 return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);
1030
1031 case '2':
1032 if (void *symbol = CYCastSymbol(name.data)) {
1033 // XXX: this is horrendously inefficient
1034 sig::Signature signature;
1035 sig::Parse(pool, &signature, entry->value_, &Structor_);
1036 ffi_cif cif;
1037 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1038 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1039 } else return NULL;
1040
1041 // XXX: implement case 3
1042 case '4':
1043 return CYMakeType(context, entry->value_);
1044 }
1045 }
1046
1047 return NULL;
1048 } CYCatch(NULL) }
1049
1050 static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1051 JSObjectRef global(CYGetGlobalObject(context));
1052 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1053 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1054
1055 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1056 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1057 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1058 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1059 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1060 JSPropertyNameArrayRelease(subset);
1061 }
1062 }
1063
1064 static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1065 if (count != 2)
1066 throw CYJSError(context, "incorrect number of arguments to Pointer constructor");
1067
1068 CYPool pool;
1069
1070 void *value(CYCastPointer<void *>(context, arguments[0]));
1071 const char *type(CYPoolCString(pool, context, arguments[1]));
1072
1073 sig::Signature signature;
1074 sig::Parse(pool, &signature, type, &Structor_);
1075
1076 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1077 } CYCatch(NULL) }
1078
1079 static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1080 if (count != 1)
1081 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1082 CYPool pool;
1083 const char *type(CYPoolCString(pool, context, arguments[0]));
1084 return CYMakeType(context, type);
1085 } CYCatch(NULL) }
1086
1087 static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1088 if (count != 1)
1089 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1090 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1091
1092 CYPool pool;
1093 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1094 if (index == _not(size_t))
1095 throw CYJSError(context, "invalid array size used with Type.arrayOf");
1096
1097 sig::Type type;
1098 type.name = NULL;
1099 type.flags = 0;
1100
1101 type.primitive = sig::array_P;
1102 type.data.data.type = internal->type_;
1103 type.data.data.size = index;
1104
1105 return CYMakeType(context, &type);
1106 } CYCatch(NULL) }
1107
1108 static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1109 if (count != 0)
1110 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1111 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1112
1113 sig::Type type(*internal->type_);
1114 type.flags |= JOC_TYPE_CONST;
1115 return CYMakeType(context, &type);
1116 } CYCatch(NULL) }
1117
1118 static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1119 if (count != 0)
1120 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1121 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1122
1123 sig::Type type;
1124 type.name = NULL;
1125 type.flags = 0;
1126
1127 type.primitive = sig::pointer_P;
1128 type.data.data.type = internal->type_;
1129 type.data.data.size = 0;
1130
1131 return CYMakeType(context, &type);
1132 } CYCatch(NULL) }
1133
1134 static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1135 if (count != 1)
1136 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1137 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1138
1139 CYPool pool;
1140 const char *name(CYPoolCString(pool, context, arguments[0]));
1141
1142 sig::Type type(*internal->type_);
1143 type.name = name;
1144 return CYMakeType(context, &type);
1145 } CYCatch(NULL) }
1146
1147 static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1148 if (count != 1)
1149 throw CYJSError(context, "incorrect number of arguments to type cast function");
1150 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1151
1152 sig::Type *type(internal->type_);
1153 ffi_type *ffi(internal->GetFFI());
1154 // XXX: alignment?
1155 uint8_t value[ffi->size];
1156 CYPool pool;
1157 CYPoolFFI(&pool, context, type, ffi, value, arguments[0]);
1158 return CYFromFFI(context, type, ffi, value);
1159 } CYCatch(NULL) }
1160
1161 static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1162 if (count != 0)
1163 throw CYJSError(context, "incorrect number of arguments to Type allocator");
1164 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1165
1166 sig::Type *type(internal->type_);
1167 size_t length;
1168
1169 if (type->primitive != sig::array_P)
1170 length = _not(size_t);
1171 else {
1172 length = type->data.data.size;
1173 type = type->data.data.type;
1174 }
1175
1176 void *value(malloc(internal->GetFFI()->size));
1177 return CYMakePointer(context, value, length, type, NULL, NULL);
1178 } CYCatch(NULL) }
1179
1180 static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1181 if (count != 2)
1182 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1183 CYPool pool;
1184 const char *type(CYPoolCString(pool, context, arguments[1]));
1185 return CYMakeFunctor(context, arguments[0], type);
1186 } CYCatch(NULL) }
1187
1188 static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1189 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1190 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1191 } CYCatch(NULL) }
1192
1193 static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1194 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1195 }
1196
1197 static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1198 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1199 char string[32];
1200 sprintf(string, "%p", internal->value_);
1201 return CYCastJSValue(context, string);
1202 } CYCatch(NULL) }
1203
1204 static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1205 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1206 if (internal->length_ != _not(size_t)) {
1207 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
1208 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1209 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1210 } else {
1211 char string[32];
1212 sprintf(string, "%p", internal->value_);
1213 return CYCastJSValue(context, string);
1214 }
1215 } CYCatch(NULL) }
1216
1217 static JSValueRef Functor_getProperty_type(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1218 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1219 CYPool pool;
1220 return CYCastJSValue(context, Unparse(pool, &internal->signature_));
1221 } CYCatch(NULL) }
1222
1223 static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1224 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1225 return CYCastJSValue(context, internal->GetFFI()->alignment);
1226 } CYCatch(NULL) }
1227
1228 static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1229 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1230 return CYCastJSValue(context, internal->type_->name);
1231 } CYCatch(NULL) }
1232
1233 static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1234 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1235 return CYCastJSValue(context, internal->GetFFI()->size);
1236 } CYCatch(NULL) }
1237
1238 static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1239 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1240 CYPool pool;
1241 const char *type(sig::Unparse(pool, internal->type_));
1242 return CYCastJSValue(context, CYJSString(type));
1243 } CYCatch(NULL) }
1244
1245 static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1246 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1247 CYPool pool;
1248 const char *type(sig::Unparse(pool, internal->type_));
1249 std::ostringstream str;
1250 CYStringify(str, type, strlen(type));
1251 char *cyon(pool.strcat("new Type(", str.str().c_str(), ")", NULL));
1252 return CYCastJSValue(context, CYJSString(cyon));
1253 } CYCatch(NULL) }
1254
1255 static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1256 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1257 }
1258
1259 static JSStaticFunction Pointer_staticFunctions[4] = {
1260 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1261 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1262 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1263 {NULL, NULL, 0}
1264 };
1265
1266 static JSStaticFunction Struct_staticFunctions[2] = {
1267 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1268 {NULL, NULL, 0}
1269 };
1270
1271 static JSStaticFunction Functor_staticFunctions[4] = {
1272 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1273 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1274 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1275 {NULL, NULL, 0}
1276 };
1277
1278 namespace cy {
1279 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1280 }
1281
1282 static JSStaticValue Functor_staticValues[2] = {
1283 {"type", &Functor_getProperty_type, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1284 {NULL, NULL, NULL, 0}
1285 };
1286
1287 static JSStaticValue Type_staticValues[4] = {
1288 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1289 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1290 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1291 {NULL, NULL, NULL, 0}
1292 };
1293
1294 static JSStaticFunction Type_staticFunctions[8] = {
1295 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1296 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1297 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1298 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1299 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1300 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1301 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1302 {NULL, NULL, 0}
1303 };
1304
1305 static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1306
1307 void CYSetArgs(int argc, const char *argv[]) {
1308 JSContextRef context(CYGetJSContext());
1309 JSValueRef args[argc];
1310 for (int i(0); i != argc; ++i)
1311 args[i] = CYCastJSValue(context, argv[i]);
1312
1313 JSObjectRef array;
1314 if (JSObjectMakeArray$ != NULL) {
1315 JSValueRef exception(NULL);
1316 array = (*JSObjectMakeArray$)(context, argc, args, &exception);
1317 CYThrow(context, exception);
1318 } else {
1319 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1320 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1321 array = CYCastJSObject(context, value);
1322 }
1323
1324 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1325 CYSetProperty(context, System, CYJSString("args"), array);
1326 }
1327
1328 JSObjectRef CYGetGlobalObject(JSContextRef context) {
1329 return JSContextGetGlobalObject(context);
1330 }
1331
1332 const char *CYExecute(CYPool &pool, CYUTF8String code) {
1333 JSContextRef context(CYGetJSContext());
1334 JSValueRef exception(NULL), result;
1335
1336 void *handle;
1337 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1338 handle = (*hooks_->ExecuteStart)(context);
1339 else
1340 handle = NULL;
1341
1342 const char *json;
1343
1344 try {
1345 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1346 } catch (const char *error) {
1347 return error;
1348 }
1349
1350 if (exception != NULL) error:
1351 return CYPoolCString(pool, context, CYJSString(context, exception));
1352
1353 if (JSValueIsUndefined(context, result))
1354 return NULL;
1355
1356 try {
1357 json = CYPoolCCYON(pool, context, result, &exception);
1358 } catch (const char *error) {
1359 return error;
1360 }
1361
1362 if (exception != NULL)
1363 goto error;
1364
1365 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1366
1367 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1368 (*hooks_->ExecuteEnd)(context, handle);
1369 return json;
1370 }
1371
1372 extern "C" void CydgetSetupContext(JSGlobalContextRef context) {
1373 CYSetupContext(context);
1374 }
1375
1376 static bool initialized_ = false;
1377
1378 void CYInitializeDynamic() {
1379 if (!initialized_)
1380 initialized_ = true;
1381 else return;
1382
1383 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1384
1385 JSClassDefinition definition;
1386
1387 definition = kJSClassDefinitionEmpty;
1388 definition.className = "All";
1389 definition.getProperty = &All_getProperty;
1390 definition.getPropertyNames = &All_getPropertyNames;
1391 All_ = JSClassCreate(&definition);
1392
1393 definition = kJSClassDefinitionEmpty;
1394 definition.className = "Context";
1395 definition.finalize = &CYFinalize;
1396 Context_ = JSClassCreate(&definition);
1397
1398 definition = kJSClassDefinitionEmpty;
1399 definition.className = "Functor";
1400 definition.staticFunctions = cy::Functor::StaticFunctions;
1401 definition.staticValues = Functor_staticValues;
1402 definition.callAsFunction = &Functor_callAsFunction;
1403 definition.finalize = &CYFinalize;
1404 Functor_ = JSClassCreate(&definition);
1405
1406 definition = kJSClassDefinitionEmpty;
1407 definition.className = "Pointer";
1408 definition.staticFunctions = Pointer_staticFunctions;
1409 definition.getProperty = &Pointer_getProperty;
1410 definition.setProperty = &Pointer_setProperty;
1411 definition.finalize = &CYFinalize;
1412 Pointer_ = JSClassCreate(&definition);
1413
1414 definition = kJSClassDefinitionEmpty;
1415 definition.className = "Struct";
1416 definition.staticFunctions = Struct_staticFunctions;
1417 definition.getProperty = &Struct_getProperty;
1418 definition.setProperty = &Struct_setProperty;
1419 definition.getPropertyNames = &Struct_getPropertyNames;
1420 definition.finalize = &CYFinalize;
1421 Struct_ = JSClassCreate(&definition);
1422
1423 definition = kJSClassDefinitionEmpty;
1424 definition.className = "Type";
1425 definition.staticValues = Type_staticValues;
1426 definition.staticFunctions = Type_staticFunctions;
1427 definition.callAsFunction = &Type_callAsFunction;
1428 definition.callAsConstructor = &Type_callAsConstructor;
1429 definition.finalize = &CYFinalize;
1430 Type_privateData::Class_ = JSClassCreate(&definition);
1431
1432 definition = kJSClassDefinitionEmpty;
1433 definition.className = "Global";
1434 //definition.getProperty = &Global_getProperty;
1435 Global_ = JSClassCreate(&definition);
1436
1437 Array_s = JSStringCreateWithUTF8CString("Array");
1438 cy_s = JSStringCreateWithUTF8CString("$cy");
1439 length_s = JSStringCreateWithUTF8CString("length");
1440 message_s = JSStringCreateWithUTF8CString("message");
1441 name_s = JSStringCreateWithUTF8CString("name");
1442 pop_s = JSStringCreateWithUTF8CString("pop");
1443 prototype_s = JSStringCreateWithUTF8CString("prototype");
1444 push_s = JSStringCreateWithUTF8CString("push");
1445 splice_s = JSStringCreateWithUTF8CString("splice");
1446 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1447 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
1448 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
1449 toString_s = JSStringCreateWithUTF8CString("toString");
1450
1451 Result_ = JSStringCreateWithUTF8CString("_");
1452
1453 if (hooks_ != NULL && hooks_->Initialize != NULL)
1454 (*hooks_->Initialize)();
1455 }
1456
1457 void CYThrow(JSContextRef context, JSValueRef value) {
1458 if (value != NULL)
1459 throw CYJSError(context, value);
1460 }
1461
1462 const char *CYJSError::PoolCString(CYPool &pool) const {
1463 // XXX: this used to be CYPoolCString
1464 return CYPoolCCYON(pool, context_, value_);
1465 }
1466
1467 JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1468 // XXX: what if the context is different?
1469 return value_;
1470 }
1471
1472 JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1473 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1474
1475 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1476
1477 JSValueRef exception(NULL);
1478 JSValueRef value(JSObjectCallAsConstructor(context, Error, 1, arguments, &exception));
1479 CYThrow(context, exception);
1480
1481 return value;
1482 }
1483
1484 JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1485 return CYCastJSError(context, message_);
1486 }
1487
1488 CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1489 _assert(context != NULL);
1490
1491 CYPool pool;
1492
1493 va_list args;
1494 va_start(args, format);
1495 // XXX: there might be a beter way to think about this
1496 const char *message(pool.vsprintf(64, format, args));
1497 va_end(args);
1498
1499 value_ = CYCastJSError(context, message);
1500 }
1501
1502 JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1503 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1504 }
1505
1506 extern "C" void CYSetupContext(JSGlobalContextRef context) {
1507 JSValueRef exception(NULL);
1508
1509 CYInitializeDynamic();
1510
1511 JSObjectRef global(CYGetGlobalObject(context));
1512
1513 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1514 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1515
1516 /* Cache Globals {{{ */
1517 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1518 CYSetProperty(context, cy, CYJSString("Array"), Array);
1519
1520 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1521 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1522
1523 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1524 CYSetProperty(context, cy, CYJSString("Error"), Error);
1525
1526 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1527 CYSetProperty(context, cy, CYJSString("Function"), Function);
1528
1529 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1530 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1531
1532 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1533 CYSetProperty(context, cy, CYJSString("Object"), Object);
1534
1535 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1536 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1537
1538 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1539 CYSetProperty(context, cy, CYJSString("String"), String);
1540
1541 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1542 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
1543 /* }}} */
1544
1545 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1546 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1547
1548 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1549 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1550 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1551
1552 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1553 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1554 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1555
1556 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1557 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1558
1559 JSObjectRef all(JSObjectMake(context, All_, NULL));
1560 CYSetProperty(context, cycript, CYJSString("all"), all);
1561
1562 JSObjectRef alls(JSObjectCallAsConstructor(context, Array, 0, NULL, &exception));
1563 CYThrow(context, exception);
1564 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1565
1566 if (true) {
1567 JSObjectRef last(NULL), curr(global);
1568
1569 goto next; for (JSValueRef next;;) {
1570 if (JSValueIsNull(context, next))
1571 break;
1572 last = curr;
1573 curr = CYCastJSObject(context, next);
1574 next:
1575 next = JSObjectGetPrototype(context, curr);
1576 }
1577
1578 JSObjectSetPrototype(context, last, all);
1579 }
1580
1581 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
1582
1583 JSObjectRef System(JSObjectMake(context, NULL, NULL));
1584 CYSetProperty(context, cy, CYJSString("System"), System);
1585
1586 CYSetProperty(context, global, CYJSString("system"), System);
1587 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1588 //CYSetProperty(context, System, CYJSString("global"), global);
1589 CYSetProperty(context, System, CYJSString("print"), &System_print);
1590
1591 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
1592 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
1593
1594 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1595 (*hooks_->SetupContext)(context);
1596
1597 CYArrayPush(context, alls, cycript);
1598 }
1599
1600 JSGlobalContextRef CYGetJSContext() {
1601 CYInitializeDynamic();
1602
1603 static JSGlobalContextRef context_;
1604
1605 if (context_ == NULL) {
1606 context_ = JSGlobalContextCreate(Global_);
1607 CYSetupContext(context_);
1608 }
1609
1610 return context_;
1611 }