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