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