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