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