]> git.saurik.com Git - cycript.git/blame - Library.cpp
Fixed GNUstep.
[cycript.git] / Library.cpp
CommitLineData
d15b59f5 1/* Cycript - Inlining/Optimizing JavaScript Compiler
37954781
JF
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
40#include <sqlite3.h>
41
42#include "Internal.hpp"
43
44#include <dlfcn.h>
45#include <iconv.h>
46
47#include "cycript.hpp"
48
49#include "sig/parse.hpp"
50#include "sig/ffi_type.hpp"
51
52#include "Pooling.hpp"
53
54#include <sys/mman.h>
55
56#include <iostream>
57#include <ext/stdio_filebuf.h>
58#include <set>
59#include <map>
60#include <iomanip>
61#include <sstream>
62#include <cmath>
63
64#include "Parser.hpp"
65#include "Cycript.tab.hh"
66
67#include "Error.hpp"
68#include "JavaScript.hpp"
69#include "String.hpp"
70
71#ifdef __OBJC__
72#define CYCatch_ \
73 catch (NSException *error) { \
74 CYThrow(context, error, exception); \
75 return NULL; \
76 }
77#else
78#define CYCatch_
79#endif
80
81char *sqlite3_column_pooled(apr_pool_t *pool, sqlite3_stmt *stmt, int n) {
82 if (const unsigned char *value = sqlite3_column_text(stmt, n))
83 return apr_pstrdup(pool, (const char *) value);
84 else return NULL;
85}
86
87struct CYHooks *hooks_;
88
89/* JavaScript Properties {{{ */
90JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, size_t index) {
91 JSValueRef exception(NULL);
92 JSValueRef value(JSObjectGetPropertyAtIndex(context, object, index, &exception));
93 CYThrow(context, exception);
94 return value;
95}
96
97JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
98 JSValueRef exception(NULL);
99 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
100 CYThrow(context, exception);
101 return value;
102}
103
104void CYSetProperty(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value) {
105 JSValueRef exception(NULL);
106 JSObjectSetPropertyAtIndex(context, object, index, value, &exception);
107 CYThrow(context, exception);
108}
109
110void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value, JSPropertyAttributes attributes) {
111 JSValueRef exception(NULL);
112 JSObjectSetProperty(context, object, name, value, attributes, &exception);
113 CYThrow(context, exception);
114}
115/* }}} */
116/* JavaScript Strings {{{ */
117JSStringRef CYCopyJSString(const char *value) {
118 return value == NULL ? NULL : JSStringCreateWithUTF8CString(value);
119}
120
121JSStringRef CYCopyJSString(JSStringRef value) {
122 return value == NULL ? NULL : JSStringRetain(value);
123}
124
125JSStringRef CYCopyJSString(CYUTF8String value) {
126 // XXX: this is very wrong
127 return CYCopyJSString(value.data);
128}
129
130JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
131 if (JSValueIsNull(context, value))
132 return NULL;
133 JSValueRef exception(NULL);
134 JSStringRef string(JSValueToStringCopy(context, value, &exception));
135 CYThrow(context, exception);
136 return string;
137}
138
139static CYUTF16String CYCastUTF16String(JSStringRef value) {
140 return CYUTF16String(JSStringGetCharactersPtr(value), JSStringGetLength(value));
141}
142
93760f3f
JF
143template <typename Type_>
144_finline size_t iconv_(size_t (*iconv)(iconv_t, Type_, size_t *, char **, size_t *), iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft) {
145 return iconv(cd, const_cast<Type_>(inbuf), inbytesleft, outbuf, outbytesleft);
146}
147
aabea98c 148CYUTF8String CYPoolUTF8String(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
37954781
JF
149 _assert(pool != NULL);
150
151 CYUTF16String utf16(CYCastUTF16String(value));
152 const char *in(reinterpret_cast<const char *>(utf16.data));
153
51a72a9d 154#ifdef __GLIBC__
28926538 155 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2")));
51a72a9d
JF
156#else
157 iconv_t conversion(_syscall(iconv_open("UTF-8", "UCS-2-INTERNAL")));
28926538 158#endif
37954781
JF
159
160 size_t size(JSStringGetMaximumUTF8CStringSize(value));
161 char *out(new(pool) char[size]);
162 CYUTF8String utf8(out, size);
163
164 size = utf16.size * 2;
93760f3f 165 _syscall(iconv_(&iconv, conversion, const_cast<char **>(&in), &size, &out, &utf8.size));
37954781
JF
166
167 *out = '\0';
168 utf8.size = out - utf8.data;
169
170 _syscall(iconv_close(conversion));
171
172 return utf8;
173}
174
175const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
176 CYUTF8String utf8(CYPoolUTF8String(pool, context, value));
177 _assert(memchr(utf8.data, '\0', utf8.size) == NULL);
178 return utf8.data;
179}
180
181const char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
182 return JSValueIsNull(context, value) ? NULL : CYPoolCString(pool, context, CYJSString(context, value));
183}
184/* }}} */
185
186/* Index Offsets {{{ */
187size_t CYGetIndex(const CYUTF8String &value) {
188 if (value.data[0] != '0') {
ba4fa42f
JF
189 size_t index(0);
190 for (size_t i(0); i != value.size; ++i) {
191 if (!DigitRange_[value.data[i]])
192 return _not(size_t);
193 index *= 10;
194 index += value.data[i] - '0';
195 }
196 return index;
197 } else if (value.size == 1)
37954781 198 return 0;
ba4fa42f
JF
199 else
200 return _not(size_t);
37954781
JF
201}
202
203size_t CYGetIndex(apr_pool_t *pool, JSContextRef context, JSStringRef value) {
204 return CYGetIndex(CYPoolUTF8String(pool, context, value));
205}
206
ba4fa42f 207// XXX: this isn't actually right
37954781
JF
208bool CYGetOffset(const char *value, ssize_t &index) {
209 if (value[0] != '0') {
210 char *end;
211 index = strtol(value, &end, 10);
212 if (value + strlen(value) == end)
213 return true;
214 } else if (value[1] == '\0') {
215 index = 0;
216 return true;
217 }
218
219 return false;
220}
221/* }}} */
222
223/* JavaScript *ify {{{ */
224void CYStringify(std::ostringstream &str, const char *data, size_t size) {
225 unsigned quot(0), apos(0);
226 for (const char *value(data), *end(data + size); value != end; ++value)
227 if (*value == '"')
228 ++quot;
229 else if (*value == '\'')
230 ++apos;
231
232 bool single(quot > apos);
233
234 str << (single ? '\'' : '"');
235
236 for (const char *value(data), *end(data + size); value != end; ++value)
237 switch (*value) {
238 case '\\': str << "\\\\"; break;
239 case '\b': str << "\\b"; break;
240 case '\f': str << "\\f"; break;
241 case '\n': str << "\\n"; break;
242 case '\r': str << "\\r"; break;
243 case '\t': str << "\\t"; break;
244 case '\v': str << "\\v"; break;
245
246 case '"':
247 if (!single)
248 str << "\\\"";
249 else goto simple;
250 break;
251
252 case '\'':
253 if (single)
254 str << "\\'";
255 else goto simple;
256 break;
257
258 default:
51a72a9d 259 // this test is designed to be "awewsome", generating neither warnings nor incorrect results
37954781 260 if (*value < 0x20 || *value >= 0x7f)
51a72a9d 261 str << "\\x" << std::setbase(16) << std::setw(2) << std::setfill('0') << unsigned(uint8_t(*value));
37954781
JF
262 else simple:
263 str << *value;
264 }
265
266 str << (single ? '\'' : '"');
267}
268
269void CYNumerify(std::ostringstream &str, double value) {
270 char string[32];
271 // XXX: I want this to print 1e3 rather than 1000
272 sprintf(string, "%.17g", value);
273 str << string;
274}
275
276bool CYIsKey(CYUTF8String value) {
277 const char *data(value.data);
278 size_t size(value.size);
279
280 if (size == 0)
281 return false;
282
283 if (DigitRange_[data[0]]) {
284 size_t index(CYGetIndex(value));
285 if (index == _not(size_t))
286 return false;
287 } else {
288 if (!WordStartRange_[data[0]])
289 return false;
290 for (size_t i(1); i != size; ++i)
291 if (!WordEndRange_[data[i]])
292 return false;
293 }
294
295 return true;
296}
297/* }}} */
298
299static JSGlobalContextRef Context_;
300static JSObjectRef System_;
301
302static JSClassRef Functor_;
303static JSClassRef Pointer_;
304static JSClassRef Runtime_;
305static JSClassRef Struct_;
306
307static JSStringRef Result_;
308
309JSObjectRef Array_;
310JSObjectRef Error_;
311JSObjectRef Function_;
312JSObjectRef String_;
313
314JSStringRef length_;
315JSStringRef message_;
316JSStringRef name_;
317JSStringRef prototype_;
318JSStringRef toCYON_;
319JSStringRef toJSON_;
320
321JSObjectRef Object_prototype_;
322JSObjectRef Function_prototype_;
323
324JSObjectRef Array_prototype_;
325JSObjectRef Array_pop_;
326JSObjectRef Array_push_;
327JSObjectRef Array_splice_;
328
329sqlite3 *Bridge_;
330
331void CYFinalize(JSObjectRef object) {
332 delete reinterpret_cast<CYData *>(JSObjectGetPrivate(object));
333}
334
335struct CStringMapLess :
336 std::binary_function<const char *, const char *, bool>
337{
338 _finline bool operator ()(const char *lhs, const char *rhs) const {
339 return strcmp(lhs, rhs) < 0;
340 }
341};
342
343void Structor_(apr_pool_t *pool, const char *name, const char *types, sig::Type *&type) {
344 if (name == NULL)
345 return;
346
347 sqlite3_stmt *statement;
348
349 _sqlcall(sqlite3_prepare(Bridge_,
350 "select "
351 "\"bridge\".\"mode\", "
352 "\"bridge\".\"value\" "
353 "from \"bridge\" "
354 "where"
355 " \"bridge\".\"mode\" in (3, 4) and"
356 " \"bridge\".\"name\" = ?"
357 " limit 1"
358 , -1, &statement, NULL));
359
360 _sqlcall(sqlite3_bind_text(statement, 1, name, -1, SQLITE_STATIC));
361
362 int mode;
363 const char *value;
364
365 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
366 mode = -1;
367 value = NULL;
368 } else {
369 mode = sqlite3_column_int(statement, 0);
370 value = sqlite3_column_pooled(pool, statement, 1);
371 }
372
373 _sqlcall(sqlite3_finalize(statement));
374
375 switch (mode) {
376 default:
377 _assert(false);
378 case -1:
379 break;
380
381 case 3: {
382 sig::Parse(pool, &type->data.signature, value, &Structor_);
383 } break;
384
385 case 4: {
386 sig::Signature signature;
387 sig::Parse(pool, &signature, value, &Structor_);
388 type = signature.elements[0].type;
389 } break;
390 }
391}
392
393JSClassRef Type_privateData::Class_;
394
395struct Pointer :
396 CYOwned
397{
398 Type_privateData *type_;
399
400 Pointer(void *value, JSContextRef context, JSObjectRef owner, sig::Type *type) :
401 CYOwned(value, context, owner),
402 type_(new(pool_) Type_privateData(type))
403 {
404 }
405};
406
407struct Struct_privateData :
408 CYOwned
409{
410 Type_privateData *type_;
411
412 Struct_privateData(JSContextRef context, JSObjectRef owner) :
413 CYOwned(NULL, context, owner)
414 {
415 }
416};
417
418typedef std::map<const char *, Type_privateData *, CStringMapLess> TypeMap;
419static TypeMap Types_;
420
421JSObjectRef CYMakeStruct(JSContextRef context, void *data, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
422 Struct_privateData *internal(new Struct_privateData(context, owner));
423 apr_pool_t *pool(internal->pool_);
424 Type_privateData *typical(new(pool) Type_privateData(type, ffi));
425 internal->type_ = typical;
426
427 if (owner != NULL)
428 internal->value_ = data;
429 else {
430 size_t size(typical->GetFFI()->size);
431 void *copy(apr_palloc(internal->pool_, size));
432 memcpy(copy, data, size);
433 internal->value_ = copy;
434 }
435
436 return JSObjectMake(context, Struct_, internal);
437}
438
439JSValueRef CYCastJSValue(JSContextRef context, bool value) {
440 return JSValueMakeBoolean(context, value);
441}
442
443JSValueRef CYCastJSValue(JSContextRef context, double value) {
444 return JSValueMakeNumber(context, value);
445}
446
447#define CYCastJSValue_(Type_) \
448 JSValueRef CYCastJSValue(JSContextRef context, Type_ value) { \
449 return JSValueMakeNumber(context, static_cast<double>(value)); \
450 }
451
452CYCastJSValue_(int)
453CYCastJSValue_(unsigned int)
454CYCastJSValue_(long int)
455CYCastJSValue_(long unsigned int)
456CYCastJSValue_(long long int)
457CYCastJSValue_(long long unsigned int)
458
459JSValueRef CYJSUndefined(JSContextRef context) {
460 return JSValueMakeUndefined(context);
461}
462
463double CYCastDouble(const char *value, size_t size) {
464 char *end;
465 double number(strtod(value, &end));
466 if (end != value + size)
467 return NAN;
468 return number;
469}
470
471double CYCastDouble(const char *value) {
472 return CYCastDouble(value, strlen(value));
473}
474
475double CYCastDouble(JSContextRef context, JSValueRef value) {
476 JSValueRef exception(NULL);
477 double number(JSValueToNumber(context, value, &exception));
478 CYThrow(context, exception);
479 return number;
480}
481
482bool CYCastBool(JSContextRef context, JSValueRef value) {
483 return JSValueToBoolean(context, value);
484}
485
486JSValueRef CYJSNull(JSContextRef context) {
487 return JSValueMakeNull(context);
488}
489
490JSValueRef CYCastJSValue(JSContextRef context, JSStringRef value) {
491 return value == NULL ? CYJSNull(context) : JSValueMakeString(context, value);
492}
493
494JSValueRef CYCastJSValue(JSContextRef context, const char *value) {
495 return CYCastJSValue(context, CYJSString(value));
496}
497
498JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
499 JSValueRef exception(NULL);
500 JSObjectRef object(JSValueToObject(context, value, &exception));
501 CYThrow(context, exception);
502 return object;
503}
504
505JSValueRef CYCallAsFunction(JSContextRef context, JSObjectRef function, JSObjectRef _this, size_t count, JSValueRef arguments[]) {
506 JSValueRef exception(NULL);
507 JSValueRef value(JSObjectCallAsFunction(context, function, _this, count, arguments, &exception));
508 CYThrow(context, exception);
509 return value;
510}
511
512bool CYIsCallable(JSContextRef context, JSValueRef value) {
513 return value != NULL && JSValueIsObject(context, value) && JSObjectIsFunction(context, (JSObjectRef) value);
514}
515
516static JSValueRef System_print(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
517 if (count == 0)
518 printf("\n");
519 else {
520 CYPool pool;
521 printf("%s\n", CYPoolCString(pool, context, arguments[0]));
522 }
523
524 return CYJSUndefined(context);
525} CYCatch }
526
527static size_t Nonce_(0);
528
529static JSValueRef $cyq(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
530 CYPool pool;
531 const char *name(apr_psprintf(pool, "%s%zu", CYPoolCString(pool, context, arguments[0]), Nonce_++));
532 return CYCastJSValue(context, name);
533}
534
535static JSValueRef Cycript_gc_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
536 JSGarbageCollect(context);
537 return CYJSUndefined(context);
538}
539
540const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value, JSValueRef *exception) { CYTry {
541 switch (JSType type = JSValueGetType(context, value)) {
542 case kJSTypeUndefined:
543 return "undefined";
544 case kJSTypeNull:
545 return "null";
546 case kJSTypeBoolean:
547 return CYCastBool(context, value) ? "true" : "false";
548
549 case kJSTypeNumber: {
550 std::ostringstream str;
551 CYNumerify(str, CYCastDouble(context, value));
552 std::string value(str.str());
553 return apr_pstrmemdup(pool, value.c_str(), value.size());
554 } break;
555
556 case kJSTypeString: {
557 std::ostringstream str;
558 CYUTF8String string(CYPoolUTF8String(pool, context, CYJSString(context, value)));
559 CYStringify(str, string.data, string.size);
560 std::string value(str.str());
561 return apr_pstrmemdup(pool, value.c_str(), value.size());
562 } break;
563
564 case kJSTypeObject:
565 return CYPoolCCYON(pool, context, (JSObjectRef) value);
566 default:
567 throw CYJSError(context, "JSValueGetType() == 0x%x", type);
568 }
569} CYCatch }
570
571const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
572 JSValueRef exception(NULL);
573 const char *cyon(CYPoolCCYON(pool, context, value, &exception));
574 CYThrow(context, exception);
575 return cyon;
576}
577
578const char *CYPoolCCYON(apr_pool_t *pool, JSContextRef context, JSObjectRef object) {
579 JSValueRef toCYON(CYGetProperty(context, object, toCYON_));
580 if (CYIsCallable(context, toCYON)) {
581 JSValueRef value(CYCallAsFunction(context, (JSObjectRef) toCYON, object, 0, NULL));
582 return CYPoolCString(pool, context, value);
583 }
584
585 JSValueRef toJSON(CYGetProperty(context, object, toJSON_));
586 if (CYIsCallable(context, toJSON)) {
587 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(""))};
588 JSValueRef exception(NULL);
589 const char *cyon(CYPoolCCYON(pool, context, CYCallAsFunction(context, (JSObjectRef) toJSON, object, 1, arguments), &exception));
590 CYThrow(context, exception);
591 return cyon;
592 }
593
594 std::ostringstream str;
595
596 str << '{';
597
598 // XXX: this is, sadly, going to leak
599 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context, object));
600
601 bool comma(false);
602
603 for (size_t index(0), count(JSPropertyNameArrayGetCount(names)); index != count; ++index) {
604 JSStringRef name(JSPropertyNameArrayGetNameAtIndex(names, index));
605 JSValueRef value(CYGetProperty(context, object, name));
606
607 if (comma)
608 str << ',';
609 else
610 comma = true;
611
612 CYUTF8String string(CYPoolUTF8String(pool, context, name));
613 if (CYIsKey(string))
614 str << string.data;
615 else
616 CYStringify(str, string.data, string.size);
617
618 str << ':' << CYPoolCCYON(pool, context, value);
619 }
620
621 str << '}';
622
623 JSPropertyNameArrayRelease(names);
624
625 std::string string(str.str());
626 return apr_pstrmemdup(pool, string.c_str(), string.size());
627}
628
629static JSValueRef Array_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
630 CYPool pool;
631 std::ostringstream str;
632
633 str << '[';
634
635 JSValueRef length(CYGetProperty(context, _this, length_));
636 bool comma(false);
637
638 for (size_t index(0), count(CYCastDouble(context, length)); index != count; ++index) {
639 JSValueRef value(CYGetProperty(context, _this, index));
640
641 if (comma)
642 str << ',';
643 else
644 comma = true;
645
646 if (!JSValueIsUndefined(context, value))
647 str << CYPoolCCYON(pool, context, value);
648 else {
649 str << ',';
650 comma = false;
651 }
652 }
653
654 str << ']';
655
656 std::string value(str.str());
657 return CYCastJSValue(context, CYJSString(CYUTF8String(value.c_str(), value.size())));
658} CYCatch }
659
660JSObjectRef CYMakePointer(JSContextRef context, void *pointer, sig::Type *type, ffi_type *ffi, JSObjectRef owner) {
661 Pointer *internal(new Pointer(pointer, context, owner, type));
662 return JSObjectMake(context, Pointer_, internal);
663}
664
665static JSObjectRef CYMakeFunctor(JSContextRef context, void (*function)(), const char *type) {
666 cy::Functor *internal(new cy::Functor(type, function));
667 return JSObjectMake(context, Functor_, internal);
668}
669
670static bool CYGetOffset(apr_pool_t *pool, JSContextRef context, JSStringRef value, ssize_t &index) {
671 return CYGetOffset(CYPoolCString(pool, context, value), index);
672}
673
674void *CYCastPointer_(JSContextRef context, JSValueRef value) {
675 switch (JSValueGetType(context, value)) {
676 case kJSTypeNull:
677 return NULL;
678 /*case kJSTypeObject:
679 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
680 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate((JSObjectRef) value)));
681 return internal->value_;
682 }*/
683 default:
684 double number(CYCastDouble(context, value));
685 if (std::isnan(number))
686 throw CYJSError(context, "cannot convert value to pointer");
687 return reinterpret_cast<void *>(static_cast<uintptr_t>(static_cast<long long>(number)));
688 }
689}
690
691void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, JSValueRef value) {
692 switch (type->primitive) {
693 case sig::boolean_P:
694 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
695 break;
696
697#define CYPoolFFI_(primitive, native) \
698 case sig::primitive ## _P: \
699 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
700 break;
701
702 CYPoolFFI_(uchar, unsigned char)
703 CYPoolFFI_(char, char)
704 CYPoolFFI_(ushort, unsigned short)
705 CYPoolFFI_(short, short)
706 CYPoolFFI_(ulong, unsigned long)
707 CYPoolFFI_(long, long)
708 CYPoolFFI_(uint, unsigned int)
709 CYPoolFFI_(int, int)
710 CYPoolFFI_(ulonglong, unsigned long long)
711 CYPoolFFI_(longlong, long long)
712 CYPoolFFI_(float, float)
713 CYPoolFFI_(double, double)
714
715 case sig::pointer_P:
716 *reinterpret_cast<void **>(data) = CYCastPointer<void *>(context, value);
717 break;
718
719 case sig::string_P:
720 *reinterpret_cast<const char **>(data) = CYPoolCString(pool, context, value);
721 break;
722
723 case sig::struct_P: {
724 uint8_t *base(reinterpret_cast<uint8_t *>(data));
725 JSObjectRef aggregate(JSValueIsObject(context, value) ? (JSObjectRef) value : NULL);
726 for (size_t index(0); index != type->data.signature.count; ++index) {
727 sig::Element *element(&type->data.signature.elements[index]);
728 ffi_type *field(ffi->elements[index]);
729
730 JSValueRef rhs;
731 if (aggregate == NULL)
732 rhs = value;
733 else {
734 rhs = CYGetProperty(context, aggregate, index);
735 if (JSValueIsUndefined(context, rhs)) {
736 if (element->name != NULL)
737 rhs = CYGetProperty(context, aggregate, CYJSString(element->name));
738 else
739 goto undefined;
740 if (JSValueIsUndefined(context, rhs)) undefined:
741 throw CYJSError(context, "unable to extract structure value");
742 }
743 }
744
745 CYPoolFFI(pool, context, element->type, field, base, rhs);
746 // XXX: alignment?
747 base += field->size;
748 }
749 } break;
750
751 case sig::void_P:
752 break;
753
754 default:
755 if (hooks_ != NULL && hooks_->PoolFFI != NULL)
756 if ((*hooks_->PoolFFI)(pool, context, type, ffi, data, value))
757 return;
758
759 fprintf(stderr, "CYPoolFFI(%c)\n", type->primitive);
760 _assert(false);
761 }
762}
763
764JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, ffi_type *ffi, void *data, bool initialize, JSObjectRef owner) {
765 switch (type->primitive) {
766 case sig::boolean_P:
767 return CYCastJSValue(context, *reinterpret_cast<bool *>(data));
768
769#define CYFromFFI_(primitive, native) \
770 case sig::primitive ## _P: \
771 return CYCastJSValue(context, *reinterpret_cast<native *>(data)); \
772
773 CYFromFFI_(uchar, unsigned char)
774 CYFromFFI_(char, char)
775 CYFromFFI_(ushort, unsigned short)
776 CYFromFFI_(short, short)
777 CYFromFFI_(ulong, unsigned long)
778 CYFromFFI_(long, long)
779 CYFromFFI_(uint, unsigned int)
780 CYFromFFI_(int, int)
781 CYFromFFI_(ulonglong, unsigned long long)
782 CYFromFFI_(longlong, long long)
783 CYFromFFI_(float, float)
784 CYFromFFI_(double, double)
785
786 case sig::pointer_P:
787 if (void *pointer = *reinterpret_cast<void **>(data))
788 return CYMakePointer(context, pointer, type->data.data.type, ffi, owner);
789 else goto null;
790
791 case sig::string_P:
792 if (char *utf8 = *reinterpret_cast<char **>(data))
793 return CYCastJSValue(context, utf8);
794 else goto null;
795
796 case sig::struct_P:
797 return CYMakeStruct(context, data, type, ffi, owner);
798 case sig::void_P:
799 return CYJSUndefined(context);
800
801 null:
802 return CYJSNull(context);
803 default:
804 if (hooks_ != NULL && hooks_->FromFFI != NULL)
805 if (JSValueRef value = (*hooks_->FromFFI)(context, type, ffi, data, initialize, owner))
806 return value;
807
808 fprintf(stderr, "CYFromFFI(%c)\n", type->primitive);
809 _assert(false);
810 }
811}
812
813static void FunctionClosure_(ffi_cif *cif, void *result, void **arguments, void *arg) {
814 Closure_privateData *internal(reinterpret_cast<Closure_privateData *>(arg));
815
816 JSContextRef context(internal->context_);
817
818 size_t count(internal->cif_.nargs);
819 JSValueRef values[count];
820
821 for (size_t index(0); index != count; ++index)
822 values[index] = CYFromFFI(context, internal->signature_.elements[1 + index].type, internal->cif_.arg_types[index], arguments[index]);
823
824 JSValueRef value(CYCallAsFunction(context, internal->function_, NULL, count, values));
825 CYPoolFFI(NULL, context, internal->signature_.elements[0].type, internal->cif_.rtype, result, value);
826}
827
828Closure_privateData *CYMakeFunctor_(JSContextRef context, JSObjectRef function, const char *type, void (*callback)(ffi_cif *, void *, void **, void *)) {
829 // XXX: in case of exceptions this will leak
830 // XXX: in point of fact, this may /need/ to leak :(
831 Closure_privateData *internal(new Closure_privateData(CYGetJSContext(), function, type));
832
833 ffi_closure *closure((ffi_closure *) _syscall(mmap(
834 NULL, sizeof(ffi_closure),
835 PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE,
836 -1, 0
837 )));
838
839 ffi_status status(ffi_prep_closure(closure, &internal->cif_, callback, internal));
840 _assert(status == FFI_OK);
841
842 _syscall(mprotect(closure, sizeof(*closure), PROT_READ | PROT_EXEC));
843
844 internal->value_ = closure;
845
846 return internal;
847}
848
849static JSObjectRef CYMakeFunctor(JSContextRef context, JSObjectRef function, const char *type) {
850 Closure_privateData *internal(CYMakeFunctor_(context, function, type, &FunctionClosure_));
851 return JSObjectMake(context, Functor_, internal);
852}
853
854static JSObjectRef CYMakeFunctor(JSContextRef context, JSValueRef value, const char *type) {
855 JSValueRef exception(NULL);
856 bool function(JSValueIsInstanceOfConstructor(context, value, Function_, &exception));
857 CYThrow(context, exception);
858
859 if (function) {
860 JSObjectRef function(CYCastJSObject(context, value));
861 return CYMakeFunctor(context, function, type);
862 } else {
863 void (*function)()(CYCastPointer<void (*)()>(context, value));
864 return CYMakeFunctor(context, function, type);
865 }
866}
867
868static bool Index_(apr_pool_t *pool, JSContextRef context, Struct_privateData *internal, JSStringRef property, ssize_t &index, uint8_t *&base) {
869 Type_privateData *typical(internal->type_);
870 sig::Type *type(typical->type_);
871 if (type == NULL)
872 return false;
873
874 const char *name(CYPoolCString(pool, context, property));
875 size_t length(strlen(name));
876 double number(CYCastDouble(name, length));
877
878 size_t count(type->data.signature.count);
879
880 if (std::isnan(number)) {
881 if (property == NULL)
882 return false;
883
884 sig::Element *elements(type->data.signature.elements);
885
886 for (size_t local(0); local != count; ++local) {
887 sig::Element *element(&elements[local]);
888 if (element->name != NULL && strcmp(name, element->name) == 0) {
889 index = local;
890 goto base;
891 }
892 }
893
894 return false;
895 } else {
896 index = static_cast<ssize_t>(number);
897 if (index != number || index < 0 || static_cast<size_t>(index) >= count)
898 return false;
899 }
900
901 base:
902 ffi_type **elements(typical->GetFFI()->elements);
903
904 base = reinterpret_cast<uint8_t *>(internal->value_);
905 for (ssize_t local(0); local != index; ++local)
906 base += elements[local]->size;
907
908 return true;
909}
910
911static JSValueRef Pointer_getIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef *exception) { CYTry {
912 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
913 Type_privateData *typical(internal->type_);
914
915 ffi_type *ffi(typical->GetFFI());
916
917 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
918 base += ffi->size * index;
919
920 JSObjectRef owner(internal->GetOwner() ?: object);
921 return CYFromFFI(context, typical->type_, ffi, base, false, owner);
922} CYCatch }
923
924static JSValueRef Pointer_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
925 CYPool pool;
926 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
927 Type_privateData *typical(internal->type_);
928
929 if (typical->type_ == NULL)
930 return NULL;
931
932 ssize_t offset;
933 if (!CYGetOffset(pool, context, property, offset))
934 return NULL;
935
936 return Pointer_getIndex(context, object, offset, exception);
937}
938
939static JSValueRef Pointer_getProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
940 return Pointer_getIndex(context, object, 0, exception);
941}
942
943static bool Pointer_setIndex(JSContextRef context, JSObjectRef object, size_t index, JSValueRef value, JSValueRef *exception) { CYTry {
944 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
945 Type_privateData *typical(internal->type_);
946
947 ffi_type *ffi(typical->GetFFI());
948
949 uint8_t *base(reinterpret_cast<uint8_t *>(internal->value_));
950 base += ffi->size * index;
951
952 CYPoolFFI(NULL, context, typical->type_, ffi, base, value);
953 return true;
954} CYCatch }
955
956static bool Pointer_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
957 CYPool pool;
958 Pointer *internal(reinterpret_cast<Pointer *>(JSObjectGetPrivate(object)));
959 Type_privateData *typical(internal->type_);
960
961 if (typical->type_ == NULL)
962 return NULL;
963
964 ssize_t offset;
965 if (!CYGetOffset(pool, context, property, offset))
966 return NULL;
967
968 return Pointer_setIndex(context, object, offset, value, exception);
969}
970
971static bool Pointer_setProperty_$cyi(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) {
972 return Pointer_setIndex(context, object, 0, value, exception);
973}
974
975static JSValueRef Struct_callAsFunction_$cya(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
976 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(_this)));
977 Type_privateData *typical(internal->type_);
978 return CYMakePointer(context, internal->value_, typical->type_, typical->ffi_, _this);
979}
980
981static JSValueRef Struct_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
982 CYPool pool;
983 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
984 Type_privateData *typical(internal->type_);
985
986 ssize_t index;
987 uint8_t *base;
988
989 if (!Index_(pool, context, internal, property, index, base))
990 return NULL;
991
992 JSObjectRef owner(internal->GetOwner() ?: object);
993
994 return CYFromFFI(context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, false, owner);
995} CYCatch }
996
997static bool Struct_setProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef value, JSValueRef *exception) { CYTry {
998 CYPool pool;
999 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1000 Type_privateData *typical(internal->type_);
1001
1002 ssize_t index;
1003 uint8_t *base;
1004
1005 if (!Index_(pool, context, internal, property, index, base))
1006 return false;
1007
1008 CYPoolFFI(NULL, context, typical->type_->data.signature.elements[index].type, typical->GetFFI()->elements[index], base, value);
1009 return true;
1010} CYCatch }
1011
1012static void Struct_getPropertyNames(JSContextRef context, JSObjectRef object, JSPropertyNameAccumulatorRef names) {
1013 Struct_privateData *internal(reinterpret_cast<Struct_privateData *>(JSObjectGetPrivate(object)));
1014 Type_privateData *typical(internal->type_);
1015 sig::Type *type(typical->type_);
1016
1017 if (type == NULL)
1018 return;
1019
1020 size_t count(type->data.signature.count);
1021 sig::Element *elements(type->data.signature.elements);
1022
1023 char number[32];
1024
1025 for (size_t index(0); index != count; ++index) {
1026 const char *name;
1027 name = elements[index].name;
1028
1029 if (name == NULL) {
272a0dd4 1030 sprintf(number, "%zu", index);
37954781
JF
1031 name = number;
1032 }
1033
1034 JSPropertyNameAccumulatorAddName(names, CYJSString(name));
1035 }
1036}
1037
1038JSValueRef 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 {
1039 if (setups + count != signature->count - 1)
1040 throw CYJSError(context, "incorrect number of arguments to ffi function");
1041
1042 size_t size(setups + count);
1043 void *values[size];
1044 memcpy(values, setup, sizeof(void *) * setups);
1045
1046 for (size_t index(setups); index != size; ++index) {
1047 sig::Element *element(&signature->elements[index + 1]);
1048 ffi_type *ffi(cif->arg_types[index]);
1049 // XXX: alignment?
1050 values[index] = new(pool) uint8_t[ffi->size];
1051 CYPoolFFI(pool, context, element->type, ffi, values[index], arguments[index - setups]);
1052 }
1053
1054 uint8_t value[cif->rtype->size];
d3760804
JF
1055
1056 if (hooks_ != NULL && hooks_->CallFunction != NULL)
1057 (*hooks_->CallFunction)(context, cif, function, value, values);
1058 else
1059 ffi_call(cif, function, value, values);
37954781
JF
1060
1061 return CYFromFFI(context, signature->elements[0].type, cif->rtype, value, initialize);
1062} CYCatch }
1063
1064static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1065 CYPool pool;
1066 cy::Functor *internal(reinterpret_cast<cy::Functor *>(JSObjectGetPrivate(object)));
1067 return CYCallFunction(pool, context, 0, NULL, count, arguments, false, exception, &internal->signature_, &internal->cif_, internal->GetValue());
1068}
1069
1070static JSObjectRef CYMakeType(JSContextRef context, const char *type) {
1071 Type_privateData *internal(new Type_privateData(NULL, type));
1072 return JSObjectMake(context, Type_privateData::Class_, internal);
1073}
1074
1075static JSObjectRef CYMakeType(JSContextRef context, sig::Type *type) {
1076 Type_privateData *internal(new Type_privateData(type));
1077 return JSObjectMake(context, Type_privateData::Class_, internal);
1078}
1079
1080static void *CYCastSymbol(const char *name) {
1081 return dlsym(RTLD_DEFAULT, name);
1082}
1083
1084static JSValueRef Runtime_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1085 CYPool pool;
1086 CYUTF8String name(CYPoolUTF8String(pool, context, property));
1087
1088 if (hooks_ != NULL && hooks_->RuntimeProperty != NULL)
1089 if (JSValueRef value = (*hooks_->RuntimeProperty)(context, name))
1090 return value;
1091
1092 sqlite3_stmt *statement;
1093
1094 _sqlcall(sqlite3_prepare(Bridge_,
1095 "select "
1096 "\"bridge\".\"mode\", "
1097 "\"bridge\".\"value\" "
1098 "from \"bridge\" "
1099 "where"
1100 " \"bridge\".\"name\" = ?"
1101 " limit 1"
1102 , -1, &statement, NULL));
1103
1104 _sqlcall(sqlite3_bind_text(statement, 1, name.data, name.size, SQLITE_STATIC));
1105
1106 int mode;
1107 const char *value;
1108
1109 if (_sqlcall(sqlite3_step(statement)) == SQLITE_DONE) {
1110 mode = -1;
1111 value = NULL;
1112 } else {
1113 mode = sqlite3_column_int(statement, 0);
1114 value = sqlite3_column_pooled(pool, statement, 1);
1115 }
1116
1117 _sqlcall(sqlite3_finalize(statement));
1118
1119 switch (mode) {
1120 default:
1121 _assert(false);
1122 case -1:
1123 return NULL;
1124
1125 case 0:
1126 return JSEvaluateScript(CYGetJSContext(), CYJSString(value), NULL, NULL, 0, NULL);
37954781 1127
65cf734f
JF
1128 case 1:
1129 if (void (*symbol)() = reinterpret_cast<void (*)()>(CYCastSymbol(name.data)))
1130 return CYMakeFunctor(context, symbol, value);
1131 else return NULL;
1132
1133 case 2:
1134 if (void *symbol = CYCastSymbol(name.data)) {
1135 // XXX: this is horrendously inefficient
1136 sig::Signature signature;
1137 sig::Parse(pool, &signature, value, &Structor_);
1138 ffi_cif cif;
1139 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
1140 return CYFromFFI(context, signature.elements[0].type, cif.rtype, symbol);
1141 } else return NULL;
37954781
JF
1142
1143 // XXX: implement case 3
1144 case 4:
1145 return CYMakeType(context, value);
1146 }
1147} CYCatch }
1148
1149static JSObjectRef Pointer_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1150 if (count != 2)
1151 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1152
1153 CYPool pool;
1154
1155 void *value(CYCastPointer<void *>(context, arguments[0]));
1156 const char *type(CYPoolCString(pool, context, arguments[1]));
1157
1158 sig::Signature signature;
1159 sig::Parse(pool, &signature, type, &Structor_);
1160
1161 return CYMakePointer(context, value, signature.elements[0].type, NULL, NULL);
1162} CYCatch }
1163
1164static JSObjectRef Type_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1165 if (count != 1)
1166 throw CYJSError(context, "incorrect number of arguments to Type constructor");
1167 CYPool pool;
1168 const char *type(CYPoolCString(pool, context, arguments[0]));
1169 return CYMakeType(context, type);
1170} CYCatch }
1171
1172static JSValueRef Type_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { CYTry {
1173 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1174
1175 sig::Type type;
1176
1177 if (JSStringIsEqualToUTF8CString(property, "$cyi")) {
1178 type.primitive = sig::pointer_P;
1179 type.data.data.size = 0;
1180 } else {
1181 CYPool pool;
1182 size_t index(CYGetIndex(pool, context, property));
1183 if (index == _not(size_t))
1184 return NULL;
1185 type.primitive = sig::array_P;
1186 type.data.data.size = index;
1187 }
1188
1189 type.name = NULL;
1190 type.flags = 0;
1191
1192 type.data.data.type = internal->type_;
1193
1194 return CYMakeType(context, &type);
1195} CYCatch }
1196
1197static JSValueRef Type_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1198 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1199
1200 if (count != 1)
1201 throw CYJSError(context, "incorrect number of arguments to type cast function");
1202 sig::Type *type(internal->type_);
1203 ffi_type *ffi(internal->GetFFI());
1204 // XXX: alignment?
1205 uint8_t value[ffi->size];
1206 CYPool pool;
1207 CYPoolFFI(pool, context, type, ffi, value, arguments[0]);
1208 return CYFromFFI(context, type, ffi, value);
1209} CYCatch }
1210
1211static JSObjectRef Type_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1212 if (count != 0)
1213 throw CYJSError(context, "incorrect number of arguments to type cast function");
1214 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(object)));
1215
1216 sig::Type *type(internal->type_);
1217 size_t size;
1218
1219 if (type->primitive != sig::array_P)
1220 size = 0;
1221 else {
1222 size = type->data.data.size;
1223 type = type->data.data.type;
1224 }
1225
1226 void *value(malloc(internal->GetFFI()->size));
1227 return CYMakePointer(context, value, type, NULL, NULL);
1228} CYCatch }
1229
1230static JSObjectRef Functor_new(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1231 if (count != 2)
1232 throw CYJSError(context, "incorrect number of arguments to Functor constructor");
1233 CYPool pool;
1234 const char *type(CYPoolCString(pool, context, arguments[1]));
1235 return CYMakeFunctor(context, arguments[0], type);
1236} CYCatch }
1237
1238static JSValueRef CYValue_callAsFunction_valueOf(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1239 CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1240 return CYCastJSValue(context, reinterpret_cast<uintptr_t>(internal->value_));
1241} CYCatch }
1242
1243static JSValueRef CYValue_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1244 return CYValue_callAsFunction_valueOf(context, object, _this, count, arguments, exception);
1245}
1246
1247static JSValueRef CYValue_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1248CYValue *internal(reinterpret_cast<CYValue *>(JSObjectGetPrivate(_this)));
1249 char string[32];
1250 sprintf(string, "%p", internal->value_);
1251
1252 return CYCastJSValue(context, string);
1253} CYCatch }
1254
1255static JSValueRef Type_callAsFunction_toString(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1256 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1257 CYPool pool;
1258 const char *type(sig::Unparse(pool, internal->type_));
1259 return CYCastJSValue(context, CYJSString(type));
1260} CYCatch }
1261
1262static JSValueRef Type_callAsFunction_toCYON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { CYTry {
1263 Type_privateData *internal(reinterpret_cast<Type_privateData *>(JSObjectGetPrivate(_this)));
1264 CYPool pool;
1265 const char *type(sig::Unparse(pool, internal->type_));
1266 size_t size(strlen(type));
1267 char *cyon(new(pool) char[12 + size + 1]);
1268 memcpy(cyon, "new Type(\"", 10);
1269 cyon[12 + size] = '\0';
1270 cyon[12 + size - 2] = '"';
1271 cyon[12 + size - 1] = ')';
1272 memcpy(cyon + 10, type, size);
1273 return CYCastJSValue(context, CYJSString(cyon));
1274} CYCatch }
1275
1276static JSValueRef Type_callAsFunction_toJSON(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
1277 return Type_callAsFunction_toString(context, object, _this, count, arguments, exception);
1278}
1279
1280static JSStaticValue Pointer_staticValues[2] = {
1281 {"$cyi", &Pointer_getProperty_$cyi, &Pointer_setProperty_$cyi, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1282 {NULL, NULL, NULL, 0}
1283};
1284
1285static JSStaticFunction Pointer_staticFunctions[4] = {
1286 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1287 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1288 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1289 {NULL, NULL, 0}
1290};
1291
1292static JSStaticFunction Struct_staticFunctions[2] = {
1293 {"$cya", &Struct_callAsFunction_$cya, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1294 {NULL, NULL, 0}
1295};
1296
1297static JSStaticFunction Functor_staticFunctions[4] = {
1298 {"toCYON", &CYValue_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1299 {"toJSON", &CYValue_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1300 {"valueOf", &CYValue_callAsFunction_valueOf, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1301 {NULL, NULL, 0}
1302};
1303
1304namespace cy {
1305 JSStaticFunction const * const Functor::StaticFunctions = Functor_staticFunctions;
1306}
1307
1308static JSStaticFunction Type_staticFunctions[4] = {
1309 {"toCYON", &Type_callAsFunction_toCYON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1310 {"toJSON", &Type_callAsFunction_toJSON, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1311 {"toString", &Type_callAsFunction_toString, kJSPropertyAttributeDontEnum | kJSPropertyAttributeDontDelete},
1312 {NULL, NULL, 0}
1313};
1314
ec28b4e5 1315static JSObjectRef (*JSObjectMakeArray$)(JSContextRef, size_t, const JSValueRef[], JSValueRef *);
e0625f37 1316
37954781
JF
1317void CYSetArgs(int argc, const char *argv[]) {
1318 JSContextRef context(CYGetJSContext());
1319 JSValueRef args[argc];
1320 for (int i(0); i != argc; ++i)
1321 args[i] = CYCastJSValue(context, argv[i]);
e0625f37
JF
1322
1323 JSObjectRef array;
ec28b4e5 1324 if (JSObjectMakeArray$ != NULL) {
e0625f37 1325 JSValueRef exception(NULL);
ec28b4e5 1326 array = (*JSObjectMakeArray$)(context, argc, args, &exception);
e0625f37
JF
1327 CYThrow(context, exception);
1328 } else {
1329 JSValueRef value(CYCallAsFunction(context, Array_, NULL, argc, args));
1330 array = CYCastJSObject(context, value);
1331 }
1332
37954781
JF
1333 CYSetProperty(context, System_, CYJSString("args"), array);
1334}
1335
1336JSObjectRef CYGetGlobalObject(JSContextRef context) {
1337 return JSContextGetGlobalObject(context);
1338}
1339
1340const char *CYExecute(apr_pool_t *pool, const char *code) {
1341 JSContextRef context(CYGetJSContext());
1342 JSValueRef exception(NULL), result;
1343
1344 void *handle;
1345 if (hooks_ != NULL && hooks_->ExecuteStart != NULL)
d3760804 1346 handle = (*hooks_->ExecuteStart)(context);
37954781
JF
1347 else
1348 handle = NULL;
1349
1350 const char *json;
1351
1352 try {
1353 result = JSEvaluateScript(context, CYJSString(code), NULL, NULL, 0, &exception);
1354 } catch (const char *error) {
1355 return error;
1356 }
1357
1358 if (exception != NULL) { error:
1359 result = exception;
1360 exception = NULL;
1361 }
1362
1363 if (JSValueIsUndefined(context, result))
1364 return NULL;
1365
1366 try {
1367 json = CYPoolCCYON(pool, context, result, &exception);
1368 } catch (const char *error) {
1369 return error;
1370 }
1371
1372 if (exception != NULL)
1373 goto error;
1374
1375 CYSetProperty(context, CYGetGlobalObject(context), Result_, result);
1376
1377 if (hooks_ != NULL && hooks_->ExecuteEnd != NULL)
d3760804 1378 (*hooks_->ExecuteEnd)(context, handle);
37954781
JF
1379 return json;
1380}
1381
1382static apr_pool_t *Pool_;
1383
1384static bool initialized_;
1385
1386void CYInitialize() {
1387 if (!initialized_)
1388 initialized_ = true;
1389 else return;
1390
1391 _aprcall(apr_initialize());
1392 _aprcall(apr_pool_create(&Pool_, NULL));
1393 _sqlcall(sqlite3_open("/usr/lib/libcycript.db", &Bridge_));
e0625f37 1394
ec28b4e5 1395 JSObjectMakeArray$ = reinterpret_cast<JSObjectRef (*)(JSContextRef, size_t, const JSValueRef[], JSValueRef *)>(dlsym(RTLD_DEFAULT, "JSObjectMakeArray"));
37954781
JF
1396}
1397
1398apr_pool_t *CYGetGlobalPool() {
1399 CYInitialize();
1400 return Pool_;
1401}
1402
1403void CYThrow(JSContextRef context, JSValueRef value) {
1404 if (value != NULL)
1405 throw CYJSError(context, value);
1406}
1407
1408const char *CYJSError::PoolCString(apr_pool_t *pool) const {
1409 return CYPoolCString(pool, context_, value_);
1410}
1411
1412JSValueRef CYJSError::CastJSValue(JSContextRef context) const {
1413 // XXX: what if the context is different?
1414 return value_;
1415}
1416
1417void CYThrow(const char *format, ...) {
1418 va_list args;
1419 va_start (args, format);
1420 throw CYPoolError(format, args);
1421 // XXX: does this matter? :(
1422 va_end (args);
1423}
1424
1425const char *CYPoolError::PoolCString(apr_pool_t *pool) const {
1426 return apr_pstrdup(pool, message_);
1427}
1428
1429CYPoolError::CYPoolError(const char *format, ...) {
1430 va_list args;
1431 va_start (args, format);
1432 message_ = apr_pvsprintf(pool_, format, args);
1433 va_end (args);
1434}
1435
1436CYPoolError::CYPoolError(const char *format, va_list args) {
1437 message_ = apr_pvsprintf(pool_, format, args);
1438}
1439
1440JSValueRef CYPoolError::CastJSValue(JSContextRef context) const {
1441 return CYCastJSValue(context, message_);
1442}
1443
1444CYJSError::CYJSError(JSContextRef context, const char *format, ...) {
1445 if (context == NULL)
1446 context = CYGetJSContext();
1447
1448 CYPool pool;
1449
1450 va_list args;
1451 va_start (args, format);
1452 const char *message(apr_pvsprintf(pool, format, args));
1453 va_end (args);
1454
1455 JSValueRef arguments[1] = {CYCastJSValue(context, CYJSString(message))};
1456
1457 JSValueRef exception(NULL);
1458 value_ = JSObjectCallAsConstructor(context, Error_, 1, arguments, &exception);
1459 CYThrow(context, exception);
1460}
1461
37954781
JF
1462JSGlobalContextRef CYGetJSContext() {
1463 CYInitialize();
1464
1465 if (Context_ == NULL) {
1466 JSClassDefinition definition;
1467
1468 definition = kJSClassDefinitionEmpty;
1469 definition.className = "Functor";
1470 definition.staticFunctions = cy::Functor::StaticFunctions;
1471 definition.callAsFunction = &Functor_callAsFunction;
1472 definition.finalize = &CYFinalize;
1473 Functor_ = JSClassCreate(&definition);
1474
1475 definition = kJSClassDefinitionEmpty;
1476 definition.className = "Pointer";
1477 definition.staticValues = Pointer_staticValues;
1478 definition.staticFunctions = Pointer_staticFunctions;
1479 definition.getProperty = &Pointer_getProperty;
1480 definition.setProperty = &Pointer_setProperty;
1481 definition.finalize = &CYFinalize;
1482 Pointer_ = JSClassCreate(&definition);
1483
1484 definition = kJSClassDefinitionEmpty;
1485 definition.className = "Struct";
1486 definition.staticFunctions = Struct_staticFunctions;
1487 definition.getProperty = &Struct_getProperty;
1488 definition.setProperty = &Struct_setProperty;
1489 definition.getPropertyNames = &Struct_getPropertyNames;
1490 definition.finalize = &CYFinalize;
1491 Struct_ = JSClassCreate(&definition);
1492
1493 definition = kJSClassDefinitionEmpty;
1494 definition.className = "Type";
1495 definition.staticFunctions = Type_staticFunctions;
1496 definition.getProperty = &Type_getProperty;
1497 definition.callAsFunction = &Type_callAsFunction;
1498 definition.callAsConstructor = &Type_callAsConstructor;
1499 definition.finalize = &CYFinalize;
1500 Type_privateData::Class_ = JSClassCreate(&definition);
1501
1502 definition = kJSClassDefinitionEmpty;
1503 definition.className = "Runtime";
1504 definition.getProperty = &Runtime_getProperty;
1505 Runtime_ = JSClassCreate(&definition);
1506
1507 definition = kJSClassDefinitionEmpty;
1508 //definition.getProperty = &Global_getProperty;
1509 JSClassRef Global(JSClassCreate(&definition));
1510
1511 JSGlobalContextRef context(JSGlobalContextCreate(Global));
1512 Context_ = context;
1513 JSObjectRef global(CYGetGlobalObject(context));
1514
1515 JSObjectSetPrototype(context, global, JSObjectMake(context, Runtime_, NULL));
1516
1517 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1518 JSValueProtect(context, Array_);
1519
1520 Error_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Error")));
1521 JSValueProtect(context, Error_);
1522
1523 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1524 JSValueProtect(context, Function_);
1525
1526 String_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("String")));
1527 JSValueProtect(context, String_);
1528
1529 length_ = JSStringCreateWithUTF8CString("length");
1530 message_ = JSStringCreateWithUTF8CString("message");
1531 name_ = JSStringCreateWithUTF8CString("name");
1532 prototype_ = JSStringCreateWithUTF8CString("prototype");
1533 toCYON_ = JSStringCreateWithUTF8CString("toCYON");
1534 toJSON_ = JSStringCreateWithUTF8CString("toJSON");
1535
1536 JSObjectRef Object(CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Object"))));
1537 Object_prototype_ = CYCastJSObject(context, CYGetProperty(context, Object, prototype_));
1538 JSValueProtect(context, Object_prototype_);
1539
1540 Array_prototype_ = CYCastJSObject(context, CYGetProperty(context, Array_, prototype_));
1541 Array_pop_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("pop")));
1542 Array_push_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("push")));
1543 Array_splice_ = CYCastJSObject(context, CYGetProperty(context, Array_prototype_, CYJSString("splice")));
1544
1545 CYSetProperty(context, Array_prototype_, toCYON_, JSObjectMakeFunctionWithCallback(context, toCYON_, &Array_callAsFunction_toCYON), kJSPropertyAttributeDontEnum);
1546
1547 JSValueProtect(context, Array_prototype_);
1548 JSValueProtect(context, Array_pop_);
1549 JSValueProtect(context, Array_push_);
1550 JSValueProtect(context, Array_splice_);
1551
1552 JSObjectRef Functor(JSObjectMakeConstructor(context, Functor_, &Functor_new));
1553
1554 Function_prototype_ = (JSObjectRef) CYGetProperty(context, Function_, prototype_);
1555 JSValueProtect(context, Function_prototype_);
1556
1557 JSObjectSetPrototype(context, (JSObjectRef) CYGetProperty(context, Functor, prototype_), Function_prototype_);
1558
1559 CYSetProperty(context, global, CYJSString("Functor"), Functor);
1560 CYSetProperty(context, global, CYJSString("Pointer"), JSObjectMakeConstructor(context, Pointer_, &Pointer_new));
1561 CYSetProperty(context, global, CYJSString("Type"), JSObjectMakeConstructor(context, Type_privateData::Class_, &Type_new));
1562
1563 JSObjectRef cycript(JSObjectMake(context, NULL, NULL));
1564 CYSetProperty(context, global, CYJSString("Cycript"), cycript);
1565 CYSetProperty(context, cycript, CYJSString("gc"), JSObjectMakeFunctionWithCallback(context, CYJSString("gc"), &Cycript_gc_callAsFunction));
1566
1567 CYSetProperty(context, global, CYJSString("$cyq"), JSObjectMakeFunctionWithCallback(context, CYJSString("$cyq"), &$cyq));
1568
1569 System_ = JSObjectMake(context, NULL, NULL);
1570 JSValueProtect(context, System_);
1571
1572 CYSetProperty(context, global, CYJSString("system"), System_);
1573 CYSetProperty(context, System_, CYJSString("args"), CYJSNull(context));
1574 //CYSetProperty(context, System_, CYJSString("global"), global);
1575
1576 CYSetProperty(context, System_, CYJSString("print"), JSObjectMakeFunctionWithCallback(context, CYJSString("print"), &System_print));
1577
1578 Result_ = JSStringCreateWithUTF8CString("_");
1579
b5dd57dc
JF
1580 if (hooks_ != NULL && hooks_->SetupContext != NULL)
1581 (*hooks_->SetupContext)(context);
37954781
JF
1582 }
1583
1584 return Context_;
1585}