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