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