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