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