]> git.saurik.com Git - cycript.git/blame - Execute.cpp
Fix support for Bison >>2.3 by capitalizing path.
[cycript.git] / Execute.cpp
CommitLineData
b3378a02 1/* Cycript - Optimizing JavaScript Compiler/Runtime
8d7447c1 2 * Copyright (C) 2009-2012 Jay Freeman (saurik)
9cad30fa
JF
3*/
4
b3378a02 5/* GNU Lesser General Public License, Version 3 {{{ */
9cad30fa 6/*
b3378a02
JF
7 * Cycript is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
9cad30fa 11 *
b3378a02
JF
12 * Cycript is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
9cad30fa 16 *
b3378a02
JF
17 * You should have received a copy of the GNU Lesser General Public License
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>
25#include <iconv.h>
26
27#include "cycript.hpp"
28
29#include "sig/parse.hpp"
30#include "sig/ffi_type.hpp"
31
32#include "Pooling.hpp"
2f51d6ab 33#include "Execute.hpp"
9cad30fa
JF
34
35#include <sys/mman.h>
36
37#include <iostream>
38#include <ext/stdio_filebuf.h>
39#include <set>
40#include <map>
41#include <iomanip>
42#include <sstream>
43#include <cmath>
44
45#include "Parser.hpp"
46#include "Cycript.tab.hh"
47
48#include "Error.hpp"
49#include "JavaScript.hpp"
50#include "String.hpp"
51
9cad30fa
JF
52struct CYHooks *hooks_;
53
54/* JavaScript Properties {{{ */
55JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
56 JSValueRef exception(NULL);
57 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
58 CYThrow(context, exception);
59 return value;
60}
61
62JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
63 JSValueRef exception(NULL);
64 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
65 CYThrow(context, exception);
66 return value;
67}
68
69void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
70 JSValueRef exception(NULL);
71 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
72 CYThrow(context, exception);
73}
74
75void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
76 JSValueRef exception(NULL);
77 JSObjectSetProperty(context, object, name, value, attributes, &exception);
78 CYThrow(context, exception);
79}
80
81void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
82 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
83}
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;
102 JSValueRef exception(NULL);
103 JSStringRef string(JSValueToStringCopy(context, value, &exception));
104 CYThrow(context, exception);
105 return string;
106}
107
108static CYUTF16String CYCastUTF16String(JSStringRef value) {
109 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
110}
111
112CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
113 return CYPoolUTF8String(pool, CYCastUTF16String(value));
114}
115
116const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
117 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
118 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
119 return utf8.data;
120}
121
122const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
123 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
124}
125/* }}} */
126/* Index Offsets {{{ */
127size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
128 return CYGetIndex(CYPoolUTF8String(pool, context, value));
129}
130/* }}} */
131
132static JSClassRef All_;
133static JSClassRef Context_;
3f9ae37c 134JSClassRef Functor_;
9cad30fa
JF
135static JSClassRef Global_;
136static JSClassRef Pointer_;
137static JSClassRef Struct_;
138
139JSStringRef Array_s;
140JSStringRef cy_s;
141JSStringRef length_s;
142JSStringRef message_s;
143JSStringRef name_s;
144JSStringRef pop_s;
145JSStringRef prototype_s;
146JSStringRef push_s;
147JSStringRef splice_s;
148JSStringRef toCYON_s;
149JSStringRef toJSON_s;
20ded97a 150JSStringRef toPointer_s;
4cb8aa43 151JSStringRef toString_s;
9cad30fa
JF
152
153static JSStringRef Result_;
154
9cad30fa 155void CYFinalize(JSObjectRef object) {
1850a470
JF
156 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
157 if (--internal->count_ == 0)
158 delete internal;
9cad30fa
JF
159}
160
9cad30fa
JF
161void Structor_(apr_pool_t *pool, sig::Type *&type) {
162 if (
163 type->primitive == sig::pointer_P &&
164 type->data.data.type != NULL &&
165 type->data.data.type->primitive == sig::struct_P &&
1648ddb9 166 type->data.data.type->name != NULL &&
9cad30fa
JF
167 strcmp(type->data.data.type->name, "_objc_class") == 0
168 ) {
169 type->primitive = sig::typename_P;
170 type->data.data.type = NULL;
171 return;
172 }
173
174 if (type->primitive != sig::struct_P || type->name == NULL)
175 return;
176
2f51d6ab
JF
177 size_t length(strlen(type->name));
178 char keyed[length + 2];
179 memcpy(keyed + 1, type->name, length + 1);
180
181 static const char *modes = "34";
182 for (size_t i(0); i != 2; ++i) {
183 char mode(modes[i]);
184 keyed[0] = mode;
185
186 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
187 switch (mode) {
188 case '3':
189 sig::Parse(pool, &type->data.signature, entry->value_, &Structor_);
190 break;
191
192 case '4': {
193 sig::Signature signature;
194 sig::Parse(pool, &signature, entry->value_, &Structor_);
195 type = signature.elements[0].type;
196 } break;
197 }
9cad30fa
JF
198 }
199}
200
201JSClassRef Type_privateData::Class_;
202
203struct Context :
204 CYData
205{
206 JSGlobalContextRef context_;
207
208 Context(JSGlobalContextRef context) :
209 context_(context)
210 {
211 }
212};
213
214struct Pointer :
215 CYOwned
216{
217 Type_privateData *type_;
218 size_t length_;
219
220 Pointer(void *value, JSContextRef context, JSObjectRef owner, size_t length, sig::Type *type) :
221 CYOwned(value, context, owner),
222 type_(new(pool_) Type_privateData(type)),
223 length_(length)
224 {
225 }
226};
227
228struct Struct_privateData :
229 CYOwned
230{
231 Type_privateData *type_;
232
233 Struct_privateData(JSContextRef context, JSObjectRef owner) :
234 CYOwned(NULL, context, owner)
235 {
236 }
237};
238
14ec9e00 239typedef std::map<const char *, Type_privateData *, CYCStringLess> TypeMap;
9cad30fa
JF
240static TypeMap Types_;
241
242JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
243 Struct_privateData *internal(new Struct_privateData(context, owner));
244 apr_pool_t *pool(internal->pool_);
245 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
246 internal->type_ = typical;
247
248 if (owner != NULL)
249 internal->value_ = data;
250 else {
251 size_t size(typical->GetFFI()->size);
252 void *copy(apr_palloc(internal->pool_, size));
253 memcpy(copy, data, size);
254 internal->value_ = copy;
255 }
256
257 return JSObjectMake(context, Struct_, internal);
258}
259
9a98069f
JF
260static void *CYCastSymbol(const char *name) {
261 return dlsym(RTLD_DEFAULT, name);
262}
263
9cad30fa
JF
264JSValueRef CYCastJSValue(JSContextRef context, bool value) {
265 return JSValueMakeBoolean(context, value);
266}
267
268JSValueRef CYCastJSValue(JSContextRef context, double value) {
269 return JSValueMakeNumber(context, value);
270}
271
272#define CYCastJSValue_(Type_) \
273 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
274 return JSValueMakeNumber(context, static_cast<double>(value)); \
275 }
276
277CYCastJSValue_(int)
278CYCastJSValue_(unsigned int)
279CYCastJSValue_(long int)
280CYCastJSValue_(long unsigned int)
281CYCastJSValue_(long long int)
282CYCastJSValue_(long long unsigned int)
283
284JSValueRef CYJSUndefined(JSContextRef context) {
285 return JSValueMakeUndefined(context);
286}
287
288double CYCastDouble(JSContextRef context, JSValueRef value) {
289 JSValueRef exception(NULL);
290 double number(JSValueToNumber(context, value, &exception));
291 CYThrow(context, exception);
292 return number;
293}
294
295bool CYCastBool(JSContextRef context, JSValueRef value) {
296 return JSValueToBoolean(context, value);
297}
298
299JSValueRef CYJSNull(JSContextRef context) {
300 return JSValueMakeNull(context);
301}
302
303JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
304 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
305}
306
307JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
308 return CYCastJSValue(context, CYJSString(value));
309}
310
311JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
312 JSValueRef exception(NULL);
313 JSObjectRef object(JSValueToObject(context, value, &exception));
314 CYThrow(context, exception);
315 return object;
316}
317
318JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
319 JSValueRef exception(NULL);
320 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
321 CYThrow(context, exception);
322 return value;
323}
324
325bool CYIsCallable(JSContextRef context, JSValueRef value) {
326 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
327}
328
329static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
330 if (count == 0)
331 printf("\n");
332 else {
333 CYPool pool;
334 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
335 }
336
337 return CYJSUndefined(context);
55c6d6ab 338} CYCatch(NULL) }
9cad30fa
JF
339
340static size_t Nonce_(0);
341
342static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
343 CYPool pool;
344 const char *name(apr_psprintf(pool, "%s%"APR_SIZE_T_FMT"", CYPoolCString(pool, context, arguments[0]), Nonce_++));
345 return CYCastJSValue(context, name);
346}
347
348static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
349 JSGarbageCollect(context);
350 return CYJSUndefined(context);
351}
352
353const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
354 switch (JSType type = JSValueGetType(context, value)) {
355 case kJSTypeUndefined:
356 return "undefined";
357 case kJSTypeNull:
358 return "null";
359 case kJSTypeBoolean:
360 return CYCastBool(context, value) ? "true" : "false";
361
362 case kJSTypeNumber: {
363 std::ostringstream str;
364 CYNumerify(str, CYCastDouble(context, value));
365 std::string value(str.str());
366 return apr_pstrmemdup(pool, value.c_str(), value.size());
367 } break;
368
369 case kJSTypeString: {
370 std::ostringstream str;
371 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
372 CYStringify(str, string.data, string.size);
373 std::string value(str.str());
374 return apr_pstrmemdup(pool, value.c_str(), value.size());
375 } break;
376
377 case kJSTypeObject:
378 return CYPoolCCYON(pool, context, (JSObjectRef) value);
379 default:
380 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
381 }
55c6d6ab 382} CYCatch(NULL) }
9cad30fa
JF
383
384const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
385 JSValueRef exception(NULL);
386 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
387 CYThrow(context, exception);
388 return cyon;
389}
390
391const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
392 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
393 if (CYIsCallable(context, toCYON)) {
394 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
395 _assert(value != NULL);
396 return CYPoolCString(pool, context, value);
397 }
398
399 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
400 if (CYIsCallable(context, toJSON)) {
401 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
402 JSValueRef exception(NULL);
403 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
404 CYThrow(context, exception);
405 return cyon;
406 }
407
005b2e9f
JF
408 if (JSObjectIsFunction(context, object)) {
409 JSValueRef toString(CYGetProperty(context, object, toString_s));
410 if (CYIsCallable(context, toString)) {
411 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
412 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
413 _assert(value != NULL);
414 return CYPoolCString(pool, context, value);
415 }
416 }
417
9cad30fa
JF
418 std::ostringstream str;
419
420 str << '{';
421
422 // XXX: this is, sadly, going to leak
423 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
424
425 bool comma(false);
426
427 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
428 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
429 JSValueRef value(CYGetProperty(context, object, name));
430
431 if (comma)
432 str << ',';
433 else
434 comma = true;
435
436 CYUTF8String string(CYPoolUTF8String(pool, context, name));
437 if (CYIsKey(string))
438 str << string.data;
439 else
440 CYStringify(str, string.data, string.size);
441
442 str << ':' << CYPoolCCYON(pool, context, value);
443 }
444
445 str << '}';
446
447 JSPropertyNameArrayRelease(names);
448
449 std::string string(str.str());
450 return apr_pstrmemdup(pool, string.c_str(), string.size());
451}
452
453static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
454 CYPool pool;
455 std::ostringstream str;
456
457 str << '[';
458
459 JSValueRef length(CYGetProperty(context, _this, length_s));
460 bool comma(false);
461
462 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
463 JSValueRef value(CYGetProperty(context, _this, index));
464
465 if (comma)
466 str << ',';
467 else
468 comma = true;
469
470 if (!JSValueIsUndefined(context, value))
471 str << CYPoolCCYON(pool, context, value);
472 else {
473 str << ',';
474 comma = false;
475 }
476 }
477
478 str << ']';
479
480 std::string value(str.str());
481 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
55c6d6ab 482} CYCatch(NULL) }
9cad30fa 483
4cb8aa43
JF
484static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
485 CYPool pool;
486 std::ostringstream str;
487
488 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
489 CYStringify(str, string.data, string.size);
490
491 std::string value(str.str());
492 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
55c6d6ab 493} CYCatch(NULL) }
4cb8aa43 494
9cad30fa
JF
495JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
496 Pointer *internal(new Pointer(pointer, context, owner, length, type));
497 return JSObjectMake(context, Pointer_, internal);
498}
499
9a98069f
JF
500static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
501 return JSObjectMake(context, Functor_, new cy::Functor(type, function));
502}
1850a470 503
9a98069f
JF
504static JSObjectRef CYMakeFunctor(JSContextRef context, const char *symbol, const char *type, void **cache) {
505 cy::Functor *internal;
506 if (*cache != NULL)
1850a470 507 internal = reinterpret_cast<cy::Functor *>(*cache);
9a98069f
JF
508 else {
509 void (*function)()(reinterpret_cast<void (*)()>(CYCastSymbol(symbol)));
510 if (function == NULL)
511 return NULL;
1850a470 512
9a98069f
JF
513 internal = new cy::Functor(type, function);
514 *cache = internal;
1850a470
JF
515 }
516
9a98069f 517 ++internal->count_;
9cad30fa
JF
518 return JSObjectMake(context, Functor_, internal);
519}
520
521static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
522 return CYGetOffset(CYPoolCString(pool, context, value), index);
523}
524
525void *CYCastPointer_(JSContextRef context, JSValueRef value) {
526 switch (JSValueGetType(context, value)) {
527 case kJSTypeNull:
528 return NULL;
20ded97a
JF
529 case kJSTypeObject: {
530 JSObjectRef object((JSObjectRef) value);
9cad30fa 531 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
20ded97a 532 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
9cad30fa 533 return internal->value_;
20ded97a
JF
534 }
535 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
536 if (CYIsCallable(context, toPointer)) {
537 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
538 _assert(value != NULL);
539 return CYCastPointer_(context, value);
540 }
541 } default:
9cad30fa
JF
542 double number(CYCastDouble(context, value));
543 if (std::isnan(number))
544 throw CYJSError(context, "cannot convert value to pointer");
545 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
546 }
547}
548
549void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
550 switch (type->primitive) {
551 case sig::boolean_P:
552 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
553 break;
554
555#define CYPoolFFI_(primitive, native) \
556 case sig::primitive ## _P: \
557 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
558 break;
559
560 CYPoolFFI_(uchar, unsigned char)
561 CYPoolFFI_(char, char)
562 CYPoolFFI_(ushort, unsigned short)
563 CYPoolFFI_(short, short)
564 CYPoolFFI_(ulong, unsigned long)
565 CYPoolFFI_(long, long)
566 CYPoolFFI_(uint, unsigned int)
567 CYPoolFFI_(int, int)
568 CYPoolFFI_(ulonglong, unsigned long long)
569 CYPoolFFI_(longlong, long long)
570 CYPoolFFI_(float, float)
571 CYPoolFFI_(double, double)
572
573 case sig::array_P: {
574 uint8_t *base(reinterpret_cast<uint8_t *>(data));
575 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
576 for (size_t index(0); index != type->data.data.size; ++index) {
577 ffi_type *field(ffi->elements[index]);
578
579 JSValueRef rhs;
580 if (aggregate == NULL)
581 rhs = value;
582 else {
583 rhs = CYGetProperty(context, aggregate, index);
584 if (JSValueIsUndefined(context, rhs))
585 throw CYJSError(context, "unable to extract array value");
586 }
587
588 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
589 // XXX: alignment?
590 base += field->size;
591 }
592 } break;
593
594 case sig::pointer_P:
595 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
596 break;
597
598 case sig::string_P:
599 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
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
764 JSValueRef exception(NULL);
765 bool function(JSValueIsInstanceOfConstructor(context, value, Function, &exception));
766 CYThrow(context, exception);
767
768 if (function) {
769 JSObjectRef function(CYCastJSObject(context, value));
770 return CYMakeFunctor(context, function, type);
771 } else {
772 void (*function)()(CYCastPointer<void (*)()>(context, value));
773 return CYMakeFunctor(context, function, type);
774 }
775}
776
777static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
778 Type_privateData *typical(internal->type_);
779 sig::Type *type(typical->type_);
780 if (type == NULL)
781 return false;
782
783 const char *name(CYPoolCString(pool, context, property));
784 size_t length(strlen(name));
785 double number(CYCastDouble(name, length));
786
787 size_t count(type->data.signature.count);
788
789 if (std::isnan(number)) {
790 if (property == NULL)
791 return false;
792
793 sig::Element *elements(type->data.signature.elements);
794
795 for (size_t local(0); local != count; ++local) {
796 sig::Element *element(&elements[local]);
797 if (element->name != NULL && strcmp(name, element->name) == 0) {
798 index = local;
799 goto base;
800 }
801 }
802
803 return false;
804 } else {
805 index = static_cast<ssize_t>(number);
806 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
807 return false;
808 }
809
810 base:
811 ffi_type **elements(typical->GetFFI()->elements);
812
813 base = reinterpret_cast<uint8_t *>(internal->value_);
814 for (ssize_t local(0); local != index; ++local)
815 base += elements[local]->size;
816
817 return true;
818}
819
820static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
821 CYPool pool;
822 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
823
824 if (JSStringIsEqual(property, length_s))
825 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
826
827 Type_privateData *typical(internal->type_);
828
829 if (typical->type_ == NULL)
830 return NULL;
831
832 ssize_t offset;
833 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
834 offset = 0;
835 else if (!CYGetOffset(pool, context, property, offset))
836 return NULL;
837
838 ffi_type *ffi(typical->GetFFI());
839
840 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
841 base += ffi->size * offset;
842
843 JSObjectRef owner(internal->GetOwner() ?: object);
844 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
55c6d6ab 845} CYCatch(NULL) }
9cad30fa
JF
846
847static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
848 CYPool pool;
849 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
850 Type_privateData *typical(internal->type_);
851
852 if (typical->type_ == NULL)
55c6d6ab 853 return false;
9cad30fa
JF
854
855 ssize_t offset;
856 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
857 offset = 0;
858 else if (!CYGetOffset(pool, context, property, offset))
55c6d6ab 859 return false;
9cad30fa
JF
860
861 ffi_type *ffi(typical->GetFFI());
862
863 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
864 base += ffi->size * offset;
865
866 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
867 return true;
55c6d6ab 868} CYCatch(false) }
9cad30fa
JF
869
870static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
871 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
872 Type_privateData *typical(internal->type_);
873 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
874}
875
876static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
877 CYPool pool;
878 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
879 Type_privateData *typical(internal->type_);
880
881 ssize_t index;
882 uint8_t *base;
883
884 if (!Index_(pool, context, internal, property, index, base))
885 return NULL;
886
887 JSObjectRef owner(internal->GetOwner() ?: object);
888
889 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
55c6d6ab 890} CYCatch(NULL) }
9cad30fa
JF
891
892static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
893 CYPool pool;
894 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
895 Type_privateData *typical(internal->type_);
896
897 ssize_t index;
898 uint8_t *base;
899
900 if (!Index_(pool, context, internal, property, index, base))
901 return false;
902
903 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
904 return true;
55c6d6ab 905} CYCatch(false) }
9cad30fa
JF
906
907static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
908 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
909 Type_privateData *typical(internal->type_);
910 sig::Type *type(typical->type_);
911
912 if (type == NULL)
913 return;
914
915 size_t count(type->data.signature.count);
916 sig::Element *elements(type->data.signature.elements);
917
918 char number[32];
919
920 for (size_t index(0); index != count; ++index) {
921 const char *name;
922 name = elements[index].name;
923
924 if (name == NULL) {
925 sprintf(number, "%zu", index);
926 name = number;
927 }
928
929 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
930 }
931}
932
933JSValueRef CYCallFunction(apr_pool_t *pool, JSContextRef context, size_t setups, void *setup[], size_t count, const JSValueRef arguments[], bool initialize, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { CYTry {
934 if (setups + count != signature->count - 1)
935 throw CYJSError(context, "incorrect number of arguments to ffi function");
936
937 size_t size(setups + count);
938 void *values[size];
939 memcpy(values, setup, sizeof(void *) * setups);
940
941 for (size_t index(setups); index != size; ++index) {
942 sig::Element *element(&signature->elements[index + 1]);
943 ffi_type *ffi(cif->arg_types[index]);
944 // XXX: alignment?
945 values[index] = new(pool) uint8_t[ffi->size];
946 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
947 }
948
949 uint8_t value[cif->rtype->size];
950
951 if (hooks_ != NULL && hooks_->CallFunction != NULL)
952 (*hooks_->CallFunction)(context, cif, function, value, values);
953 else
954 ffi_call(cif, function, value, values);
955
956 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
55c6d6ab 957} CYCatch(NULL) }
9cad30fa
JF
958
959static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
960 CYPool pool;
961 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
962 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
963}
964
8a23fb2e 965JSObjectRef CYMakeType(JSContextRef context, const char *type) {
9cad30fa
JF
966 Type_privateData *internal(new Type_privateData(type));
967 return JSObjectMake(context, Type_privateData::Class_, internal);
968}
969
8a23fb2e 970JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
9cad30fa
JF
971 Type_privateData *internal(new Type_privateData(type));
972 return JSObjectMake(context, Type_privateData::Class_, internal);
973}
974
9cad30fa
JF
975static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
976 JSObjectRef global(CYGetGlobalObject(context));
977 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
26ef7a82
JF
978 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
979
980 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
981 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
982 if (JSValueRef value = CYGetProperty(context, space, property))
983 if (!JSValueIsUndefined(context, value))
984 return value;
9cad30fa
JF
985
986 CYPool pool;
987 CYUTF8String name(CYPoolUTF8String(pool, context, property));
988
2f51d6ab
JF
989 size_t length(name.size);
990 char keyed[length + 2];
991 memcpy(keyed + 1, name.data, length + 1);
992
993 static const char *modes = "0124";
994 for (size_t i(0); i != 4; ++i) {
995 char mode(modes[i]);
996 keyed[0] = mode;
997
998 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
999 switch (mode) {
1000 case '0':
1001 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
1002
1003 case '1':
9a98069f 1004 return CYMakeFunctor(context, name.data, entry->value_, &entry->cache_);
2f51d6ab
JF
1005
1006 case '2':
1007 if (void *symbol = CYCastSymbol(name.data)) {
1008 // XXX: this is horrendously inefficient
1009 sig::Signature signature;
1010 sig::Parse(pool, &signature, entry->value_, &Structor_);
1011 ffi_cif cif;
1012 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1013 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1014 } else return NULL;
1015
1016 // XXX: implement case 3
1017 case '4':
1018 return CYMakeType(context, entry->value_);
1019 }
9cad30fa
JF
1020 }
1021
2f51d6ab 1022 return NULL;
55c6d6ab 1023} CYCatch(NULL) }
9cad30fa 1024
26ef7a82
JF
1025static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1026 JSObjectRef global(CYGetGlobalObject(context));
1027 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1028 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1029
1030 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1031 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1032 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1033 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1034 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1035 JSPropertyNameArrayRelease(subset);
1036 }
1037}
1038
9cad30fa
JF
1039static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1040 if (count != 2)
5d422750 1041 throw CYJSError(context, "incorrect number of arguments to Pointer constructor");
9cad30fa
JF
1042
1043 CYPool pool;
1044
1045 void *value(CYCastPointer<void *>(context, arguments[0]));
1046 const char *type(CYPoolCString(pool, context, arguments[1]));
1047
1048 sig::Signature signature;
1049 sig::Parse(pool, &signature, type, &Structor_);
1050
1051 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
55c6d6ab 1052} CYCatch(NULL) }
9cad30fa
JF
1053
1054static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1055 if (count != 1)
1056 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1057 CYPool pool;
1058 const char *type(CYPoolCString(pool, context, arguments[0]));
1059 return CYMakeType(context, type);
55c6d6ab 1060} CYCatch(NULL) }
9cad30fa 1061
85e90410
JF
1062static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1063 if (count != 1)
1064 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1065 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1066
1067 CYPool pool;
1068 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1069 if (index == _not(size_t))
1070 throw CYJSError(context, "invalid array size used with Type.arrayOf");
9cad30fa
JF
1071
1072 sig::Type type;
85e90410
JF
1073 type.name = NULL;
1074 type.flags = 0;
9cad30fa 1075
85e90410
JF
1076 type.primitive = sig::array_P;
1077 type.data.data.type = internal->type_;
1078 type.data.data.size = index;
1079
1080 return CYMakeType(context, &type);
55c6d6ab 1081} CYCatch(NULL) }
9cad30fa 1082
fbc17268
JF
1083static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1084 if (count != 0)
1085 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1086 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1087
1088 sig::Type type(*internal->type_);
1089 type.flags |= JOC_TYPE_CONST;
1090 return CYMakeType(context, &type);
55c6d6ab 1091} CYCatch(NULL) }
fbc17268 1092
85e90410
JF
1093static JSValueRef Type_callAsFunction_pointerTo(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.pointerTo");
1096 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1097
1098 sig::Type type;
9cad30fa
JF
1099 type.name = NULL;
1100 type.flags = 0;
1101
85e90410 1102 type.primitive = sig::pointer_P;
9cad30fa 1103 type.data.data.type = internal->type_;
85e90410 1104 type.data.data.size = 0;
9cad30fa
JF
1105
1106 return CYMakeType(context, &type);
55c6d6ab 1107} CYCatch(NULL) }
9cad30fa 1108
21d5f610
JF
1109static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1110 if (count != 1)
1111 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1112 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1113
1114 CYPool pool;
1115 const char *name(CYPoolCString(pool, context, arguments[0]));
1116
1117 sig::Type type(*internal->type_);
1118 type.name = name;
1119 return CYMakeType(context, &type);
55c6d6ab 1120} CYCatch(NULL) }
21d5f610 1121
9cad30fa 1122static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9cad30fa
JF
1123 if (count != 1)
1124 throw CYJSError(context, "incorrect number of arguments to type cast function");
1c3dd2c3
JF
1125 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1126
9cad30fa
JF
1127 sig::Type *type(internal->type_);
1128 ffi_type *ffi(internal->GetFFI());
1129 // XXX: alignment?
1130 uint8_t value[ffi->size];
1131 CYPool pool;
1132 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1133 return CYFromFFI(context, type, ffi, value);
55c6d6ab 1134} CYCatch(NULL) }
9cad30fa
JF
1135
1136static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1137 if (count != 0)
767e8255 1138 throw CYJSError(context, "incorrect number of arguments to Type allocator");
9cad30fa
JF
1139 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1140
1141 sig::Type *type(internal->type_);
1142 size_t length;
1143
1144 if (type->primitive != sig::array_P)
1145 length = _not(size_t);
1146 else {
1147 length = type->data.data.size;
1148 type = type->data.data.type;
1149 }
1150
1151 void *value(malloc(internal->GetFFI()->size));
1152 return CYMakePointer(context, value, length, type, NULL, NULL);
55c6d6ab 1153} CYCatch(NULL) }
9cad30fa
JF
1154
1155static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1156 if (count != 2)
1157 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1158 CYPool pool;
1159 const char *type(CYPoolCString(pool, context, arguments[1]));
1160 return CYMakeFunctor(context, arguments[0], type);
55c6d6ab 1161} CYCatch(NULL) }
9cad30fa
JF
1162
1163static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1164 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1165 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
55c6d6ab 1166} CYCatch(NULL) }
9cad30fa
JF
1167
1168static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1169 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1170}
1171
1172static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1173 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1174 char string[32];
1175 sprintf(string, "%p", internal->value_);
1176 return CYCastJSValue(context, string);
55c6d6ab 1177} CYCatch(NULL) }
9cad30fa
JF
1178
1179static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1180 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1181 if (internal->length_ != _not(size_t)) {
3b1534c0 1182 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array_prototype")));
9cad30fa
JF
1183 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1184 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1185 } else {
1186 char string[32];
1187 sprintf(string, "%p", internal->value_);
1188 return CYCastJSValue(context, string);
1189 }
55c6d6ab 1190} CYCatch(NULL) }
9cad30fa 1191
74e8c566
JF
1192static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1193 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1194 return CYCastJSValue(context, internal->GetFFI()->alignment);
1195}
1196
21d5f610
JF
1197static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1198 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1199 return CYCastJSValue(context, internal->type_->name);
1200}
1201
74e8c566
JF
1202static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1203 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1204 return CYCastJSValue(context, internal->GetFFI()->size);
1205}
1206
9cad30fa
JF
1207static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1208 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1209 CYPool pool;
1210 const char *type(sig::Unparse(pool, internal->type_));
1211 return CYCastJSValue(context, CYJSString(type));
55c6d6ab 1212} CYCatch(NULL) }
9cad30fa
JF
1213
1214static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1215 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1216 CYPool pool;
1217 const char *type(sig::Unparse(pool, internal->type_));
4a8523e5
JF
1218 std::ostringstream str;
1219 CYStringify(str, type, strlen(type));
1220 char *cyon(apr_pstrcat(pool, "new Type(", str.str().c_str(), ")", NULL));
9cad30fa 1221 return CYCastJSValue(context, CYJSString(cyon));
55c6d6ab 1222} CYCatch(NULL) }
9cad30fa
JF
1223
1224static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1225 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1226}
1227
1228static JSStaticFunction Pointer_staticFunctions[4] = {
1229 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1230 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1231 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1232 {NULL, NULL, 0}
1233};
1234
1235static JSStaticFunction Struct_staticFunctions[2] = {
1236 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1237 {NULL, NULL, 0}
1238};
1239
1240static JSStaticFunction Functor_staticFunctions[4] = {
1241 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1242 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1243 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1244 {NULL, NULL, 0}
1245};
1246
1247namespace cy {
1248 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1249}
1250
21d5f610 1251static JSStaticValue Type_staticValues[4] = {
74e8c566 1252 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1253 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
74e8c566
JF
1254 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1255 {NULL, NULL, NULL, 0}
1256};
1257
21d5f610 1258static JSStaticFunction Type_staticFunctions[8] = {
85e90410 1259 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
fbc17268 1260 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
85e90410 1261 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1262 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9cad30fa
JF
1263 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1264 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1265 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1266 {NULL, NULL, 0}
1267};
1268
1269static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1270
1271void CYSetArgs(int argc, const char *argv[]) {
1272 JSContextRef context(CYGetJSContext());
1273 JSValueRef args[argc];
1274 for (int i(0); i != argc; ++i)
1275 args[i] = CYCastJSValue(context, argv[i]);
1276
1277 JSObjectRef array;
1278 if (JSObjectMakeArray$ != NULL) {
1279 JSValueRef exception(NULL);
1280 array = (*JSObjectMakeArray$)(context, argc, args, &exception);
1281 CYThrow(context, exception);
1282 } else {
1283 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1284 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1285 array = CYCastJSObject(context, value);
1286 }
1287
1288 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1289 CYSetProperty(context, System, CYJSString("args"), array);
1290}
1291
1292JSObjectRef CYGetGlobalObject(JSContextRef context) {
1293 return JSContextGetGlobalObject(context);
1294}
1295
0ced2e47 1296const char *CYExecute(apr_pool_t *pool, CYUTF8String code) {
9cad30fa
JF
1297 JSContextRef context(CYGetJSContext());
1298 JSValueRef exception(NULL), result;
1299
1300 void *handle;
1301 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1302 handle = (*hooks_->ExecuteStart)(context);
1303 else
1304 handle = NULL;
1305
1306 const char *json;
1307
1308 try {
1309 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1310 } catch (const char *error) {
1311 return error;
1312 }
1313
9cc84a5a
JF
1314 if (exception != NULL) error:
1315 return CYPoolCString(pool, context, CYJSString(context, exception));
9cad30fa
JF
1316
1317 if (JSValueIsUndefined(context, result))
1318 return NULL;
1319
1320 try {
1321 json = CYPoolCCYON(pool, context, result, &exception);
1322 } catch (const char *error) {
1323 return error;
1324 }
1325
1326 if (exception != NULL)
1327 goto error;
1328
1329 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1330
1331 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1332 (*hooks_->ExecuteEnd)(context, handle);
1333 return json;
1334}
1335
1336extern "C" void CydgetSetupContext(JSGlobalContextRef context) {
1337 CYSetupContext(context);
1338}
1339
09eee478
JF
1340static bool initialized_ = false;
1341
9cad30fa 1342void CYInitializeDynamic() {
09eee478
JF
1343 if (!initialized_)
1344 initialized_ = true;
1345 else return;
1346
9cad30fa
JF
1347 CYInitializeStatic();
1348
9cad30fa
JF
1349 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1350
1351 JSClassDefinition definition;
1352
1353 definition = kJSClassDefinitionEmpty;
1354 definition.className = "All";
1355 definition.getProperty = &All_getProperty;
26ef7a82 1356 definition.getPropertyNames = &All_getPropertyNames;
9cad30fa
JF
1357 All_ = JSClassCreate(&definition);
1358
1359 definition = kJSClassDefinitionEmpty;
1360 definition.className = "Context";
1361 definition.finalize = &CYFinalize;
1362 Context_ = JSClassCreate(&definition);
1363
1364 definition = kJSClassDefinitionEmpty;
1365 definition.className = "Functor";
1366 definition.staticFunctions = cy::Functor::StaticFunctions;
1367 definition.callAsFunction = &Functor_callAsFunction;
1368 definition.finalize = &CYFinalize;
1369 Functor_ = JSClassCreate(&definition);
1370
1371 definition = kJSClassDefinitionEmpty;
1372 definition.className = "Pointer";
1373 definition.staticFunctions = Pointer_staticFunctions;
1374 definition.getProperty = &Pointer_getProperty;
1375 definition.setProperty = &Pointer_setProperty;
1376 definition.finalize = &CYFinalize;
1377 Pointer_ = JSClassCreate(&definition);
1378
1379 definition = kJSClassDefinitionEmpty;
1380 definition.className = "Struct";
1381 definition.staticFunctions = Struct_staticFunctions;
1382 definition.getProperty = &Struct_getProperty;
1383 definition.setProperty = &Struct_setProperty;
1384 definition.getPropertyNames = &Struct_getPropertyNames;
1385 definition.finalize = &CYFinalize;
1386 Struct_ = JSClassCreate(&definition);
1387
1388 definition = kJSClassDefinitionEmpty;
1389 definition.className = "Type";
74e8c566 1390 definition.staticValues = Type_staticValues;
9cad30fa 1391 definition.staticFunctions = Type_staticFunctions;
9cad30fa
JF
1392 definition.callAsFunction = &Type_callAsFunction;
1393 definition.callAsConstructor = &Type_callAsConstructor;
1394 definition.finalize = &CYFinalize;
1395 Type_privateData::Class_ = JSClassCreate(&definition);
1396
1397 definition = kJSClassDefinitionEmpty;
56a66df3 1398 definition.className = "Global";
9cad30fa
JF
1399 //definition.getProperty = &Global_getProperty;
1400 Global_ = JSClassCreate(&definition);
1401
1402 Array_s = JSStringCreateWithUTF8CString("Array");
1403 cy_s = JSStringCreateWithUTF8CString("$cy");
1404 length_s = JSStringCreateWithUTF8CString("length");
1405 message_s = JSStringCreateWithUTF8CString("message");
1406 name_s = JSStringCreateWithUTF8CString("name");
1407 pop_s = JSStringCreateWithUTF8CString("pop");
1408 prototype_s = JSStringCreateWithUTF8CString("prototype");
1409 push_s = JSStringCreateWithUTF8CString("push");
1410 splice_s = JSStringCreateWithUTF8CString("splice");
1411 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1412 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
20ded97a 1413 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
4cb8aa43 1414 toString_s = JSStringCreateWithUTF8CString("toString");
9cad30fa
JF
1415
1416 Result_ = JSStringCreateWithUTF8CString("_");
1417
1418 if (hooks_ != NULL && hooks_->Initialize != NULL)
1419 (*hooks_->Initialize)();
1420}
1421
1422void CYThrow(JSContextRef context, JSValueRef value) {
1423 if (value != NULL)
1424 throw CYJSError(context, value);
1425}
1426
1427const char *CYJSError::PoolCString(apr_pool_t *pool) const {
1428 // XXX: this used to be CYPoolCString
1429 return CYPoolCCYON(pool, context_, value_);
1430}
1431
1432JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1433 // XXX: what if the context is different?
1434 return value_;
1435}
1436
1437JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1438 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1439
1440 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1441
1442 JSValueRef exception(NULL);
1443 JSValueRef value(JSObjectCallAsConstructor(context, Error, 1, arguments, &exception));
1444 CYThrow(context, exception);
1445
1446 return value;
1447}
1448
1449JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1450 return CYCastJSError(context, message_);
1451}
1452
1453CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1454 _assert(context != NULL);
1455
1456 CYPool pool;
1457
1458 va_list args;
1459 va_start(args, format);
1460 const char *message(apr_pvsprintf(pool, format, args));
1461 va_end(args);
1462
1463 value_ = CYCastJSError(context, message);
1464}
1465
1466JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1467 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1468}
1469
1470extern "C" void CYSetupContext(JSGlobalContextRef context) {
26ef7a82
JF
1471 JSValueRef exception(NULL);
1472
9cad30fa
JF
1473 CYInitializeDynamic();
1474
1475 JSObjectRef global(CYGetGlobalObject(context));
1476
1477 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1478 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1479
1480/* Cache Globals {{{ */
1481 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1482 CYSetProperty(context, cy, CYJSString("Array"), Array);
1483
1484 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1485 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1486
1487 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1488 CYSetProperty(context, cy, CYJSString("Error"), Error);
1489
1490 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1491 CYSetProperty(context, cy, CYJSString("Function"), Function);
1492
1493 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1494 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1495
1496 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1497 CYSetProperty(context, cy, CYJSString("Object"), Object);
1498
1499 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1500 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1501
1502 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1503 CYSetProperty(context, cy, CYJSString("String"), String);
4cb8aa43
JF
1504
1505 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1506 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
9cad30fa
JF
1507/* }}} */
1508
1509 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
4cb8aa43 1510 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1511
1512 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1513 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1514 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1515
1516 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1517 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1518 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1519
1520 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
b63701b2 1521 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
9cad30fa
JF
1522
1523 JSObjectRef all(JSObjectMake(context, All_, NULL));
1524 CYSetProperty(context, cycript, CYJSString("all"), all);
1525
26ef7a82
JF
1526 JSObjectRef alls(JSObjectCallAsConstructor(context, Array, 0, NULL, &exception));
1527 CYThrow(context, exception);
1528 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1529
56a66df3
JF
1530 if (true) {
1531 JSObjectRef last(NULL), curr(global);
9cad30fa 1532
56a66df3
JF
1533 goto next; for (JSValueRef next;;) {
1534 if (JSValueIsNull(context, next))
1535 break;
1536 last = curr;
1537 curr = CYCastJSObject(context, next);
1538 next:
1539 next = JSObjectGetPrototype(context, curr);
1540 }
9cad30fa 1541
56a66df3
JF
1542 JSObjectSetPrototype(context, last, all);
1543 }
9cad30fa 1544
56a66df3 1545 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1546
1547 JSObjectRef System(JSObjectMake(context, NULL, NULL));
cdc80ff2 1548 CYSetProperty(context, cy, CYJSString("System"), System);
9cad30fa
JF
1549
1550 CYSetProperty(context, global, CYJSString("system"), System);
1551 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1552 //CYSetProperty(context, System, CYJSString("global"), global);
1553 CYSetProperty(context, System, CYJSString("print"), &System_print);
1554
a621ae76
JF
1555 if (CYBridgeEntry *entry = CYBridgeHash("1dlerror", 8))
1556 entry->cache_ = new cy::Functor(entry->value_, reinterpret_cast<void (*)()>(&dlerror));
1557
9cad30fa
JF
1558 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1559 (*hooks_->SetupContext)(context);
26ef7a82
JF
1560
1561 CYArrayPush(context, alls, cycript);
9cad30fa
JF
1562}
1563
1564JSGlobalContextRef CYGetJSContext() {
1565 CYInitializeDynamic();
1566
1567 static JSGlobalContextRef context_;
1568
1569 if (context_ == NULL) {
1570 context_ = JSGlobalContextCreate(Global_);
1571 CYSetupContext(context_);
1572 }
1573
1574 return context_;
1575}