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