]> git.saurik.com Git - cycript.git/blob - Library.mm
Further normalization and fixed some output cases.
[cycript.git] / Library.mm
1 /* Cyrker - Remove Execution Server and Disassembler
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 #define _GNU_SOURCE
41
42 #include <substrate.h>
43 #include "cycript.hpp"
44
45 #include "sig/parse.hpp"
46 #include "sig/ffi_type.hpp"
47
48 #include "Pooling.hpp"
49 #include "Struct.hpp"
50
51 #include <unistd.h>
52
53 #include <CoreFoundation/CoreFoundation.h>
54 #include <CoreFoundation/CFLogUtilities.h>
55
56 #include <CFNetwork/CFNetwork.h>
57
58 #include <WebKit/WebScriptObject.h>
59
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <netinet/in.h>
63
64 #include <iostream>
65 #include <ext/stdio_filebuf.h>
66 #include <set>
67 #include <map>
68
69 #include "Parser.hpp"
70 #include "Cycript.tab.hh"
71
72 #undef _assert
73 #undef _trace
74
75 #define _assert(test) do { \
76 if (!(test)) \
77 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"_assert(%s):%s(%u):%s", #test, __FILE__, __LINE__, __FUNCTION__] userInfo:nil]; \
78 } while (false)
79
80 #define _trace() do { \
81 CFLog(kCFLogLevelNotice, CFSTR("_trace():%u"), __LINE__); \
82 } while (false)
83
84
85 static JSContextRef Context_;
86
87 static JSClassRef Functor_;
88 static JSClassRef Instance_;
89 static JSClassRef Pointer_;
90 static JSClassRef Selector_;
91
92 static JSObjectRef Array_;
93 static JSObjectRef Function_;
94
95 static JSStringRef name_;
96 static JSStringRef message_;
97 static JSStringRef length_;
98
99 static Class NSCFBoolean_;
100
101 static NSMutableDictionary *Bridge_;
102
103 struct Client {
104 CFHTTPMessageRef message_;
105 CFSocketRef socket_;
106 };
107
108 JSObjectRef CYMakeObject(JSContextRef context, id object) {
109 return JSObjectMake(context, Instance_, [object retain]);
110 }
111
112 @interface NSMethodSignature (Cycript)
113 - (NSString *) _typeString;
114 @end
115
116 @interface NSObject (Cycript)
117 - (bool) cy$isUndefined;
118 - (NSString *) cy$toJSON;
119 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context;
120 @end
121
122 @interface NSString (Cycript)
123 - (void *) cy$symbol;
124 @end
125
126 @interface NSNumber (Cycript)
127 - (void *) cy$symbol;
128 @end
129
130 @implementation NSObject (Cycript)
131
132 - (bool) cy$isUndefined {
133 return false;
134 }
135
136 - (NSString *) cy$toJSON {
137 return [self description];
138 }
139
140 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
141 return CYMakeObject(context, self);
142 }
143
144 @end
145
146 @implementation WebUndefined (Cycript)
147
148 - (bool) cy$isUndefined {
149 return true;
150 }
151
152 - (NSString *) cy$toJSON {
153 return @"undefined";
154 }
155
156 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
157 return JSValueMakeUndefined(context);
158 }
159
160 @end
161
162 @implementation NSArray (Cycript)
163
164 - (NSString *) cy$toJSON {
165 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
166 [json appendString:@"["];
167
168 bool comma(false);
169 for (id object in self) {
170 if (comma)
171 [json appendString:@","];
172 else
173 comma = true;
174 if (![object cy$isUndefined])
175 [json appendString:[object cy$toJSON]];
176 else {
177 [json appendString:@","];
178 comma = false;
179 }
180 }
181
182 [json appendString:@"]"];
183 return json;
184 }
185
186 @end
187
188 @implementation NSDictionary (Cycript)
189
190 - (NSString *) cy$toJSON {
191 NSMutableString *json([[[NSMutableString alloc] init] autorelease]);
192 [json appendString:@"({"];
193
194 bool comma(false);
195 for (id key in self) {
196 if (comma)
197 [json appendString:@","];
198 else
199 comma = true;
200 [json appendString:[key cy$toJSON]];
201 [json appendString:@":"];
202 NSObject *object([self objectForKey:key]);
203 [json appendString:[object cy$toJSON]];
204 }
205
206 [json appendString:@"})"];
207 return json;
208 }
209
210 @end
211
212 @implementation NSNumber (Cycript)
213
214 - (NSString *) cy$toJSON {
215 return [self class] != NSCFBoolean_ ? [self stringValue] : [self boolValue] ? @"true" : @"false";
216 }
217
218 - (JSValueRef) cy$JSValueInContext:(JSContextRef)context {
219 return [self class] != NSCFBoolean_ ? JSValueMakeNumber(context, [self doubleValue]) : JSValueMakeBoolean(context, [self boolValue]);
220 }
221
222 - (void *) cy$symbol {
223 return [self pointerValue];
224 }
225
226 @end
227
228 @implementation NSString (Cycript)
229
230 - (NSString *) cy$toJSON {
231 CFMutableStringRef json(CFStringCreateMutableCopy(kCFAllocatorDefault, 0, (CFStringRef) self));
232
233 CFStringFindAndReplace(json, CFSTR("\\"), CFSTR("\\\\"), CFRangeMake(0, CFStringGetLength(json)), 0);
234 CFStringFindAndReplace(json, CFSTR("\""), CFSTR("\\\""), CFRangeMake(0, CFStringGetLength(json)), 0);
235 CFStringFindAndReplace(json, CFSTR("\t"), CFSTR("\\t"), CFRangeMake(0, CFStringGetLength(json)), 0);
236 CFStringFindAndReplace(json, CFSTR("\r"), CFSTR("\\r"), CFRangeMake(0, CFStringGetLength(json)), 0);
237 CFStringFindAndReplace(json, CFSTR("\n"), CFSTR("\\n"), CFRangeMake(0, CFStringGetLength(json)), 0);
238
239 CFStringInsert(json, 0, CFSTR("\""));
240 CFStringAppend(json, CFSTR("\""));
241
242 return [reinterpret_cast<const NSString *>(json) autorelease];
243 }
244
245 - (void *) cy$symbol {
246 return dlsym(RTLD_DEFAULT, [self UTF8String]);
247 }
248
249 @end
250
251 @interface CYJSObject : NSDictionary {
252 JSObjectRef object_;
253 JSContextRef context_;
254 }
255
256 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
257
258 - (NSUInteger) count;
259 - (id) objectForKey:(id)key;
260 - (NSEnumerator *) keyEnumerator;
261 - (void) setObject:(id)object forKey:(id)key;
262 - (void) removeObjectForKey:(id)key;
263
264 @end
265
266 @interface CYJSArray : NSArray {
267 JSObjectRef object_;
268 JSContextRef context_;
269 }
270
271 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context;
272
273 - (NSUInteger) count;
274 - (id) objectAtIndex:(NSUInteger)index;
275
276 @end
277
278 CYRange WordStartRange_(0x1000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$
279 CYRange WordEndRange_(0x3ff001000000000LLU,0x7fffffe87fffffeLLU); // A-Za-z_$0-9
280
281 JSContextRef CYGetJSContext() {
282 return Context_;
283 }
284
285 #define CYCatch \
286 @catch (id error) { \
287 CYThrow(context, error, exception); \
288 return NULL; \
289 }
290
291 void CYThrow(JSContextRef context, JSValueRef value);
292
293 id CYCastNSObject(JSContextRef context, JSObjectRef object) {
294 if (JSValueIsObjectOfClass(context, object, Instance_))
295 return reinterpret_cast<id>(JSObjectGetPrivate(object));
296 JSValueRef exception(NULL);
297 bool array(JSValueIsInstanceOfConstructor(context, object, Array_, &exception));
298 CYThrow(context, exception);
299 if (array)
300 return [[[CYJSArray alloc] initWithJSObject:object inContext:context] autorelease];
301 return [[[CYJSObject alloc] initWithJSObject:object inContext:context] autorelease];
302 }
303
304 JSStringRef CYCopyJSString(id value) {
305 return JSStringCreateWithCFString(reinterpret_cast<CFStringRef>([value description]));
306 }
307
308 JSStringRef CYCopyJSString(const char *value) {
309 return JSStringCreateWithUTF8CString(value);
310 }
311
312 JSStringRef CYCopyJSString(JSStringRef value) {
313 return JSStringRetain(value);
314 }
315
316 JSStringRef CYCopyJSString(JSContextRef context, JSValueRef value) {
317 JSValueRef exception(NULL);
318 JSStringRef string(JSValueToStringCopy(context, value, &exception));
319 CYThrow(context, exception);
320 return string;
321 }
322
323 // XXX: this is not a safe handle
324 class CYJSString {
325 private:
326 JSStringRef string_;
327
328 public:
329 template <typename Arg0_>
330 CYJSString(Arg0_ arg0) {
331 string_ = CYCopyJSString(arg0);
332 }
333
334 template <typename Arg0_, typename Arg1_>
335 CYJSString(Arg0_ arg0, Arg1_ arg1) {
336 string_ = CYCopyJSString(arg0, arg1);
337 }
338
339 ~CYJSString() {
340 JSStringRelease(string_);
341 }
342
343 operator JSStringRef() const {
344 return string_;
345 }
346 };
347
348 CFStringRef CYCopyCFString(JSStringRef value) {
349 return JSStringCopyCFString(kCFAllocatorDefault, value);
350 }
351
352 CFStringRef CYCopyCFString(JSContextRef context, JSValueRef value) {
353 return CYCopyCFString(CYJSString(context, value));
354 }
355
356 double CYCastDouble(JSContextRef context, JSValueRef value) {
357 JSValueRef exception(NULL);
358 double number(JSValueToNumber(context, value, &exception));
359 CYThrow(context, exception);
360 return number;
361 }
362
363 CFNumberRef CYCopyCFNumber(JSContextRef context, JSValueRef value) {
364 double number(CYCastDouble(context, value));
365 return CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &number);
366 }
367
368 NSString *CYCastNSString(JSStringRef value) {
369 return [reinterpret_cast<const NSString *>(CYCopyCFString(value)) autorelease];
370 }
371
372 CFTypeRef CYCopyCFType(JSContextRef context, JSValueRef value) {
373 switch (JSType type = JSValueGetType(context, value)) {
374 case kJSTypeUndefined:
375 return CFRetain([WebUndefined undefined]);
376 case kJSTypeNull:
377 return nil;
378 case kJSTypeBoolean:
379 return CFRetain(JSValueToBoolean(context, value) ? kCFBooleanTrue : kCFBooleanFalse);
380 case kJSTypeNumber:
381 return CYCopyCFNumber(context, value);
382 case kJSTypeString:
383 return CYCopyCFString(context, value);
384 case kJSTypeObject:
385 return CFRetain((CFTypeRef) CYCastNSObject(context, (JSObjectRef) value));
386 default:
387 @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"JSValueGetType() == 0x%x", type] userInfo:nil];
388 }
389 }
390
391 NSArray *CYCastNSArray(JSPropertyNameArrayRef names) {
392 size_t size(JSPropertyNameArrayGetCount(names));
393 NSMutableArray *array([NSMutableArray arrayWithCapacity:size]);
394 for (size_t index(0); index != size; ++index)
395 [array addObject:CYCastNSString(JSPropertyNameArrayGetNameAtIndex(names, index))];
396 return array;
397 }
398
399 id CYCastNSObject(JSContextRef context, JSValueRef value) {
400 const NSObject *object(reinterpret_cast<const NSObject *>(CYCopyCFType(context, value)));
401 return object == nil ? nil : [object autorelease];
402 }
403
404 void CYThrow(JSContextRef context, JSValueRef value) {
405 if (value == NULL)
406 return;
407 @throw CYCastNSObject(context, value);
408 }
409
410 JSValueRef CYCastJSValue(JSContextRef context, id value) {
411 return value == nil ? JSValueMakeNull(context) : [value cy$JSValueInContext:context];
412 }
413
414 JSObjectRef CYCastJSObject(JSContextRef context, JSValueRef value) {
415 JSValueRef exception(NULL);
416 JSObjectRef object(JSValueToObject(context, value, &exception));
417 CYThrow(context, exception);
418 return object;
419 }
420
421 JSValueRef CYGetProperty(JSContextRef context, JSObjectRef object, JSStringRef name) {
422 JSValueRef exception(NULL);
423 JSValueRef value(JSObjectGetProperty(context, object, name, &exception));
424 CYThrow(context, exception);
425 return value;
426 }
427
428 void CYSetProperty(JSContextRef context, JSObjectRef object, JSStringRef name, JSValueRef value) {
429 JSValueRef exception(NULL);
430 JSObjectSetProperty(context, object, name, value, kJSPropertyAttributeNone, &exception);
431 CYThrow(context, exception);
432 }
433
434 void CYThrow(JSContextRef context, id error, JSValueRef *exception) {
435 *exception = CYCastJSValue(context, error);
436 }
437
438 @implementation CYJSObject
439
440 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
441 if ((self = [super init]) != nil) {
442 object_ = object;
443 context_ = context;
444 } return self;
445 }
446
447 - (NSUInteger) count {
448 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
449 size_t size(JSPropertyNameArrayGetCount(names));
450 JSPropertyNameArrayRelease(names);
451 return size;
452 }
453
454 - (id) objectForKey:(id)key {
455 return CYCastNSObject(context_, CYGetProperty(context_, object_, CYJSString(key)));
456 }
457
458 - (NSEnumerator *) keyEnumerator {
459 JSPropertyNameArrayRef names(JSObjectCopyPropertyNames(context_, object_));
460 NSEnumerator *enumerator([CYCastNSArray(names) objectEnumerator]);
461 JSPropertyNameArrayRelease(names);
462 return enumerator;
463 }
464
465 - (void) setObject:(id)object forKey:(id)key {
466 CYSetProperty(context_, object_, CYJSString(key), CYCastJSValue(context_, object));
467 }
468
469 - (void) removeObjectForKey:(id)key {
470 JSValueRef exception(NULL);
471 // XXX: this returns a bool... throw exception, or ignore?
472 JSObjectDeleteProperty(context_, object_, CYJSString(key), &exception);
473 CYThrow(context_, exception);
474 }
475
476 @end
477
478 @implementation CYJSArray
479
480 - (id) initWithJSObject:(JSObjectRef)object inContext:(JSContextRef)context {
481 if ((self = [super init]) != nil) {
482 object_ = object;
483 context_ = context;
484 } return self;
485 }
486
487 - (NSUInteger) count {
488 return CYCastDouble(context_, CYGetProperty(context_, object_, length_));
489 }
490
491 - (id) objectAtIndex:(NSUInteger)index {
492 JSValueRef exception(NULL);
493 JSValueRef value(JSObjectGetPropertyAtIndex(context_, object_, index, &exception));
494 CYThrow(context_, exception);
495 id object(CYCastNSObject(context_, value));
496 return object == nil ? [NSNull null] : object;
497 }
498
499 @end
500
501 CFStringRef CYCopyJSONString(JSContextRef context, JSValueRef value) {
502 id object(CYCastNSObject(context, value));
503 return reinterpret_cast<CFStringRef>([(object == nil ? @"null" : [object cy$toJSON]) retain]);
504 }
505
506 static void OnData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
507 switch (type) {
508 case kCFSocketDataCallBack:
509 CFDataRef data(reinterpret_cast<CFDataRef>(value));
510 Client *client(reinterpret_cast<Client *>(info));
511
512 if (client->message_ == NULL)
513 client->message_ = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE);
514
515 if (!CFHTTPMessageAppendBytes(client->message_, CFDataGetBytePtr(data), CFDataGetLength(data)))
516 CFLog(kCFLogLevelError, CFSTR("CFHTTPMessageAppendBytes()"));
517 else if (CFHTTPMessageIsHeaderComplete(client->message_)) {
518 CFURLRef url(CFHTTPMessageCopyRequestURL(client->message_));
519 Boolean absolute;
520 CFStringRef path(CFURLCopyStrictPath(url, &absolute));
521 CFRelease(client->message_);
522
523 CFStringRef code(CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, path, CFSTR("")));
524 CFRelease(path);
525
526 JSStringRef script(JSStringCreateWithCFString(code));
527 CFRelease(code);
528
529 JSValueRef result(JSEvaluateScript(CYGetJSContext(), script, NULL, NULL, 0, NULL));
530 JSStringRelease(script);
531
532 CFHTTPMessageRef response(CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1));
533 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("application/json; charset=utf-8"));
534
535 CFStringRef json(CYCopyJSONString(CYGetJSContext(), result));
536 CFDataRef body(CFStringCreateExternalRepresentation(kCFAllocatorDefault, json, kCFStringEncodingUTF8, NULL));
537 CFRelease(json);
538
539 CFStringRef length(CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%u"), CFDataGetLength(body)));
540 CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), length);
541 CFRelease(length);
542
543 CFHTTPMessageSetBody(response, body);
544 CFRelease(body);
545
546 CFDataRef serialized(CFHTTPMessageCopySerializedMessage(response));
547 CFRelease(response);
548
549 CFSocketSendData(socket, NULL, serialized, 0);
550 CFRelease(serialized);
551
552 CFRelease(url);
553 }
554 break;
555 }
556 }
557
558 static void OnAccept(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *value, void *info) {
559 switch (type) {
560 case kCFSocketAcceptCallBack:
561 Client *client(new Client());
562
563 client->message_ = NULL;
564
565 CFSocketContext context;
566 context.version = 0;
567 context.info = client;
568 context.retain = NULL;
569 context.release = NULL;
570 context.copyDescription = NULL;
571
572 client->socket_ = CFSocketCreateWithNative(kCFAllocatorDefault, *reinterpret_cast<const CFSocketNativeHandle *>(value), kCFSocketDataCallBack, &OnData, &context);
573
574 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, client->socket_, 0), kCFRunLoopDefaultMode);
575 break;
576 }
577 }
578
579 static JSValueRef Instance_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
580 @try {
581 NSString *name(CYCastNSString(property));
582 NSLog(@"%@", name);
583 return NULL;
584 } CYCatch
585 }
586
587 typedef id jocData;
588
589 static JSObjectRef Instance_callAsConstructor(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
590 @try {
591 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
592 return CYMakeObject(context, [[data alloc] autorelease]);
593 } CYCatch
594 }
595
596 struct ptrData {
597 apr_pool_t *pool_;
598 void *value_;
599 sig::Type type_;
600
601 void *operator new(size_t size) {
602 apr_pool_t *pool;
603 apr_pool_create(&pool, NULL);
604 void *data(apr_palloc(pool, size));
605 reinterpret_cast<ptrData *>(data)->pool_ = pool;
606 return data;;
607 }
608
609 ptrData(void *value) :
610 value_(value)
611 {
612 }
613 };
614
615 struct ffiData : ptrData {
616 sig::Signature signature_;
617 ffi_cif cif_;
618
619 ffiData(void (*value)(), const char *type) :
620 ptrData(reinterpret_cast<void *>(value))
621 {
622 sig::Parse(pool_, &signature_, type);
623 sig::sig_ffi_cif(pool_, &sig::ObjectiveC, &signature_, &cif_);
624 }
625 };
626
627 struct selData : ptrData {
628 selData(SEL value) :
629 ptrData(value)
630 {
631 }
632 };
633
634 JSObjectRef CYMakeSelector(JSContextRef context, SEL sel) {
635 selData *data(new selData(sel));
636 return JSObjectMake(context, Selector_, data);
637 }
638
639 JSObjectRef CYMakePointer(JSContextRef context, void *pointer) {
640 ptrData *data(new ptrData(pointer));
641 return JSObjectMake(context, Pointer_, data);
642 }
643
644 static void Pointer_finalize(JSObjectRef object) {
645 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
646 apr_pool_destroy(data->pool_);
647 }
648
649 static void Instance_finalize(JSObjectRef object) {
650 id data(reinterpret_cast<jocData>(JSObjectGetPrivate(object)));
651 [data release];
652 }
653
654 JSObjectRef CYMakeFunction(JSContextRef context, void (*function)(), const char *type) {
655 ffiData *data(new ffiData(function, type));
656 return JSObjectMake(context, Functor_, data);
657 }
658
659 JSObjectRef CYMakeFunction(JSContextRef context, void *function, const char *type) {
660 return CYMakeFunction(context, reinterpret_cast<void (*)()>(function), type);
661 }
662
663 char *CYPoolCString(apr_pool_t *pool, JSStringRef value) {
664 size_t size(JSStringGetMaximumUTF8CStringSize(value));
665 char *string(new(pool) char[size]);
666 JSStringGetUTF8CString(value, string, size);
667 JSStringRelease(value);
668 return string;
669 }
670
671 char *CYPoolCString(apr_pool_t *pool, JSContextRef context, JSValueRef value) {
672 return CYPoolCString(pool, CYJSString(context, value));
673 }
674
675 // XXX: this macro is unhygenic
676 #define CYCastCString(context, value) ({ \
677 JSStringRef string(CYCopyJSString(context, value)); \
678 size_t size(JSStringGetMaximumUTF8CStringSize(string)); \
679 char *utf8(reinterpret_cast<char *>(alloca(size))); \
680 JSStringGetUTF8CString(string, utf8, size); \
681 JSStringRelease(string); \
682 utf8; \
683 })
684
685 SEL CYCastSEL(JSContextRef context, JSValueRef value) {
686 if (JSValueIsNull(context, value))
687 return NULL;
688 else if (JSValueIsObjectOfClass(context, value, Selector_)) {
689 selData *data(reinterpret_cast<selData *>(JSObjectGetPrivate((JSObjectRef) value)));
690 return reinterpret_cast<SEL>(data->value_);
691 } else
692 return sel_registerName(CYCastCString(context, value));
693 }
694
695 void *CYCastPointer(JSContextRef context, JSValueRef value) {
696 switch (JSValueGetType(context, value)) {
697 case kJSTypeNull:
698 return NULL;
699 case kJSTypeString:
700 return dlsym(RTLD_DEFAULT, CYCastCString(context, value));
701 case kJSTypeObject:
702 if (JSValueIsObjectOfClass(context, value, Pointer_)) {
703 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate((JSObjectRef) value)));
704 return data->value_;
705 }
706 default:
707 return reinterpret_cast<void *>(static_cast<uintptr_t>(CYCastDouble(context, value)));
708 }
709 }
710
711 void CYPoolFFI(apr_pool_t *pool, JSContextRef context, sig::Type *type, void *data, JSValueRef value) {
712 switch (type->primitive) {
713 case sig::boolean_P:
714 *reinterpret_cast<bool *>(data) = JSValueToBoolean(context, value);
715 break;
716
717 #define CYPoolFFI_(primitive, native) \
718 case sig::primitive ## _P: \
719 *reinterpret_cast<native *>(data) = CYCastDouble(context, value); \
720 break;
721
722 CYPoolFFI_(uchar, unsigned char)
723 CYPoolFFI_(char, char)
724 CYPoolFFI_(ushort, unsigned short)
725 CYPoolFFI_(short, short)
726 CYPoolFFI_(ulong, unsigned long)
727 CYPoolFFI_(long, long)
728 CYPoolFFI_(uint, unsigned int)
729 CYPoolFFI_(int, int)
730 CYPoolFFI_(ulonglong, unsigned long long)
731 CYPoolFFI_(longlong, long long)
732 CYPoolFFI_(float, float)
733 CYPoolFFI_(double, double)
734
735 case sig::object_P:
736 case sig::typename_P:
737 *reinterpret_cast<id *>(data) = CYCastNSObject(context, value);
738 break;
739
740 case sig::selector_P:
741 *reinterpret_cast<SEL *>(data) = CYCastSEL(context, value);
742 break;
743
744 case sig::pointer_P:
745 *reinterpret_cast<void **>(data) = CYCastPointer(context, value);
746 break;
747
748 case sig::string_P:
749 *reinterpret_cast<char **>(data) = CYPoolCString(pool, context, value);
750 break;
751
752 case sig::struct_P:
753 goto fail;
754
755 case sig::void_P:
756 break;
757
758 default: fail:
759 NSLog(@"CYPoolFFI(%c)\n", type->primitive);
760 _assert(false);
761 }
762 }
763
764 JSValueRef CYFromFFI(JSContextRef context, sig::Type *type, void *data) {
765 JSValueRef value;
766
767 switch (type->primitive) {
768 case sig::boolean_P:
769 value = JSValueMakeBoolean(context, *reinterpret_cast<bool *>(data));
770 break;
771
772 #define CYFromFFI_(primitive, native) \
773 case sig::primitive ## _P: \
774 value = JSValueMakeNumber(context, *reinterpret_cast<native *>(data)); \
775 break;
776
777 CYFromFFI_(uchar, unsigned char)
778 CYFromFFI_(char, char)
779 CYFromFFI_(ushort, unsigned short)
780 CYFromFFI_(short, short)
781 CYFromFFI_(ulong, unsigned long)
782 CYFromFFI_(long, long)
783 CYFromFFI_(uint, unsigned int)
784 CYFromFFI_(int, int)
785 CYFromFFI_(ulonglong, unsigned long long)
786 CYFromFFI_(longlong, long long)
787 CYFromFFI_(float, float)
788 CYFromFFI_(double, double)
789
790 case sig::object_P:
791 case sig::typename_P:
792 value = CYCastJSValue(context, *reinterpret_cast<id *>(data));
793 break;
794
795 case sig::selector_P:
796 if (SEL sel = *reinterpret_cast<SEL *>(data))
797 value = CYMakeSelector(context, sel);
798 else goto null;
799 break;
800
801 case sig::pointer_P:
802 if (void *pointer = *reinterpret_cast<void **>(data))
803 value = CYMakePointer(context, pointer);
804 else goto null;
805 break;
806
807 case sig::string_P:
808 if (char *utf8 = *reinterpret_cast<char **>(data))
809 value = JSValueMakeString(context, CYJSString(utf8));
810 else goto null;
811 break;
812
813 case sig::struct_P:
814 goto fail;
815
816 case sig::void_P:
817 value = JSValueMakeUndefined(context);
818 break;
819
820 null:
821 value = JSValueMakeNull(context);
822 break;
823
824 default: fail:
825 NSLog(@"CYFromFFI(%c)\n", type->primitive);
826 _assert(false);
827 }
828
829 return value;
830 }
831
832 static JSValueRef CYCallFunction(JSContextRef context, size_t count, const JSValueRef *arguments, JSValueRef *exception, sig::Signature *signature, ffi_cif *cif, void (*function)()) { _pooled
833 @try {
834 if (count != signature->count - 1)
835 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to ffi function" userInfo:nil];
836
837 CYPool pool;
838 void *values[count];
839
840 for (unsigned index(0); index != count; ++index) {
841 sig::Element *element(&signature->elements[index + 1]);
842 // XXX: alignment?
843 values[index] = new(pool) uint8_t[cif->arg_types[index]->size];
844 CYPoolFFI(pool, context, element->type, values[index], arguments[index]);
845 }
846
847 uint8_t value[cif->rtype->size];
848 ffi_call(cif, function, value, values);
849
850 return CYFromFFI(context, signature->elements[0].type, value);
851 } CYCatch
852 }
853
854 static JSValueRef Global_getProperty(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) { _pooled
855 @try {
856 NSString *name(CYCastNSString(property));
857 if (Class _class = NSClassFromString(name))
858 return CYMakeObject(context, _class);
859 if (NSMutableArray *entry = [Bridge_ objectForKey:name])
860 switch ([[entry objectAtIndex:0] intValue]) {
861 case 0:
862 return JSEvaluateScript(CYGetJSContext(), CYJSString([entry objectAtIndex:1]), NULL, NULL, 0, NULL);
863 case 1:
864 return CYMakeFunction(context, [name cy$symbol], [[entry objectAtIndex:1] UTF8String]);
865 case 2:
866 CYPool pool;
867 sig::Signature signature;
868 sig::Parse(pool, &signature, [[entry objectAtIndex:1] UTF8String]);
869 return CYFromFFI(context, signature.elements[0].type, [name cy$symbol]);
870 }
871 return NULL;
872 } CYCatch
873 }
874
875 bool stret(ffi_type *ffi_type) {
876 return ffi_type->type == FFI_TYPE_STRUCT && (
877 ffi_type->size > OBJC_MAX_STRUCT_BY_VALUE ||
878 struct_forward_array[ffi_type->size] != 0
879 );
880 }
881
882 static JSValueRef $objc_msgSend(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) { _pooled
883 const char *type;
884
885 @try {
886 if (count < 2)
887 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"too few arguments to objc_msgSend" userInfo:nil];
888
889 id self(CYCastNSObject(context, arguments[0]));
890 if (self == nil)
891 return JSValueMakeNull(context);
892
893 SEL _cmd(CYCastSEL(context, arguments[1]));
894 NSMethodSignature *method([self methodSignatureForSelector:_cmd]);
895 if (method == nil)
896 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:[NSString stringWithFormat:@"unrecognized selector %s sent to object %p", sel_getName(_cmd), self] userInfo:nil];
897
898 type = [[method _typeString] UTF8String];
899 } CYCatch
900
901 CYPool pool;
902
903 sig::Signature signature;
904 sig::Parse(pool, &signature, type);
905
906 ffi_cif cif;
907 sig::sig_ffi_cif(pool, &sig::ObjectiveC, &signature, &cif);
908
909 void (*function)() = stret(cif.rtype) ? reinterpret_cast<void (*)()>(&objc_msgSend_stret) : reinterpret_cast<void (*)()>(&objc_msgSend);
910 return CYCallFunction(context, count, arguments, exception, &signature, &cif, function);
911 }
912
913 static JSValueRef Selector_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
914 JSValueRef setup[count + 2];
915 setup[0] = _this;
916 setup[1] = object;
917 memmove(setup + 2, arguments, sizeof(JSValueRef) * count);
918 return $objc_msgSend(context, NULL, NULL, count + 2, setup, exception);
919 }
920
921 static JSValueRef Functor_callAsFunction(JSContextRef context, JSObjectRef object, JSObjectRef _this, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
922 ffiData *data(reinterpret_cast<ffiData *>(JSObjectGetPrivate(object)));
923 return CYCallFunction(context, count, arguments, exception, &data->signature_, &data->cif_, reinterpret_cast<void (*)()>(data->value_));
924 }
925
926 JSObjectRef sel(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
927 @try {
928 if (count != 1)
929 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Selector constructor" userInfo:nil];
930 const char *name(CYCastCString(context, arguments[0]));
931 return CYMakeSelector(context, sel_registerName(name));
932 } CYCatch
933 }
934
935 JSObjectRef ffi(JSContextRef context, JSObjectRef object, size_t count, const JSValueRef arguments[], JSValueRef *exception) {
936 @try {
937 if (count != 2)
938 @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"incorrect number of arguments to Functor constructor" userInfo:nil];
939 void *function(CYCastPointer(context, arguments[0]));
940 const char *type(CYCastCString(context, arguments[1]));
941 return CYMakeFunction(context, function, type);
942 } CYCatch
943 }
944
945 JSValueRef Pointer_getProperty_value(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
946 ptrData *data(reinterpret_cast<ptrData *>(JSObjectGetPrivate(object)));
947 return JSValueMakeNumber(context, reinterpret_cast<uintptr_t>(data->value_));
948 }
949
950 JSValueRef Selector_getProperty_prototype(JSContextRef context, JSObjectRef object, JSStringRef property, JSValueRef *exception) {
951 return Function_;
952 }
953
954 static JSStaticValue Pointer_staticValues[2] = {
955 {"value", &Pointer_getProperty_value, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
956 {NULL, NULL, NULL, 0}
957 };
958
959 /*static JSStaticValue Selector_staticValues[2] = {
960 {"prototype", &Selector_getProperty_prototype, NULL, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete},
961 {NULL, NULL, NULL, 0}
962 };*/
963
964 CYDriver::CYDriver(const std::string &filename) :
965 state_(CYClear),
966 data_(NULL),
967 size_(0),
968 filename_(filename),
969 source_(NULL)
970 {
971 ScannerInit();
972 }
973
974 CYDriver::~CYDriver() {
975 ScannerDestroy();
976 }
977
978 void cy::parser::error(const cy::parser::location_type &location, const std::string &message) {
979 CYDriver::Error error;
980 error.location_ = location;
981 error.message_ = message;
982 driver.errors_.push_back(error);
983 }
984
985 MSInitialize { _pooled
986 apr_initialize();
987
988 NSCFBoolean_ = objc_getClass("NSCFBoolean");
989
990 pid_t pid(getpid());
991
992 struct sockaddr_in address;
993 address.sin_len = sizeof(address);
994 address.sin_family = AF_INET;
995 address.sin_addr.s_addr = INADDR_ANY;
996 address.sin_port = htons(10000 + pid);
997
998 CFDataRef data(CFDataCreate(kCFAllocatorDefault, reinterpret_cast<UInt8 *>(&address), sizeof(address)));
999
1000 CFSocketSignature signature;
1001 signature.protocolFamily = AF_INET;
1002 signature.socketType = SOCK_STREAM;
1003 signature.protocol = IPPROTO_TCP;
1004 signature.address = data;
1005
1006 CFSocketRef socket(CFSocketCreateWithSocketSignature(kCFAllocatorDefault, &signature, kCFSocketAcceptCallBack, &OnAccept, NULL));
1007 CFRunLoopAddSource(CFRunLoopGetCurrent(), CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0), kCFRunLoopDefaultMode);
1008
1009 JSClassDefinition definition;
1010
1011 definition = kJSClassDefinitionEmpty;
1012 definition.className = "Pointer";
1013 definition.staticValues = Pointer_staticValues;
1014 definition.finalize = &Pointer_finalize;
1015 Pointer_ = JSClassCreate(&definition);
1016
1017 definition = kJSClassDefinitionEmpty;
1018 definition.className = "Functor";
1019 definition.parentClass = Pointer_;
1020 definition.callAsFunction = &Functor_callAsFunction;
1021 Functor_ = JSClassCreate(&definition);
1022
1023 definition = kJSClassDefinitionEmpty;
1024 definition.className = "Selector";
1025 definition.parentClass = Pointer_;
1026 //definition.staticValues = Selector_staticValues;
1027 definition.callAsFunction = &Selector_callAsFunction;
1028 Selector_ = JSClassCreate(&definition);
1029
1030 definition = kJSClassDefinitionEmpty;
1031 definition.className = "Instance_";
1032 definition.getProperty = &Instance_getProperty;
1033 definition.callAsConstructor = &Instance_callAsConstructor;
1034 definition.finalize = &Instance_finalize;
1035 Instance_ = JSClassCreate(&definition);
1036
1037 definition = kJSClassDefinitionEmpty;
1038 definition.getProperty = &Global_getProperty;
1039 JSClassRef Global(JSClassCreate(&definition));
1040
1041 JSContextRef context(JSGlobalContextCreate(Global));
1042 Context_ = context;
1043
1044 JSObjectRef global(JSContextGetGlobalObject(context));
1045
1046 CYSetProperty(context, global, CYJSString("SEL"), JSObjectMakeConstructor(context, Selector_, &sel));
1047 CYSetProperty(context, global, CYJSString("ffi"), JSObjectMakeConstructor(context, Functor_, &ffi));
1048
1049 CYSetProperty(context, global, CYJSString("objc_msgSend"), JSObjectMakeFunctionWithCallback(context, CYJSString("objc_msgSend"), &$objc_msgSend));
1050
1051 Bridge_ = [[NSMutableDictionary dictionaryWithContentsOfFile:@"/usr/lib/libcycript.plist"] retain];
1052
1053 name_ = JSStringCreateWithUTF8CString("name");
1054 message_ = JSStringCreateWithUTF8CString("message");
1055 length_ = JSStringCreateWithUTF8CString("length");
1056
1057 Array_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Array")));
1058 Function_ = CYCastJSObject(context, CYGetProperty(context, global, CYJSString("Function")));
1059 }