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