]> git.saurik.com Git - cycript.git/blame - Execute.cpp
Allow Type objects to have associated identifiers.
[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_;
134static JSClassRef Functor_;
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
260JSValueRef CYCastJSValue(JSContextRef context, bool value) {
261 return JSValueMakeBoolean(context, value);
262}
263
264JSValueRef CYCastJSValue(JSContextRef context, double value) {
265 return JSValueMakeNumber(context, value);
266}
267
268#define CYCastJSValue_(Type_) \
269 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
270 return JSValueMakeNumber(context, static_cast<double>(value)); \
271 }
272
273CYCastJSValue_(int)
274CYCastJSValue_(unsigned int)
275CYCastJSValue_(long int)
276CYCastJSValue_(long unsigned int)
277CYCastJSValue_(long long int)
278CYCastJSValue_(long long unsigned int)
279
280JSValueRef CYJSUndefined(JSContextRef context) {
281 return JSValueMakeUndefined(context);
282}
283
284double CYCastDouble(JSContextRef context, JSValueRef value) {
285 JSValueRef exception(NULL);
286 double number(JSValueToNumber(context, value, &exception));
287 CYThrow(context, exception);
288 return number;
289}
290
291bool CYCastBool(JSContextRef context, JSValueRef value) {
292 return JSValueToBoolean(context, value);
293}
294
295JSValueRef CYJSNull(JSContextRef context) {
296 return JSValueMakeNull(context);
297}
298
299JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
300 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
301}
302
303JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
304 return CYCastJSValue(context, CYJSString(value));
305}
306
307JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
308 JSValueRef exception(NULL);
309 JSObjectRef object(JSValueToObject(context, value, &exception));
310 CYThrow(context, exception);
311 return object;
312}
313
314JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
315 JSValueRef exception(NULL);
316 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
317 CYThrow(context, exception);
318 return value;
319}
320
321bool CYIsCallable(JSContextRef context, JSValueRef value) {
322 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
323}
324
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);
334} CYCatch }
335
336static size_t Nonce_(0);
337
338static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
339 CYPool pool;
340 const char *name(apr_psprintf(pool, "%s%"APR_SIZE_T_FMT"", CYPoolCString(pool, context, arguments[0]), Nonce_++));
341 return CYCastJSValue(context, name);
342}
343
344static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
345 JSGarbageCollect(context);
346 return CYJSUndefined(context);
347}
348
349const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
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());
362 return apr_pstrmemdup(pool, value.c_str(), value.size());
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());
370 return apr_pstrmemdup(pool, value.c_str(), value.size());
371 } break;
372
373 case kJSTypeObject:
374 return CYPoolCCYON(pool, context, (JSObjectRef) value);
375 default:
376 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
377 }
378} CYCatch }
379
380const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
381 JSValueRef exception(NULL);
382 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
383 CYThrow(context, exception);
384 return cyon;
385}
386
387const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
388 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
389 if (CYIsCallable(context, toCYON)) {
390 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
391 _assert(value != NULL);
392 return CYPoolCString(pool, context, value);
393 }
394
395 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
396 if (CYIsCallable(context, toJSON)) {
397 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
398 JSValueRef exception(NULL);
399 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
400 CYThrow(context, exception);
401 return cyon;
402 }
403
005b2e9f
JF
404 if (JSObjectIsFunction(context, object)) {
405 JSValueRef toString(CYGetProperty(context, object, toString_s));
406 if (CYIsCallable(context, toString)) {
407 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
408 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toString, object, 1, arguments));
409 _assert(value != NULL);
410 return CYPoolCString(pool, context, value);
411 }
412 }
413
9cad30fa
JF
414 std::ostringstream str;
415
416 str << '{';
417
418 // XXX: this is, sadly, going to leak
419 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
420
421 bool comma(false);
422
423 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
424 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
425 JSValueRef value(CYGetProperty(context, object, name));
426
427 if (comma)
428 str << ',';
429 else
430 comma = true;
431
432 CYUTF8String string(CYPoolUTF8String(pool, context, name));
433 if (CYIsKey(string))
434 str << string.data;
435 else
436 CYStringify(str, string.data, string.size);
437
438 str << ':' << CYPoolCCYON(pool, context, value);
439 }
440
441 str << '}';
442
443 JSPropertyNameArrayRelease(names);
444
445 std::string string(str.str());
446 return apr_pstrmemdup(pool, string.c_str(), string.size());
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) {
459 JSValueRef value(CYGetProperty(context, _this, index));
460
461 if (comma)
462 str << ',';
463 else
464 comma = true;
465
466 if (!JSValueIsUndefined(context, value))
467 str << CYPoolCCYON(pool, context, value);
468 else {
469 str << ',';
470 comma = false;
471 }
472 }
473
474 str << ']';
475
476 std::string value(str.str());
477 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
478} CYCatch }
479
4cb8aa43
JF
480static JSValueRef String_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
481 CYPool pool;
482 std::ostringstream str;
483
484 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, _this)));
485 CYStringify(str, string.data, string.size);
486
487 std::string value(str.str());
488 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
489} CYCatch }
490
9cad30fa
JF
491JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
492 Pointer *internal(new Pointer(pointer, context, owner, length, type));
493 return JSObjectMake(context, Pointer_, internal);
494}
495
1850a470
JF
496static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type, void **cache = NULL) {
497 cy::Functor *internal;
498
499 if (cache != NULL && *cache != NULL) {
500 internal = reinterpret_cast<cy::Functor *>(*cache);
501 ++internal->count_;
502 } else {
503 internal = new cy::Functor(type, function);
504
505 if (cache != NULL) {
506 *cache = internal;
507 ++internal->count_;
508 }
509 }
510
9cad30fa
JF
511 return JSObjectMake(context, Functor_, internal);
512}
513
514static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
515 return CYGetOffset(CYPoolCString(pool, context, value), index);
516}
517
518void *CYCastPointer_(JSContextRef context, JSValueRef value) {
519 switch (JSValueGetType(context, value)) {
520 case kJSTypeNull:
521 return NULL;
20ded97a
JF
522 case kJSTypeObject: {
523 JSObjectRef object((JSObjectRef) value);
9cad30fa 524 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
20ded97a 525 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
9cad30fa 526 return internal->value_;
20ded97a
JF
527 }
528 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
529 if (CYIsCallable(context, toPointer)) {
530 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
531 _assert(value != NULL);
532 return CYCastPointer_(context, value);
533 }
534 } default:
9cad30fa
JF
535 double number(CYCastDouble(context, value));
536 if (std::isnan(number))
537 throw CYJSError(context, "cannot convert value to pointer");
538 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
539 }
540}
541
542void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
543 switch (type->primitive) {
544 case sig::boolean_P:
545 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
546 break;
547
548#define CYPoolFFI_(primitive, native) \
549 case sig::primitive ## _P: \
550 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
551 break;
552
553 CYPoolFFI_(uchar, unsigned char)
554 CYPoolFFI_(char, char)
555 CYPoolFFI_(ushort, unsigned short)
556 CYPoolFFI_(short, short)
557 CYPoolFFI_(ulong, unsigned long)
558 CYPoolFFI_(long, long)
559 CYPoolFFI_(uint, unsigned int)
560 CYPoolFFI_(int, int)
561 CYPoolFFI_(ulonglong, unsigned long long)
562 CYPoolFFI_(longlong, long long)
563 CYPoolFFI_(float, float)
564 CYPoolFFI_(double, double)
565
566 case sig::array_P: {
567 uint8_t *base(reinterpret_cast<uint8_t *>(data));
568 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
569 for (size_t index(0); index != type->data.data.size; ++index) {
570 ffi_type *field(ffi->elements[index]);
571
572 JSValueRef rhs;
573 if (aggregate == NULL)
574 rhs = value;
575 else {
576 rhs = CYGetProperty(context, aggregate, index);
577 if (JSValueIsUndefined(context, rhs))
578 throw CYJSError(context, "unable to extract array value");
579 }
580
581 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
582 // XXX: alignment?
583 base += field->size;
584 }
585 } break;
586
587 case sig::pointer_P:
588 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
589 break;
590
591 case sig::string_P:
592 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
593 break;
594
595 case sig::struct_P: {
596 uint8_t *base(reinterpret_cast<uint8_t *>(data));
597 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
598 for (size_t index(0); index != type->data.signature.count; ++index) {
599 sig::Element *element(&type->data.signature.elements[index]);
600 ffi_type *field(ffi->elements[index]);
601
602 JSValueRef rhs;
603 if (aggregate == NULL)
604 rhs = value;
605 else {
606 rhs = CYGetProperty(context, aggregate, index);
607 if (JSValueIsUndefined(context, rhs)) {
608 if (element->name != NULL)
609 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
610 else
611 goto undefined;
612 if (JSValueIsUndefined(context, rhs)) undefined:
613 throw CYJSError(context, "unable to extract structure value");
614 }
615 }
616
617 CYPoolFFI(pool, context, element->type, field, base, rhs);
618 // XXX: alignment?
619 base += field->size;
620 }
621 } break;
622
623 case sig::void_P:
624 break;
625
626 default:
627 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
628 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
629 return;
630
631 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
632 }
633}
634
635JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
636 switch (type->primitive) {
637 case sig::boolean_P:
638 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
639
640#define CYFromFFI_(primitive, native) \
641 case sig::primitive ## _P: \
642 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
643
644 CYFromFFI_(uchar, unsigned char)
645 CYFromFFI_(char, char)
646 CYFromFFI_(ushort, unsigned short)
647 CYFromFFI_(short, short)
648 CYFromFFI_(ulong, unsigned long)
649 CYFromFFI_(long, long)
650 CYFromFFI_(uint, unsigned int)
651 CYFromFFI_(int, int)
652 CYFromFFI_(ulonglong, unsigned long long)
653 CYFromFFI_(longlong, long long)
654 CYFromFFI_(float, float)
655 CYFromFFI_(double, double)
656
657 case sig::array_P:
658 if (void *pointer = data)
659 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
660 else goto null;
661
662 case sig::pointer_P:
663 if (void *pointer = *reinterpret_cast<void **>(data))
664 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
665 else goto null;
666
667 case sig::string_P:
668 if (char *utf8 = *reinterpret_cast<char **>(data))
669 return CYCastJSValue(context, utf8);
670 else goto null;
671
672 case sig::struct_P:
673 return CYMakeStruct(context, data, type, ffi, owner);
674 case sig::void_P:
675 return CYJSUndefined(context);
676
677 null:
678 return CYJSNull(context);
679 default:
680 if (hooks_ != NULL && hooks_->FromFFI != NULL)
681 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
682 return value;
683
684 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
685 }
686}
687
688static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
689 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
690
691 JSContextRef context(internal->context_);
692
693 size_t count(internal->cif_.nargs);
694 JSValueRef values[count];
695
696 for (size_t index(0); index != count; ++index)
697 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
698
699 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
700 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
701}
702
703Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
704 // XXX: in case of exceptions this will leak
705 // XXX: in point of fact, this may /need/ to leak :(
706 Closure_privateData *internal(new Closure_privateData(context, function, type));
707
c5bce670
JF
708#if defined(__APPLE__) && defined(__arm__)
709 void *executable;
710 ffi_closure *writable(reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &executable)));
711
712 ffi_status status(ffi_prep_closure_loc(writable, &internal->cif_, callback, internal, executable));
713 _assert(status == FFI_OK);
714
715 internal->value_ = executable;
716#else
9cad30fa
JF
717 ffi_closure *closure((ffi_closure *) _syscall(mmap(
718 NULL, sizeof(ffi_closure),
719 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
720 -1, 0
721 )));
722
723 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
724 _assert(status == FFI_OK);
725
726 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
727
728 internal->value_ = closure;
c5bce670 729#endif
9cad30fa
JF
730
731 return internal;
732}
733
734static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
735 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
736 JSObjectRef object(JSObjectMake(context, Functor_, internal));
737 // XXX: see above notes about needing to leak
738 JSValueProtect(CYGetJSContext(context), object);
739 return object;
740}
741
742JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
743 return CYCastJSObject(context, CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name));
744}
745
746static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
747 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
748
749 JSValueRef exception(NULL);
750 bool function(JSValueIsInstanceOfConstructor(context, value, Function, &exception));
751 CYThrow(context, exception);
752
753 if (function) {
754 JSObjectRef function(CYCastJSObject(context, value));
755 return CYMakeFunctor(context, function, type);
756 } else {
757 void (*function)()(CYCastPointer<void (*)()>(context, value));
758 return CYMakeFunctor(context, function, type);
759 }
760}
761
762static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
763 Type_privateData *typical(internal->type_);
764 sig::Type *type(typical->type_);
765 if (type == NULL)
766 return false;
767
768 const char *name(CYPoolCString(pool, context, property));
769 size_t length(strlen(name));
770 double number(CYCastDouble(name, length));
771
772 size_t count(type->data.signature.count);
773
774 if (std::isnan(number)) {
775 if (property == NULL)
776 return false;
777
778 sig::Element *elements(type->data.signature.elements);
779
780 for (size_t local(0); local != count; ++local) {
781 sig::Element *element(&elements[local]);
782 if (element->name != NULL && strcmp(name, element->name) == 0) {
783 index = local;
784 goto base;
785 }
786 }
787
788 return false;
789 } else {
790 index = static_cast<ssize_t>(number);
791 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
792 return false;
793 }
794
795 base:
796 ffi_type **elements(typical->GetFFI()->elements);
797
798 base = reinterpret_cast<uint8_t *>(internal->value_);
799 for (ssize_t local(0); local != index; ++local)
800 base += elements[local]->size;
801
802 return true;
803}
804
805static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
806 CYPool pool;
807 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
808
809 if (JSStringIsEqual(property, length_s))
810 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
811
812 Type_privateData *typical(internal->type_);
813
814 if (typical->type_ == NULL)
815 return NULL;
816
817 ssize_t offset;
818 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
819 offset = 0;
820 else if (!CYGetOffset(pool, context, property, offset))
821 return NULL;
822
823 ffi_type *ffi(typical->GetFFI());
824
825 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
826 base += ffi->size * offset;
827
828 JSObjectRef owner(internal->GetOwner() ?: object);
829 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
830} CYCatch }
831
832static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
833 CYPool pool;
834 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
835 Type_privateData *typical(internal->type_);
836
837 if (typical->type_ == NULL)
838 return NULL;
839
840 ssize_t offset;
841 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
842 offset = 0;
843 else if (!CYGetOffset(pool, context, property, offset))
844 return NULL;
845
846 ffi_type *ffi(typical->GetFFI());
847
848 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
849 base += ffi->size * offset;
850
851 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
852 return true;
853} CYCatch }
854
855static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
856 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
857 Type_privateData *typical(internal->type_);
858 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
859}
860
861static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
862 CYPool pool;
863 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
864 Type_privateData *typical(internal->type_);
865
866 ssize_t index;
867 uint8_t *base;
868
869 if (!Index_(pool, context, internal, property, index, base))
870 return NULL;
871
872 JSObjectRef owner(internal->GetOwner() ?: object);
873
874 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
875} CYCatch }
876
877static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
878 CYPool pool;
879 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
880 Type_privateData *typical(internal->type_);
881
882 ssize_t index;
883 uint8_t *base;
884
885 if (!Index_(pool, context, internal, property, index, base))
886 return false;
887
888 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
889 return true;
890} CYCatch }
891
892static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
893 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
894 Type_privateData *typical(internal->type_);
895 sig::Type *type(typical->type_);
896
897 if (type == NULL)
898 return;
899
900 size_t count(type->data.signature.count);
901 sig::Element *elements(type->data.signature.elements);
902
903 char number[32];
904
905 for (size_t index(0); index != count; ++index) {
906 const char *name;
907 name = elements[index].name;
908
909 if (name == NULL) {
910 sprintf(number, "%zu", index);
911 name = number;
912 }
913
914 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
915 }
916}
917
918JSValueRef 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 {
919 if (setups + count != signature->count - 1)
920 throw CYJSError(context, "incorrect number of arguments to ffi function");
921
922 size_t size(setups + count);
923 void *values[size];
924 memcpy(values, setup, sizeof(void *) * setups);
925
926 for (size_t index(setups); index != size; ++index) {
927 sig::Element *element(&signature->elements[index + 1]);
928 ffi_type *ffi(cif->arg_types[index]);
929 // XXX: alignment?
930 values[index] = new(pool) uint8_t[ffi->size];
931 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
932 }
933
934 uint8_t value[cif->rtype->size];
935
936 if (hooks_ != NULL && hooks_->CallFunction != NULL)
937 (*hooks_->CallFunction)(context, cif, function, value, values);
938 else
939 ffi_call(cif, function, value, values);
940
941 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
942} CYCatch }
943
944static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
945 CYPool pool;
946 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
947 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
948}
949
8a23fb2e 950JSObjectRef CYMakeType(JSContextRef context, const char *type) {
9cad30fa
JF
951 Type_privateData *internal(new Type_privateData(type));
952 return JSObjectMake(context, Type_privateData::Class_, internal);
953}
954
8a23fb2e 955JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
9cad30fa
JF
956 Type_privateData *internal(new Type_privateData(type));
957 return JSObjectMake(context, Type_privateData::Class_, internal);
958}
959
960static void *CYCastSymbol(const char *name) {
961 return dlsym(RTLD_DEFAULT, name);
962}
963
964static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
965 JSObjectRef global(CYGetGlobalObject(context));
966 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
26ef7a82
JF
967 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
968
969 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
970 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1)))
971 if (JSValueRef value = CYGetProperty(context, space, property))
972 if (!JSValueIsUndefined(context, value))
973 return value;
9cad30fa
JF
974
975 CYPool pool;
976 CYUTF8String name(CYPoolUTF8String(pool, context, property));
977
2f51d6ab
JF
978 size_t length(name.size);
979 char keyed[length + 2];
980 memcpy(keyed + 1, name.data, length + 1);
981
982 static const char *modes = "0124";
983 for (size_t i(0); i != 4; ++i) {
984 char mode(modes[i]);
985 keyed[0] = mode;
986
987 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
988 switch (mode) {
989 case '0':
990 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
991
992 case '1':
993 if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
1850a470 994 return CYMakeFunctor(context, symbol, entry->value_, &entry->cache_);
2f51d6ab
JF
995 else return NULL;
996
997 case '2':
998 if (void *symbol = CYCastSymbol(name.data)) {
999 // XXX: this is horrendously inefficient
1000 sig::Signature signature;
1001 sig::Parse(pool, &signature, entry->value_, &Structor_);
1002 ffi_cif cif;
1003 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1004 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1005 } else return NULL;
1006
1007 // XXX: implement case 3
1008 case '4':
1009 return CYMakeType(context, entry->value_);
1010 }
9cad30fa
JF
1011 }
1012
2f51d6ab 1013 return NULL;
9cad30fa
JF
1014} CYCatch }
1015
26ef7a82
JF
1016static void All_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1017 JSObjectRef global(CYGetGlobalObject(context));
1018 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
1019 JSObjectRef alls(CYCastJSObject(context, CYGetProperty(context, cycript, CYJSString("alls"))));
1020
1021 for (size_t i(0), count(CYArrayLength(context, alls)); i != count; ++i)
1022 if (JSObjectRef space = CYCastJSObject(context, CYArrayGet(context, alls, count - i - 1))) {
1023 JSPropertyNameArrayRef subset(JSObjectCopyPropertyNames(context, space));
1024 for (size_t index(0), count(JSPropertyNameArrayGetCount(subset)); index != count; ++index)
1025 JSPropertyNameAccumulatorAddName(names, JSPropertyNameArrayGetNameAtIndex(subset, index));
1026 JSPropertyNameArrayRelease(subset);
1027 }
1028}
1029
9cad30fa
JF
1030static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1031 if (count != 2)
5d422750 1032 throw CYJSError(context, "incorrect number of arguments to Pointer constructor");
9cad30fa
JF
1033
1034 CYPool pool;
1035
1036 void *value(CYCastPointer<void *>(context, arguments[0]));
1037 const char *type(CYPoolCString(pool, context, arguments[1]));
1038
1039 sig::Signature signature;
1040 sig::Parse(pool, &signature, type, &Structor_);
1041
1042 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1043} CYCatch }
1044
1045static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1046 if (count != 1)
1047 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1048 CYPool pool;
1049 const char *type(CYPoolCString(pool, context, arguments[0]));
1050 return CYMakeType(context, type);
1051} CYCatch }
1052
85e90410
JF
1053static JSValueRef Type_callAsFunction_arrayOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1054 if (count != 1)
1055 throw CYJSError(context, "incorrect number of arguments to Type.arrayOf");
1056 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1057
1058 CYPool pool;
1059 size_t index(CYGetIndex(pool, context, CYJSString(context, arguments[0])));
1060 if (index == _not(size_t))
1061 throw CYJSError(context, "invalid array size used with Type.arrayOf");
9cad30fa
JF
1062
1063 sig::Type type;
85e90410
JF
1064 type.name = NULL;
1065 type.flags = 0;
9cad30fa 1066
85e90410
JF
1067 type.primitive = sig::array_P;
1068 type.data.data.type = internal->type_;
1069 type.data.data.size = index;
1070
1071 return CYMakeType(context, &type);
1072} CYCatch }
9cad30fa 1073
fbc17268
JF
1074static JSValueRef Type_callAsFunction_constant(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1075 if (count != 0)
1076 throw CYJSError(context, "incorrect number of arguments to Type.constant");
1077 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1078
1079 sig::Type type(*internal->type_);
1080 type.flags |= JOC_TYPE_CONST;
1081 return CYMakeType(context, &type);
1082} CYCatch }
1083
85e90410
JF
1084static JSValueRef Type_callAsFunction_pointerTo(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1085 if (count != 0)
1086 throw CYJSError(context, "incorrect number of arguments to Type.pointerTo");
1087 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1088
1089 sig::Type type;
9cad30fa
JF
1090 type.name = NULL;
1091 type.flags = 0;
1092
85e90410 1093 type.primitive = sig::pointer_P;
9cad30fa 1094 type.data.data.type = internal->type_;
85e90410 1095 type.data.data.size = 0;
9cad30fa
JF
1096
1097 return CYMakeType(context, &type);
1098} CYCatch }
1099
21d5f610
JF
1100static JSValueRef Type_callAsFunction_withName(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1101 if (count != 1)
1102 throw CYJSError(context, "incorrect number of arguments to Type.withName");
1103 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1104
1105 CYPool pool;
1106 const char *name(CYPoolCString(pool, context, arguments[0]));
1107
1108 sig::Type type(*internal->type_);
1109 type.name = name;
1110 return CYMakeType(context, &type);
1111} CYCatch }
1112
9cad30fa 1113static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
9cad30fa
JF
1114 if (count != 1)
1115 throw CYJSError(context, "incorrect number of arguments to type cast function");
1c3dd2c3
JF
1116 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1117
9cad30fa
JF
1118 sig::Type *type(internal->type_);
1119 ffi_type *ffi(internal->GetFFI());
1120 // XXX: alignment?
1121 uint8_t value[ffi->size];
1122 CYPool pool;
1123 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1124 return CYFromFFI(context, type, ffi, value);
1125} CYCatch }
1126
1127static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1128 if (count != 0)
767e8255 1129 throw CYJSError(context, "incorrect number of arguments to Type allocator");
9cad30fa
JF
1130 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1131
1132 sig::Type *type(internal->type_);
1133 size_t length;
1134
1135 if (type->primitive != sig::array_P)
1136 length = _not(size_t);
1137 else {
1138 length = type->data.data.size;
1139 type = type->data.data.type;
1140 }
1141
1142 void *value(malloc(internal->GetFFI()->size));
1143 return CYMakePointer(context, value, length, type, NULL, NULL);
1144} CYCatch }
1145
1146static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1147 if (count != 2)
1148 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1149 CYPool pool;
1150 const char *type(CYPoolCString(pool, context, arguments[1]));
1151 return CYMakeFunctor(context, arguments[0], type);
1152} CYCatch }
1153
1154static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1155 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1156 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1157} CYCatch }
1158
1159static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1160 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1161}
1162
1163static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1164 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1165 char string[32];
1166 sprintf(string, "%p", internal->value_);
1167 return CYCastJSValue(context, string);
1168} CYCatch }
1169
1170static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1171 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1172 if (internal->length_ != _not(size_t)) {
1173 JSObjectRef Array(CYGetCachedObject(context, Array_s));
1174 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1175 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1176 } else {
1177 char string[32];
1178 sprintf(string, "%p", internal->value_);
1179 return CYCastJSValue(context, string);
1180 }
1181} CYCatch }
1182
74e8c566
JF
1183static JSValueRef Type_getProperty_alignment(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1184 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1185 return CYCastJSValue(context, internal->GetFFI()->alignment);
1186}
1187
21d5f610
JF
1188static JSValueRef Type_getProperty_name(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1189 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1190 return CYCastJSValue(context, internal->type_->name);
1191}
1192
74e8c566
JF
1193static JSValueRef Type_getProperty_size(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
1194 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1195 return CYCastJSValue(context, internal->GetFFI()->size);
1196}
1197
9cad30fa
JF
1198static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1199 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1200 CYPool pool;
1201 const char *type(sig::Unparse(pool, internal->type_));
1202 return CYCastJSValue(context, CYJSString(type));
1203} CYCatch }
1204
1205static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1206 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1207 CYPool pool;
1208 const char *type(sig::Unparse(pool, internal->type_));
1209 size_t size(strlen(type));
1210 char *cyon(new(pool) char[12 + size + 1]);
1211 memcpy(cyon, "new Type(\"", 10);
1212 cyon[12 + size] = '\0';
1213 cyon[12 + size - 2] = '"';
1214 cyon[12 + size - 1] = ')';
1215 memcpy(cyon + 10, type, size);
1216 return CYCastJSValue(context, CYJSString(cyon));
1217} CYCatch }
1218
1219static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1220 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1221}
1222
1223static JSStaticFunction Pointer_staticFunctions[4] = {
1224 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1225 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1226 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1227 {NULL, NULL, 0}
1228};
1229
1230static JSStaticFunction Struct_staticFunctions[2] = {
1231 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1232 {NULL, NULL, 0}
1233};
1234
1235static JSStaticFunction Functor_staticFunctions[4] = {
1236 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1237 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1238 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1239 {NULL, NULL, 0}
1240};
1241
1242namespace cy {
1243 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1244}
1245
21d5f610 1246static JSStaticValue Type_staticValues[4] = {
74e8c566 1247 {"alignment", &Type_getProperty_alignment, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1248 {"name", &Type_getProperty_name, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
74e8c566
JF
1249 {"size", &Type_getProperty_size, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1250 {NULL, NULL, NULL, 0}
1251};
1252
21d5f610 1253static JSStaticFunction Type_staticFunctions[8] = {
85e90410 1254 {"arrayOf", &Type_callAsFunction_arrayOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
fbc17268 1255 {"constant", &Type_callAsFunction_constant, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
85e90410 1256 {"pointerTo", &Type_callAsFunction_pointerTo, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
21d5f610 1257 {"withName", &Type_callAsFunction_withName, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
9cad30fa
JF
1258 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1259 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1260 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1261 {NULL, NULL, 0}
1262};
1263
1264static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1265
1266void CYSetArgs(int argc, const char *argv[]) {
1267 JSContextRef context(CYGetJSContext());
1268 JSValueRef args[argc];
1269 for (int i(0); i != argc; ++i)
1270 args[i] = CYCastJSValue(context, argv[i]);
1271
1272 JSObjectRef array;
1273 if (JSObjectMakeArray$ != NULL) {
1274 JSValueRef exception(NULL);
1275 array = (*JSObjectMakeArray$)(context, argc, args, &exception);
1276 CYThrow(context, exception);
1277 } else {
1278 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1279 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1280 array = CYCastJSObject(context, value);
1281 }
1282
1283 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1284 CYSetProperty(context, System, CYJSString("args"), array);
1285}
1286
1287JSObjectRef CYGetGlobalObject(JSContextRef context) {
1288 return JSContextGetGlobalObject(context);
1289}
1290
0ced2e47 1291const char *CYExecute(apr_pool_t *pool, CYUTF8String code) {
9cad30fa
JF
1292 JSContextRef context(CYGetJSContext());
1293 JSValueRef exception(NULL), result;
1294
1295 void *handle;
1296 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1297 handle = (*hooks_->ExecuteStart)(context);
1298 else
1299 handle = NULL;
1300
1301 const char *json;
1302
1303 try {
1304 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1305 } catch (const char *error) {
1306 return error;
1307 }
1308
9cc84a5a
JF
1309 if (exception != NULL) error:
1310 return CYPoolCString(pool, context, CYJSString(context, exception));
9cad30fa
JF
1311
1312 if (JSValueIsUndefined(context, result))
1313 return NULL;
1314
1315 try {
1316 json = CYPoolCCYON(pool, context, result, &exception);
1317 } catch (const char *error) {
1318 return error;
1319 }
1320
1321 if (exception != NULL)
1322 goto error;
1323
1324 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1325
1326 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1327 (*hooks_->ExecuteEnd)(context, handle);
1328 return json;
1329}
1330
1331extern "C" void CydgetSetupContext(JSGlobalContextRef context) {
1332 CYSetupContext(context);
1333}
1334
09eee478
JF
1335static bool initialized_ = false;
1336
9cad30fa 1337void CYInitializeDynamic() {
09eee478
JF
1338 if (!initialized_)
1339 initialized_ = true;
1340 else return;
1341
9cad30fa
JF
1342 CYInitializeStatic();
1343
9cad30fa
JF
1344 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1345
1346 JSClassDefinition definition;
1347
1348 definition = kJSClassDefinitionEmpty;
1349 definition.className = "All";
1350 definition.getProperty = &All_getProperty;
26ef7a82 1351 definition.getPropertyNames = &All_getPropertyNames;
9cad30fa
JF
1352 All_ = JSClassCreate(&definition);
1353
1354 definition = kJSClassDefinitionEmpty;
1355 definition.className = "Context";
1356 definition.finalize = &CYFinalize;
1357 Context_ = JSClassCreate(&definition);
1358
1359 definition = kJSClassDefinitionEmpty;
1360 definition.className = "Functor";
1361 definition.staticFunctions = cy::Functor::StaticFunctions;
1362 definition.callAsFunction = &Functor_callAsFunction;
1363 definition.finalize = &CYFinalize;
1364 Functor_ = JSClassCreate(&definition);
1365
1366 definition = kJSClassDefinitionEmpty;
1367 definition.className = "Pointer";
1368 definition.staticFunctions = Pointer_staticFunctions;
1369 definition.getProperty = &Pointer_getProperty;
1370 definition.setProperty = &Pointer_setProperty;
1371 definition.finalize = &CYFinalize;
1372 Pointer_ = JSClassCreate(&definition);
1373
1374 definition = kJSClassDefinitionEmpty;
1375 definition.className = "Struct";
1376 definition.staticFunctions = Struct_staticFunctions;
1377 definition.getProperty = &Struct_getProperty;
1378 definition.setProperty = &Struct_setProperty;
1379 definition.getPropertyNames = &Struct_getPropertyNames;
1380 definition.finalize = &CYFinalize;
1381 Struct_ = JSClassCreate(&definition);
1382
1383 definition = kJSClassDefinitionEmpty;
1384 definition.className = "Type";
74e8c566 1385 definition.staticValues = Type_staticValues;
9cad30fa 1386 definition.staticFunctions = Type_staticFunctions;
9cad30fa
JF
1387 definition.callAsFunction = &Type_callAsFunction;
1388 definition.callAsConstructor = &Type_callAsConstructor;
1389 definition.finalize = &CYFinalize;
1390 Type_privateData::Class_ = JSClassCreate(&definition);
1391
1392 definition = kJSClassDefinitionEmpty;
56a66df3 1393 definition.className = "Global";
9cad30fa
JF
1394 //definition.getProperty = &Global_getProperty;
1395 Global_ = JSClassCreate(&definition);
1396
1397 Array_s = JSStringCreateWithUTF8CString("Array");
1398 cy_s = JSStringCreateWithUTF8CString("$cy");
1399 length_s = JSStringCreateWithUTF8CString("length");
1400 message_s = JSStringCreateWithUTF8CString("message");
1401 name_s = JSStringCreateWithUTF8CString("name");
1402 pop_s = JSStringCreateWithUTF8CString("pop");
1403 prototype_s = JSStringCreateWithUTF8CString("prototype");
1404 push_s = JSStringCreateWithUTF8CString("push");
1405 splice_s = JSStringCreateWithUTF8CString("splice");
1406 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1407 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
20ded97a 1408 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
4cb8aa43 1409 toString_s = JSStringCreateWithUTF8CString("toString");
9cad30fa
JF
1410
1411 Result_ = JSStringCreateWithUTF8CString("_");
1412
1413 if (hooks_ != NULL && hooks_->Initialize != NULL)
1414 (*hooks_->Initialize)();
1415}
1416
1417void CYThrow(JSContextRef context, JSValueRef value) {
1418 if (value != NULL)
1419 throw CYJSError(context, value);
1420}
1421
1422const char *CYJSError::PoolCString(apr_pool_t *pool) const {
1423 // XXX: this used to be CYPoolCString
1424 return CYPoolCCYON(pool, context_, value_);
1425}
1426
1427JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1428 // XXX: what if the context is different?
1429 return value_;
1430}
1431
1432JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1433 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1434
1435 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1436
1437 JSValueRef exception(NULL);
1438 JSValueRef value(JSObjectCallAsConstructor(context, Error, 1, arguments, &exception));
1439 CYThrow(context, exception);
1440
1441 return value;
1442}
1443
1444JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1445 return CYCastJSError(context, message_);
1446}
1447
1448CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1449 _assert(context != NULL);
1450
1451 CYPool pool;
1452
1453 va_list args;
1454 va_start(args, format);
1455 const char *message(apr_pvsprintf(pool, format, args));
1456 va_end(args);
1457
1458 value_ = CYCastJSError(context, message);
1459}
1460
1461JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1462 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1463}
1464
1465extern "C" void CYSetupContext(JSGlobalContextRef context) {
26ef7a82
JF
1466 JSValueRef exception(NULL);
1467
9cad30fa
JF
1468 CYInitializeDynamic();
1469
1470 JSObjectRef global(CYGetGlobalObject(context));
1471
1472 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1473 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1474
1475/* Cache Globals {{{ */
1476 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1477 CYSetProperty(context, cy, CYJSString("Array"), Array);
1478
1479 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1480 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1481
1482 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1483 CYSetProperty(context, cy, CYJSString("Error"), Error);
1484
1485 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1486 CYSetProperty(context, cy, CYJSString("Function"), Function);
1487
1488 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1489 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1490
1491 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1492 CYSetProperty(context, cy, CYJSString("Object"), Object);
1493
1494 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1495 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1496
1497 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1498 CYSetProperty(context, cy, CYJSString("String"), String);
4cb8aa43
JF
1499
1500 JSObjectRef String_prototype(CYCastJSObject(context, CYGetProperty(context, String, prototype_s)));
1501 CYSetProperty(context, cy, CYJSString("String_prototype"), String_prototype);
9cad30fa
JF
1502/* }}} */
1503
1504 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
4cb8aa43 1505 CYSetProperty(context, String_prototype, toCYON_s, &String_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1506
1507 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1508 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1509 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1510
1511 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1512 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1513 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1514
1515 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
b63701b2 1516 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
9cad30fa
JF
1517
1518 JSObjectRef all(JSObjectMake(context, All_, NULL));
1519 CYSetProperty(context, cycript, CYJSString("all"), all);
1520
26ef7a82
JF
1521 JSObjectRef alls(JSObjectCallAsConstructor(context, Array, 0, NULL, &exception));
1522 CYThrow(context, exception);
1523 CYSetProperty(context, cycript, CYJSString("alls"), alls);
1524
56a66df3
JF
1525 if (true) {
1526 JSObjectRef last(NULL), curr(global);
9cad30fa 1527
56a66df3
JF
1528 goto next; for (JSValueRef next;;) {
1529 if (JSValueIsNull(context, next))
1530 break;
1531 last = curr;
1532 curr = CYCastJSObject(context, next);
1533 next:
1534 next = JSObjectGetPrototype(context, curr);
1535 }
9cad30fa 1536
56a66df3
JF
1537 JSObjectSetPrototype(context, last, all);
1538 }
9cad30fa 1539
56a66df3 1540 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq, kJSPropertyAttributeDontEnum);
9cad30fa
JF
1541
1542 JSObjectRef System(JSObjectMake(context, NULL, NULL));
cdc80ff2 1543 CYSetProperty(context, cy, CYJSString("System"), System);
9cad30fa
JF
1544
1545 CYSetProperty(context, global, CYJSString("system"), System);
1546 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1547 //CYSetProperty(context, System, CYJSString("global"), global);
1548 CYSetProperty(context, System, CYJSString("print"), &System_print);
1549
1550 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1551 (*hooks_->SetupContext)(context);
26ef7a82
JF
1552
1553 CYArrayPush(context, alls, cycript);
9cad30fa
JF
1554}
1555
1556JSGlobalContextRef CYGetJSContext() {
1557 CYInitializeDynamic();
1558
1559 static JSGlobalContextRef context_;
1560
1561 if (context_ == NULL) {
1562 context_ = JSGlobalContextCreate(Global_);
1563 CYSetupContext(context_);
1564 }
1565
1566 return context_;
1567}