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