]> git.saurik.com Git - cycript.git/blame - Execute.cpp
Added CalEventIsAllDay to Bridge.def for Element.
[cycript.git] / Execute.cpp
CommitLineData
9cad30fa
JF
1/* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3*/
4
5/* Modified BSD License {{{ */
6/*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37*/
38/* }}} */
39
9cad30fa
JF
40#include "Internal.hpp"
41
42#include <dlfcn.h>
43#include <iconv.h>
44
45#include "cycript.hpp"
46
47#include "sig/parse.hpp"
48#include "sig/ffi_type.hpp"
49
50#include "Pooling.hpp"
2f51d6ab 51#include "Execute.hpp"
9cad30fa
JF
52
53#include <sys/mman.h>
54
55#include <iostream>
56#include <ext/stdio_filebuf.h>
57#include <set>
58#include <map>
59#include <iomanip>
60#include <sstream>
61#include <cmath>
62
63#include "Parser.hpp"
64#include "Cycript.tab.hh"
65
66#include "Error.hpp"
67#include "JavaScript.hpp"
68#include "String.hpp"
69
9cad30fa
JF
70struct CYHooks *hooks_;
71
72/* JavaScript Properties {{{ */
73JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
74 JSValueRef exception(NULL);
75 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
76 CYThrow(context, exception);
77 return value;
78}
79
80JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
81 JSValueRef exception(NULL);
82 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
83 CYThrow(context, exception);
84 return value;
85}
86
87void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
88 JSValueRef exception(NULL);
89 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
90 CYThrow(context, exception);
91}
92
93void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
94 JSValueRef exception(NULL);
95 JSObjectSetProperty(context, object, name, value, attributes, &exception);
96 CYThrow(context, exception);
97}
98
99void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef (*callback)(JSContextRef, JSObjectRef, JSObjectRef, size_t, const JSValueRef[], JSValueRef *), JSPropertyAttributes attributes) {
100 CYSetProperty(context, object, name, JSObjectMakeFunctionWithCallback(context, name, callback), attributes);
101}
102/* }}} */
103/* JavaScript Strings {{{ */
104JSStringRef CYCopyJSString(const char *value) {
105 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
106}
107
108JSStringRef CYCopyJSString(JSStringRef value) {
109 return value == NULL ? NULL : JSStringRetain(value);
110}
111
112JSStringRef CYCopyJSString(CYUTF8String value) {
113 // XXX: this is very wrong; it needs to convert to UTF16 and then create from there
114 return CYCopyJSString(value.data);
115}
116
117JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
118 if (JSValueIsNull(context, value))
119 return NULL;
120 JSValueRef exception(NULL);
121 JSStringRef string(JSValueToStringCopy(context, value, &exception));
122 CYThrow(context, exception);
123 return string;
124}
125
126static CYUTF16String CYCastUTF16String(JSStringRef value) {
127 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
128}
129
130CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
131 return CYPoolUTF8String(pool, CYCastUTF16String(value));
132}
133
134const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
135 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
136 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
137 return utf8.data;
138}
139
140const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
141 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
142}
143/* }}} */
144/* Index Offsets {{{ */
145size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
146 return CYGetIndex(CYPoolUTF8String(pool, context, value));
147}
148/* }}} */
149
150static JSClassRef All_;
151static JSClassRef Context_;
152static JSClassRef Functor_;
153static JSClassRef Global_;
154static JSClassRef Pointer_;
155static JSClassRef Struct_;
156
157JSStringRef Array_s;
158JSStringRef cy_s;
159JSStringRef length_s;
160JSStringRef message_s;
161JSStringRef name_s;
162JSStringRef pop_s;
163JSStringRef prototype_s;
164JSStringRef push_s;
165JSStringRef splice_s;
166JSStringRef toCYON_s;
167JSStringRef toJSON_s;
20ded97a 168JSStringRef toPointer_s;
9cad30fa
JF
169
170static JSStringRef Result_;
171
9cad30fa 172void CYFinalize(JSObjectRef object) {
1850a470
JF
173 CYData *internal(reinterpret_cast<CYData *>(JSObjectGetPrivate(object)));
174 if (--internal->count_ == 0)
175 delete internal;
9cad30fa
JF
176}
177
9cad30fa
JF
178void Structor_(apr_pool_t *pool, sig::Type *&type) {
179 if (
180 type->primitive == sig::pointer_P &&
181 type->data.data.type != NULL &&
182 type->data.data.type->primitive == sig::struct_P &&
1648ddb9 183 type->data.data.type->name != NULL &&
9cad30fa
JF
184 strcmp(type->data.data.type->name, "_objc_class") == 0
185 ) {
186 type->primitive = sig::typename_P;
187 type->data.data.type = NULL;
188 return;
189 }
190
191 if (type->primitive != sig::struct_P || type->name == NULL)
192 return;
193
2f51d6ab
JF
194 size_t length(strlen(type->name));
195 char keyed[length + 2];
196 memcpy(keyed + 1, type->name, length + 1);
197
198 static const char *modes = "34";
199 for (size_t i(0); i != 2; ++i) {
200 char mode(modes[i]);
201 keyed[0] = mode;
202
203 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
204 switch (mode) {
205 case '3':
206 sig::Parse(pool, &type->data.signature, entry->value_, &Structor_);
207 break;
208
209 case '4': {
210 sig::Signature signature;
211 sig::Parse(pool, &signature, entry->value_, &Structor_);
212 type = signature.elements[0].type;
213 } break;
214 }
9cad30fa
JF
215 }
216}
217
218JSClassRef Type_privateData::Class_;
219
220struct Context :
221 CYData
222{
223 JSGlobalContextRef context_;
224
225 Context(JSGlobalContextRef context) :
226 context_(context)
227 {
228 }
229};
230
231struct Pointer :
232 CYOwned
233{
234 Type_privateData *type_;
235 size_t length_;
236
237 Pointer(void *value, JSContextRef context, JSObjectRef owner, size_t length, sig::Type *type) :
238 CYOwned(value, context, owner),
239 type_(new(pool_) Type_privateData(type)),
240 length_(length)
241 {
242 }
243};
244
245struct Struct_privateData :
246 CYOwned
247{
248 Type_privateData *type_;
249
250 Struct_privateData(JSContextRef context, JSObjectRef owner) :
251 CYOwned(NULL, context, owner)
252 {
253 }
254};
255
14ec9e00 256typedef std::map<const char *, Type_privateData *, CYCStringLess> TypeMap;
9cad30fa
JF
257static TypeMap Types_;
258
259JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
260 Struct_privateData *internal(new Struct_privateData(context, owner));
261 apr_pool_t *pool(internal->pool_);
262 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
263 internal->type_ = typical;
264
265 if (owner != NULL)
266 internal->value_ = data;
267 else {
268 size_t size(typical->GetFFI()->size);
269 void *copy(apr_palloc(internal->pool_, size));
270 memcpy(copy, data, size);
271 internal->value_ = copy;
272 }
273
274 return JSObjectMake(context, Struct_, internal);
275}
276
277JSValueRef CYCastJSValue(JSContextRef context, bool value) {
278 return JSValueMakeBoolean(context, value);
279}
280
281JSValueRef CYCastJSValue(JSContextRef context, double value) {
282 return JSValueMakeNumber(context, value);
283}
284
285#define CYCastJSValue_(Type_) \
286 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
287 return JSValueMakeNumber(context, static_cast<double>(value)); \
288 }
289
290CYCastJSValue_(int)
291CYCastJSValue_(unsigned int)
292CYCastJSValue_(long int)
293CYCastJSValue_(long unsigned int)
294CYCastJSValue_(long long int)
295CYCastJSValue_(long long unsigned int)
296
297JSValueRef CYJSUndefined(JSContextRef context) {
298 return JSValueMakeUndefined(context);
299}
300
301double CYCastDouble(JSContextRef context, JSValueRef value) {
302 JSValueRef exception(NULL);
303 double number(JSValueToNumber(context, value, &exception));
304 CYThrow(context, exception);
305 return number;
306}
307
308bool CYCastBool(JSContextRef context, JSValueRef value) {
309 return JSValueToBoolean(context, value);
310}
311
312JSValueRef CYJSNull(JSContextRef context) {
313 return JSValueMakeNull(context);
314}
315
316JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
317 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
318}
319
320JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
321 return CYCastJSValue(context, CYJSString(value));
322}
323
324JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
325 JSValueRef exception(NULL);
326 JSObjectRef object(JSValueToObject(context, value, &exception));
327 CYThrow(context, exception);
328 return object;
329}
330
331JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, const JSValueRef arguments[]) {
332 JSValueRef exception(NULL);
333 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
334 CYThrow(context, exception);
335 return value;
336}
337
338bool CYIsCallable(JSContextRef context, JSValueRef value) {
339 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
340}
341
342static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
343 if (count == 0)
344 printf("\n");
345 else {
346 CYPool pool;
347 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
348 }
349
350 return CYJSUndefined(context);
351} CYCatch }
352
353static size_t Nonce_(0);
354
355static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
356 CYPool pool;
357 const char *name(apr_psprintf(pool, "%s%"APR_SIZE_T_FMT"", CYPoolCString(pool, context, arguments[0]), Nonce_++));
358 return CYCastJSValue(context, name);
359}
360
361static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
362 JSGarbageCollect(context);
363 return CYJSUndefined(context);
364}
365
366const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
367 switch (JSType type = JSValueGetType(context, value)) {
368 case kJSTypeUndefined:
369 return "undefined";
370 case kJSTypeNull:
371 return "null";
372 case kJSTypeBoolean:
373 return CYCastBool(context, value) ? "true" : "false";
374
375 case kJSTypeNumber: {
376 std::ostringstream str;
377 CYNumerify(str, CYCastDouble(context, value));
378 std::string value(str.str());
379 return apr_pstrmemdup(pool, value.c_str(), value.size());
380 } break;
381
382 case kJSTypeString: {
383 std::ostringstream str;
384 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
385 CYStringify(str, string.data, string.size);
386 std::string value(str.str());
387 return apr_pstrmemdup(pool, value.c_str(), value.size());
388 } break;
389
390 case kJSTypeObject:
391 return CYPoolCCYON(pool, context, (JSObjectRef) value);
392 default:
393 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
394 }
395} CYCatch }
396
397const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
398 JSValueRef exception(NULL);
399 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
400 CYThrow(context, exception);
401 return cyon;
402}
403
404const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
405 JSValueRef toCYON(CYGetProperty(context, object, toCYON_s));
406 if (CYIsCallable(context, toCYON)) {
407 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
408 _assert(value != NULL);
409 return CYPoolCString(pool, context, value);
410 }
411
412 JSValueRef toJSON(CYGetProperty(context, object, toJSON_s));
413 if (CYIsCallable(context, toJSON)) {
414 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
415 JSValueRef exception(NULL);
416 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
417 CYThrow(context, exception);
418 return cyon;
419 }
420
421 std::ostringstream str;
422
423 str << '{';
424
425 // XXX: this is, sadly, going to leak
426 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
427
428 bool comma(false);
429
430 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
431 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
432 JSValueRef value(CYGetProperty(context, object, name));
433
434 if (comma)
435 str << ',';
436 else
437 comma = true;
438
439 CYUTF8String string(CYPoolUTF8String(pool, context, name));
440 if (CYIsKey(string))
441 str << string.data;
442 else
443 CYStringify(str, string.data, string.size);
444
445 str << ':' << CYPoolCCYON(pool, context, value);
446 }
447
448 str << '}';
449
450 JSPropertyNameArrayRelease(names);
451
452 std::string string(str.str());
453 return apr_pstrmemdup(pool, string.c_str(), string.size());
454}
455
456static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
457 CYPool pool;
458 std::ostringstream str;
459
460 str << '[';
461
462 JSValueRef length(CYGetProperty(context, _this, length_s));
463 bool comma(false);
464
465 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
466 JSValueRef value(CYGetProperty(context, _this, index));
467
468 if (comma)
469 str << ',';
470 else
471 comma = true;
472
473 if (!JSValueIsUndefined(context, value))
474 str << CYPoolCCYON(pool, context, value);
475 else {
476 str << ',';
477 comma = false;
478 }
479 }
480
481 str << ']';
482
483 std::string value(str.str());
484 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
485} CYCatch }
486
487JSObjectRef CYMakePointer(JSContextRef context, void *pointer, size_t length, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
488 Pointer *internal(new Pointer(pointer, context, owner, length, type));
489 return JSObjectMake(context, Pointer_, internal);
490}
491
1850a470
JF
492static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type, void **cache = NULL) {
493 cy::Functor *internal;
494
495 if (cache != NULL && *cache != NULL) {
496 internal = reinterpret_cast<cy::Functor *>(*cache);
497 ++internal->count_;
498 } else {
499 internal = new cy::Functor(type, function);
500
501 if (cache != NULL) {
502 *cache = internal;
503 ++internal->count_;
504 }
505 }
506
9cad30fa
JF
507 return JSObjectMake(context, Functor_, internal);
508}
509
510static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
511 return CYGetOffset(CYPoolCString(pool, context, value), index);
512}
513
514void *CYCastPointer_(JSContextRef context, JSValueRef value) {
515 switch (JSValueGetType(context, value)) {
516 case kJSTypeNull:
517 return NULL;
20ded97a
JF
518 case kJSTypeObject: {
519 JSObjectRef object((JSObjectRef) value);
9cad30fa 520 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
20ded97a 521 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
9cad30fa 522 return internal->value_;
20ded97a
JF
523 }
524 JSValueRef toPointer(CYGetProperty(context, object, toPointer_s));
525 if (CYIsCallable(context, toPointer)) {
526 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toPointer, object, 0, NULL));
527 _assert(value != NULL);
528 return CYCastPointer_(context, value);
529 }
530 } default:
9cad30fa
JF
531 double number(CYCastDouble(context, value));
532 if (std::isnan(number))
533 throw CYJSError(context, "cannot convert value to pointer");
534 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
535 }
536}
537
538void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
539 switch (type->primitive) {
540 case sig::boolean_P:
541 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
542 break;
543
544#define CYPoolFFI_(primitive, native) \
545 case sig::primitive ## _P: \
546 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
547 break;
548
549 CYPoolFFI_(uchar, unsigned char)
550 CYPoolFFI_(char, char)
551 CYPoolFFI_(ushort, unsigned short)
552 CYPoolFFI_(short, short)
553 CYPoolFFI_(ulong, unsigned long)
554 CYPoolFFI_(long, long)
555 CYPoolFFI_(uint, unsigned int)
556 CYPoolFFI_(int, int)
557 CYPoolFFI_(ulonglong, unsigned long long)
558 CYPoolFFI_(longlong, long long)
559 CYPoolFFI_(float, float)
560 CYPoolFFI_(double, double)
561
562 case sig::array_P: {
563 uint8_t *base(reinterpret_cast<uint8_t *>(data));
564 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
565 for (size_t index(0); index != type->data.data.size; ++index) {
566 ffi_type *field(ffi->elements[index]);
567
568 JSValueRef rhs;
569 if (aggregate == NULL)
570 rhs = value;
571 else {
572 rhs = CYGetProperty(context, aggregate, index);
573 if (JSValueIsUndefined(context, rhs))
574 throw CYJSError(context, "unable to extract array value");
575 }
576
577 CYPoolFFI(pool, context, type->data.data.type, field, base, rhs);
578 // XXX: alignment?
579 base += field->size;
580 }
581 } break;
582
583 case sig::pointer_P:
584 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
585 break;
586
587 case sig::string_P:
588 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
589 break;
590
591 case sig::struct_P: {
592 uint8_t *base(reinterpret_cast<uint8_t *>(data));
593 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
594 for (size_t index(0); index != type->data.signature.count; ++index) {
595 sig::Element *element(&type->data.signature.elements[index]);
596 ffi_type *field(ffi->elements[index]);
597
598 JSValueRef rhs;
599 if (aggregate == NULL)
600 rhs = value;
601 else {
602 rhs = CYGetProperty(context, aggregate, index);
603 if (JSValueIsUndefined(context, rhs)) {
604 if (element->name != NULL)
605 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
606 else
607 goto undefined;
608 if (JSValueIsUndefined(context, rhs)) undefined:
609 throw CYJSError(context, "unable to extract structure value");
610 }
611 }
612
613 CYPoolFFI(pool, context, element->type, field, base, rhs);
614 // XXX: alignment?
615 base += field->size;
616 }
617 } break;
618
619 case sig::void_P:
620 break;
621
622 default:
623 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
624 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
625 return;
626
627 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
628 }
629}
630
631JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
632 switch (type->primitive) {
633 case sig::boolean_P:
634 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
635
636#define CYFromFFI_(primitive, native) \
637 case sig::primitive ## _P: \
638 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
639
640 CYFromFFI_(uchar, unsigned char)
641 CYFromFFI_(char, char)
642 CYFromFFI_(ushort, unsigned short)
643 CYFromFFI_(short, short)
644 CYFromFFI_(ulong, unsigned long)
645 CYFromFFI_(long, long)
646 CYFromFFI_(uint, unsigned int)
647 CYFromFFI_(int, int)
648 CYFromFFI_(ulonglong, unsigned long long)
649 CYFromFFI_(longlong, long long)
650 CYFromFFI_(float, float)
651 CYFromFFI_(double, double)
652
653 case sig::array_P:
654 if (void *pointer = data)
655 return CYMakePointer(context, pointer, type->data.data.size, type->data.data.type, NULL, owner);
656 else goto null;
657
658 case sig::pointer_P:
659 if (void *pointer = *reinterpret_cast<void **>(data))
660 return CYMakePointer(context, pointer, _not(size_t), type->data.data.type, NULL, owner);
661 else goto null;
662
663 case sig::string_P:
664 if (char *utf8 = *reinterpret_cast<char **>(data))
665 return CYCastJSValue(context, utf8);
666 else goto null;
667
668 case sig::struct_P:
669 return CYMakeStruct(context, data, type, ffi, owner);
670 case sig::void_P:
671 return CYJSUndefined(context);
672
673 null:
674 return CYJSNull(context);
675 default:
676 if (hooks_ != NULL && hooks_->FromFFI != NULL)
677 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
678 return value;
679
680 CYThrow("unimplemented signature code: '%c''\n", type->primitive);
681 }
682}
683
684static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
685 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
686
687 JSContextRef context(internal->context_);
688
689 size_t count(internal->cif_.nargs);
690 JSValueRef values[count];
691
692 for (size_t index(0); index != count; ++index)
693 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
694
695 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
696 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
697}
698
699Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
700 // XXX: in case of exceptions this will leak
701 // XXX: in point of fact, this may /need/ to leak :(
702 Closure_privateData *internal(new Closure_privateData(context, function, type));
703
704 ffi_closure *closure((ffi_closure *) _syscall(mmap(
705 NULL, sizeof(ffi_closure),
706 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
707 -1, 0
708 )));
709
710 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
711 _assert(status == FFI_OK);
712
713 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
714
715 internal->value_ = closure;
716
717 return internal;
718}
719
720static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
721 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
722 JSObjectRef object(JSObjectMake(context, Functor_, internal));
723 // XXX: see above notes about needing to leak
724 JSValueProtect(CYGetJSContext(context), object);
725 return object;
726}
727
728JSObjectRef CYGetCachedObject(JSContextRef context, JSStringRef name) {
729 return CYCastJSObject(context, CYGetProperty(context, CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s)), name));
730}
731
732static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
733 JSObjectRef Function(CYGetCachedObject(context, CYJSString("Function")));
734
735 JSValueRef exception(NULL);
736 bool function(JSValueIsInstanceOfConstructor(context, value, Function, &exception));
737 CYThrow(context, exception);
738
739 if (function) {
740 JSObjectRef function(CYCastJSObject(context, value));
741 return CYMakeFunctor(context, function, type);
742 } else {
743 void (*function)()(CYCastPointer<void (*)()>(context, value));
744 return CYMakeFunctor(context, function, type);
745 }
746}
747
748static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
749 Type_privateData *typical(internal->type_);
750 sig::Type *type(typical->type_);
751 if (type == NULL)
752 return false;
753
754 const char *name(CYPoolCString(pool, context, property));
755 size_t length(strlen(name));
756 double number(CYCastDouble(name, length));
757
758 size_t count(type->data.signature.count);
759
760 if (std::isnan(number)) {
761 if (property == NULL)
762 return false;
763
764 sig::Element *elements(type->data.signature.elements);
765
766 for (size_t local(0); local != count; ++local) {
767 sig::Element *element(&elements[local]);
768 if (element->name != NULL && strcmp(name, element->name) == 0) {
769 index = local;
770 goto base;
771 }
772 }
773
774 return false;
775 } else {
776 index = static_cast<ssize_t>(number);
777 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
778 return false;
779 }
780
781 base:
782 ffi_type **elements(typical->GetFFI()->elements);
783
784 base = reinterpret_cast<uint8_t *>(internal->value_);
785 for (ssize_t local(0); local != index; ++local)
786 base += elements[local]->size;
787
788 return true;
789}
790
791static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
792 CYPool pool;
793 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
794
795 if (JSStringIsEqual(property, length_s))
796 return internal->length_ == _not(size_t) ? CYJSUndefined(context) : CYCastJSValue(context, internal->length_);
797
798 Type_privateData *typical(internal->type_);
799
800 if (typical->type_ == NULL)
801 return NULL;
802
803 ssize_t offset;
804 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
805 offset = 0;
806 else if (!CYGetOffset(pool, context, property, offset))
807 return NULL;
808
809 ffi_type *ffi(typical->GetFFI());
810
811 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
812 base += ffi->size * offset;
813
814 JSObjectRef owner(internal->GetOwner() ?: object);
815 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
816} CYCatch }
817
818static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
819 CYPool pool;
820 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
821 Type_privateData *typical(internal->type_);
822
823 if (typical->type_ == NULL)
824 return NULL;
825
826 ssize_t offset;
827 if (JSStringIsEqualToUTF8CString(property, "$cyi"))
828 offset = 0;
829 else if (!CYGetOffset(pool, context, property, offset))
830 return NULL;
831
832 ffi_type *ffi(typical->GetFFI());
833
834 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
835 base += ffi->size * offset;
836
837 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
838 return true;
839} CYCatch }
840
841static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
842 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
843 Type_privateData *typical(internal->type_);
844 return CYMakePointer(context, internal->value_, _not(size_t), typical->type_, typical->ffi_, _this);
845}
846
847static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
848 CYPool pool;
849 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
850 Type_privateData *typical(internal->type_);
851
852 ssize_t index;
853 uint8_t *base;
854
855 if (!Index_(pool, context, internal, property, index, base))
856 return NULL;
857
858 JSObjectRef owner(internal->GetOwner() ?: object);
859
860 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
861} CYCatch }
862
863static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
864 CYPool pool;
865 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
866 Type_privateData *typical(internal->type_);
867
868 ssize_t index;
869 uint8_t *base;
870
871 if (!Index_(pool, context, internal, property, index, base))
872 return false;
873
874 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
875 return true;
876} CYCatch }
877
878static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
879 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
880 Type_privateData *typical(internal->type_);
881 sig::Type *type(typical->type_);
882
883 if (type == NULL)
884 return;
885
886 size_t count(type->data.signature.count);
887 sig::Element *elements(type->data.signature.elements);
888
889 char number[32];
890
891 for (size_t index(0); index != count; ++index) {
892 const char *name;
893 name = elements[index].name;
894
895 if (name == NULL) {
896 sprintf(number, "%zu", index);
897 name = number;
898 }
899
900 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
901 }
902}
903
904JSValueRef 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 {
905 if (setups + count != signature->count - 1)
906 throw CYJSError(context, "incorrect number of arguments to ffi function");
907
908 size_t size(setups + count);
909 void *values[size];
910 memcpy(values, setup, sizeof(void *) * setups);
911
912 for (size_t index(setups); index != size; ++index) {
913 sig::Element *element(&signature->elements[index + 1]);
914 ffi_type *ffi(cif->arg_types[index]);
915 // XXX: alignment?
916 values[index] = new(pool) uint8_t[ffi->size];
917 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
918 }
919
920 uint8_t value[cif->rtype->size];
921
922 if (hooks_ != NULL && hooks_->CallFunction != NULL)
923 (*hooks_->CallFunction)(context, cif, function, value, values);
924 else
925 ffi_call(cif, function, value, values);
926
927 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
928} CYCatch }
929
930static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
931 CYPool pool;
932 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
933 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
934}
935
936static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
937 Type_privateData *internal(new Type_privateData(type));
938 return JSObjectMake(context, Type_privateData::Class_, internal);
939}
940
941static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
942 Type_privateData *internal(new Type_privateData(type));
943 return JSObjectMake(context, Type_privateData::Class_, internal);
944}
945
946static void *CYCastSymbol(const char *name) {
947 return dlsym(RTLD_DEFAULT, name);
948}
949
950static JSValueRef All_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
951 JSObjectRef global(CYGetGlobalObject(context));
952 JSObjectRef cycript(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Cycript"))));
953 if (JSValueRef value = CYGetProperty(context, cycript, property))
954 if (!JSValueIsUndefined(context, value))
955 return value;
956
957 CYPool pool;
958 CYUTF8String name(CYPoolUTF8String(pool, context, property));
959
960 if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
961 if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
962 return value;
963
2f51d6ab
JF
964 size_t length(name.size);
965 char keyed[length + 2];
966 memcpy(keyed + 1, name.data, length + 1);
967
968 static const char *modes = "0124";
969 for (size_t i(0); i != 4; ++i) {
970 char mode(modes[i]);
971 keyed[0] = mode;
972
973 if (CYBridgeEntry *entry = CYBridgeHash(keyed, length + 1))
974 switch (mode) {
975 case '0':
976 return JSEvaluateScript(CYGetJSContext(context), CYJSString(entry->value_), NULL, NULL, 0, NULL);
977
978 case '1':
979 if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
1850a470 980 return CYMakeFunctor(context, symbol, entry->value_, &entry->cache_);
2f51d6ab
JF
981 else return NULL;
982
983 case '2':
984 if (void *symbol = CYCastSymbol(name.data)) {
985 // XXX: this is horrendously inefficient
986 sig::Signature signature;
987 sig::Parse(pool, &signature, entry->value_, &Structor_);
988 ffi_cif cif;
989 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
990 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
991 } else return NULL;
992
993 // XXX: implement case 3
994 case '4':
995 return CYMakeType(context, entry->value_);
996 }
9cad30fa
JF
997 }
998
2f51d6ab 999 return NULL;
9cad30fa
JF
1000} CYCatch }
1001
1002static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1003 if (count != 2)
1004 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1005
1006 CYPool pool;
1007
1008 void *value(CYCastPointer<void *>(context, arguments[0]));
1009 const char *type(CYPoolCString(pool, context, arguments[1]));
1010
1011 sig::Signature signature;
1012 sig::Parse(pool, &signature, type, &Structor_);
1013
1014 return CYMakePointer(context, value, _not(size_t), signature.elements[0].type, NULL, NULL);
1015} CYCatch }
1016
1017static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1018 if (count != 1)
1019 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1020 CYPool pool;
1021 const char *type(CYPoolCString(pool, context, arguments[0]));
1022 return CYMakeType(context, type);
1023} CYCatch }
1024
1025static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1026 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1027
1028 sig::Type type;
1029
1030 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
1031 type.primitive = sig::pointer_P;
1032 type.data.data.size = 0;
1033 } else {
1034 CYPool pool;
1035 size_t index(CYGetIndex(pool, context, property));
1036 if (index == _not(size_t))
1037 return NULL;
1038 type.primitive = sig::array_P;
1039 type.data.data.size = index;
1040 }
1041
1042 type.name = NULL;
1043 type.flags = 0;
1044
1045 type.data.data.type = internal->type_;
1046
1047 return CYMakeType(context, &type);
1048} CYCatch }
1049
1050static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1051 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1052
1053 if (count != 1)
1054 throw CYJSError(context, "incorrect number of arguments to type cast function");
1055 sig::Type *type(internal->type_);
1056 ffi_type *ffi(internal->GetFFI());
1057 // XXX: alignment?
1058 uint8_t value[ffi->size];
1059 CYPool pool;
1060 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1061 return CYFromFFI(context, type, ffi, value);
1062} CYCatch }
1063
1064static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1065 if (count != 0)
1066 throw CYJSError(context, "incorrect number of arguments to type cast function");
1067 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1068
1069 sig::Type *type(internal->type_);
1070 size_t length;
1071
1072 if (type->primitive != sig::array_P)
1073 length = _not(size_t);
1074 else {
1075 length = type->data.data.size;
1076 type = type->data.data.type;
1077 }
1078
1079 void *value(malloc(internal->GetFFI()->size));
1080 return CYMakePointer(context, value, length, type, NULL, NULL);
1081} CYCatch }
1082
1083static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1084 if (count != 2)
1085 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1086 CYPool pool;
1087 const char *type(CYPoolCString(pool, context, arguments[1]));
1088 return CYMakeFunctor(context, arguments[0], type);
1089} CYCatch }
1090
1091static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1092 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1093 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1094} CYCatch }
1095
1096static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1097 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1098}
1099
1100static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1101 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1102 char string[32];
1103 sprintf(string, "%p", internal->value_);
1104 return CYCastJSValue(context, string);
1105} CYCatch }
1106
1107static JSValueRef Pointer_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1108 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(_this)));
1109 if (internal->length_ != _not(size_t)) {
1110 JSObjectRef Array(CYGetCachedObject(context, Array_s));
1111 JSObjectRef toCYON(CYCastJSObject(context, CYGetProperty(context, Array, toCYON_s)));
1112 return CYCallAsFunction(context, toCYON, _this, count, arguments);
1113 } else {
1114 char string[32];
1115 sprintf(string, "%p", internal->value_);
1116 return CYCastJSValue(context, string);
1117 }
1118} CYCatch }
1119
1120static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1121 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1122 CYPool pool;
1123 const char *type(sig::Unparse(pool, internal->type_));
1124 return CYCastJSValue(context, CYJSString(type));
1125} CYCatch }
1126
1127static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1128 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1129 CYPool pool;
1130 const char *type(sig::Unparse(pool, internal->type_));
1131 size_t size(strlen(type));
1132 char *cyon(new(pool) char[12 + size + 1]);
1133 memcpy(cyon, "new Type(\"", 10);
1134 cyon[12 + size] = '\0';
1135 cyon[12 + size - 2] = '"';
1136 cyon[12 + size - 1] = ')';
1137 memcpy(cyon + 10, type, size);
1138 return CYCastJSValue(context, CYJSString(cyon));
1139} CYCatch }
1140
1141static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1142 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1143}
1144
1145static JSStaticFunction Pointer_staticFunctions[4] = {
1146 {"toCYON", &Pointer_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1147 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1148 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1149 {NULL, NULL, 0}
1150};
1151
1152static JSStaticFunction Struct_staticFunctions[2] = {
1153 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1154 {NULL, NULL, 0}
1155};
1156
1157static JSStaticFunction Functor_staticFunctions[4] = {
1158 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1159 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1160 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1161 {NULL, NULL, 0}
1162};
1163
1164namespace cy {
1165 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1166}
1167
1168static JSStaticFunction Type_staticFunctions[4] = {
1169 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1170 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1171 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1172 {NULL, NULL, 0}
1173};
1174
1175static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
1176
1177void CYSetArgs(int argc, const char *argv[]) {
1178 JSContextRef context(CYGetJSContext());
1179 JSValueRef args[argc];
1180 for (int i(0); i != argc; ++i)
1181 args[i] = CYCastJSValue(context, argv[i]);
1182
1183 JSObjectRef array;
1184 if (JSObjectMakeArray$ != NULL) {
1185 JSValueRef exception(NULL);
1186 array = (*JSObjectMakeArray$)(context, argc, args, &exception);
1187 CYThrow(context, exception);
1188 } else {
1189 JSObjectRef Array(CYGetCachedObject(context, CYJSString("Array")));
1190 JSValueRef value(CYCallAsFunction(context, Array, NULL, argc, args));
1191 array = CYCastJSObject(context, value);
1192 }
1193
1194 JSObjectRef System(CYGetCachedObject(context, CYJSString("System")));
1195 CYSetProperty(context, System, CYJSString("args"), array);
1196}
1197
1198JSObjectRef CYGetGlobalObject(JSContextRef context) {
1199 return JSContextGetGlobalObject(context);
1200}
1201
1202const char *CYExecute(apr_pool_t *pool, const char *code) {
1203 JSContextRef context(CYGetJSContext());
1204 JSValueRef exception(NULL), result;
1205
1206 void *handle;
1207 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
1208 handle = (*hooks_->ExecuteStart)(context);
1209 else
1210 handle = NULL;
1211
1212 const char *json;
1213
1214 try {
1215 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1216 } catch (const char *error) {
1217 return error;
1218 }
1219
1220 if (exception != NULL) { error:
1221 result = exception;
1222 exception = NULL;
1223 }
1224
1225 if (JSValueIsUndefined(context, result))
1226 return NULL;
1227
1228 try {
1229 json = CYPoolCCYON(pool, context, result, &exception);
1230 } catch (const char *error) {
1231 return error;
1232 }
1233
1234 if (exception != NULL)
1235 goto error;
1236
1237 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1238
1239 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
1240 (*hooks_->ExecuteEnd)(context, handle);
1241 return json;
1242}
1243
1244extern "C" void CydgetSetupContext(JSGlobalContextRef context) {
1245 CYSetupContext(context);
1246}
1247
09eee478
JF
1248static bool initialized_ = false;
1249
9cad30fa 1250void CYInitializeDynamic() {
09eee478
JF
1251 if (!initialized_)
1252 initialized_ = true;
1253 else return;
1254
9cad30fa
JF
1255 CYInitializeStatic();
1256
9cad30fa
JF
1257 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
1258
1259 JSClassDefinition definition;
1260
1261 definition = kJSClassDefinitionEmpty;
1262 definition.className = "All";
1263 definition.getProperty = &All_getProperty;
1264 All_ = JSClassCreate(&definition);
1265
1266 definition = kJSClassDefinitionEmpty;
1267 definition.className = "Context";
1268 definition.finalize = &CYFinalize;
1269 Context_ = JSClassCreate(&definition);
1270
1271 definition = kJSClassDefinitionEmpty;
1272 definition.className = "Functor";
1273 definition.staticFunctions = cy::Functor::StaticFunctions;
1274 definition.callAsFunction = &Functor_callAsFunction;
1275 definition.finalize = &CYFinalize;
1276 Functor_ = JSClassCreate(&definition);
1277
1278 definition = kJSClassDefinitionEmpty;
1279 definition.className = "Pointer";
1280 definition.staticFunctions = Pointer_staticFunctions;
1281 definition.getProperty = &Pointer_getProperty;
1282 definition.setProperty = &Pointer_setProperty;
1283 definition.finalize = &CYFinalize;
1284 Pointer_ = JSClassCreate(&definition);
1285
1286 definition = kJSClassDefinitionEmpty;
1287 definition.className = "Struct";
1288 definition.staticFunctions = Struct_staticFunctions;
1289 definition.getProperty = &Struct_getProperty;
1290 definition.setProperty = &Struct_setProperty;
1291 definition.getPropertyNames = &Struct_getPropertyNames;
1292 definition.finalize = &CYFinalize;
1293 Struct_ = JSClassCreate(&definition);
1294
1295 definition = kJSClassDefinitionEmpty;
1296 definition.className = "Type";
1297 definition.staticFunctions = Type_staticFunctions;
1298 definition.getProperty = &Type_getProperty;
1299 definition.callAsFunction = &Type_callAsFunction;
1300 definition.callAsConstructor = &Type_callAsConstructor;
1301 definition.finalize = &CYFinalize;
1302 Type_privateData::Class_ = JSClassCreate(&definition);
1303
1304 definition = kJSClassDefinitionEmpty;
1305 //definition.getProperty = &Global_getProperty;
1306 Global_ = JSClassCreate(&definition);
1307
1308 Array_s = JSStringCreateWithUTF8CString("Array");
1309 cy_s = JSStringCreateWithUTF8CString("$cy");
1310 length_s = JSStringCreateWithUTF8CString("length");
1311 message_s = JSStringCreateWithUTF8CString("message");
1312 name_s = JSStringCreateWithUTF8CString("name");
1313 pop_s = JSStringCreateWithUTF8CString("pop");
1314 prototype_s = JSStringCreateWithUTF8CString("prototype");
1315 push_s = JSStringCreateWithUTF8CString("push");
1316 splice_s = JSStringCreateWithUTF8CString("splice");
1317 toCYON_s = JSStringCreateWithUTF8CString("toCYON");
1318 toJSON_s = JSStringCreateWithUTF8CString("toJSON");
20ded97a 1319 toPointer_s = JSStringCreateWithUTF8CString("toPointer");
9cad30fa
JF
1320
1321 Result_ = JSStringCreateWithUTF8CString("_");
1322
1323 if (hooks_ != NULL && hooks_->Initialize != NULL)
1324 (*hooks_->Initialize)();
1325}
1326
1327void CYThrow(JSContextRef context, JSValueRef value) {
1328 if (value != NULL)
1329 throw CYJSError(context, value);
1330}
1331
1332const char *CYJSError::PoolCString(apr_pool_t *pool) const {
1333 // XXX: this used to be CYPoolCString
1334 return CYPoolCCYON(pool, context_, value_);
1335}
1336
1337JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1338 // XXX: what if the context is different?
1339 return value_;
1340}
1341
1342JSValueRef CYCastJSError(JSContextRef context, const char *message) {
1343 JSObjectRef Error(CYGetCachedObject(context, CYJSString("Error")));
1344
1345 JSValueRef arguments[1] = {CYCastJSValue(context, message)};
1346
1347 JSValueRef exception(NULL);
1348 JSValueRef value(JSObjectCallAsConstructor(context, Error, 1, arguments, &exception));
1349 CYThrow(context, exception);
1350
1351 return value;
1352}
1353
1354JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1355 return CYCastJSError(context, message_);
1356}
1357
1358CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1359 _assert(context != NULL);
1360
1361 CYPool pool;
1362
1363 va_list args;
1364 va_start(args, format);
1365 const char *message(apr_pvsprintf(pool, format, args));
1366 va_end(args);
1367
1368 value_ = CYCastJSError(context, message);
1369}
1370
1371JSGlobalContextRef CYGetJSContext(JSContextRef context) {
1372 return reinterpret_cast<Context *>(JSObjectGetPrivate(CYCastJSObject(context, CYGetProperty(context, CYGetGlobalObject(context), cy_s))))->context_;
1373}
1374
1375extern "C" void CYSetupContext(JSGlobalContextRef context) {
1376 CYInitializeDynamic();
1377
1378 JSObjectRef global(CYGetGlobalObject(context));
1379
1380 JSObjectRef cy(JSObjectMake(context, Context_, new Context(context)));
1381 CYSetProperty(context, global, cy_s, cy, kJSPropertyAttributeDontEnum);
1382
1383/* Cache Globals {{{ */
1384 JSObjectRef Array(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array"))));
1385 CYSetProperty(context, cy, CYJSString("Array"), Array);
1386
1387 JSObjectRef Array_prototype(CYCastJSObject(context, CYGetProperty(context, Array, prototype_s)));
1388 CYSetProperty(context, cy, CYJSString("Array_prototype"), Array_prototype);
1389
1390 JSObjectRef Error(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error"))));
1391 CYSetProperty(context, cy, CYJSString("Error"), Error);
1392
1393 JSObjectRef Function(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function"))));
1394 CYSetProperty(context, cy, CYJSString("Function"), Function);
1395
1396 JSObjectRef Function_prototype(CYCastJSObject(context, CYGetProperty(context, Function, prototype_s)));
1397 CYSetProperty(context, cy, CYJSString("Function_prototype"), Function_prototype);
1398
1399 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1400 CYSetProperty(context, cy, CYJSString("Object"), Object);
1401
1402 JSObjectRef Object_prototype(CYCastJSObject(context, CYGetProperty(context, Object, prototype_s)));
1403 CYSetProperty(context, cy, CYJSString("Object_prototype"), Object_prototype);
1404
1405 JSObjectRef String(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String"))));
1406 CYSetProperty(context, cy, CYJSString("String"), String);
1407/* }}} */
1408
1409 CYSetProperty(context, Array_prototype, toCYON_s, &Array_callAsFunction_toCYON, kJSPropertyAttributeDontEnum);
1410
1411 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1412 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1413 CYSetProperty(context, cycript, CYJSString("gc"), &Cycript_gc_callAsFunction);
1414
1415 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1416 JSObjectSetPrototype(context, CYCastJSObject(context, CYGetProperty(context, Functor, prototype_s)), Function_prototype);
1417 CYSetProperty(context, cycript, CYJSString("Functor"), Functor);
1418
1419 CYSetProperty(context, cycript, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1420 CYSetProperty(context, cycript, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1421
1422 JSObjectRef all(JSObjectMake(context, All_, NULL));
1423 CYSetProperty(context, cycript, CYJSString("all"), all);
1424
1425 JSObjectRef last(NULL), curr(global);
1426
1427 goto next; for (JSValueRef next;;) {
1428 if (JSValueIsNull(context, next))
1429 break;
1430 last = curr;
1431 curr = CYCastJSObject(context, next);
1432 next:
1433 next = JSObjectGetPrototype(context, curr);
1434 }
1435
1436 JSObjectSetPrototype(context, last, all);
1437
1438 CYSetProperty(context, global, CYJSString("$cyq"), &$cyq);
1439
1440 JSObjectRef System(JSObjectMake(context, NULL, NULL));
cdc80ff2 1441 CYSetProperty(context, cy, CYJSString("System"), System);
9cad30fa
JF
1442
1443 CYSetProperty(context, global, CYJSString("system"), System);
1444 CYSetProperty(context, System, CYJSString("args"), CYJSNull(context));
1445 //CYSetProperty(context, System, CYJSString("global"), global);
1446 CYSetProperty(context, System, CYJSString("print"), &System_print);
1447
1448 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1449 (*hooks_->SetupContext)(context);
1450}
1451
1452JSGlobalContextRef CYGetJSContext() {
1453 CYInitializeDynamic();
1454
1455 static JSGlobalContextRef context_;
1456
1457 if (context_ == NULL) {
1458 context_ = JSGlobalContextCreate(Global_);
1459 CYSetupContext(context_);
1460 }
1461
1462 return context_;
1463}