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