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