29 |
30 | namespace sig {
31 |
32 | void Parse_(apr_pool_t *pool, struct Signature *signature, const char **name, char eos, Callback callback);
33 | struct Type *Parse_(apr_pool_t *pool, const char **name, char eos, bool named, Callback callback);
34 |
35 |
36 | /* XXX: I really screwed up this time */
37 | void *prealloc_(apr_pool_t *pool, void *odata, size_t osize, size_t nsize) {
38 | void *ndata = apr_palloc(pool, nsize);
39 | memcpy(ndata, odata, osize);
40 | return ndata;
41 | }
42 |
43 | void Parse_(apr_pool_t *pool, struct Signature *signature, const char **name, char eos, Callback callback) {
44 | _assert(*name != NULL);
45 |
46 | // XXX: this is just a stupid check :(
47 | bool named(**name == '"');
48 |
49 | signature->elements = NULL;
50 | signature->count = 0;
51 |
52 | for (;;) {
53 | if (**name == eos) {
54 | ++*name;
55 | return;
56 | }
57 |
58 | signature->elements = (struct Element *) prealloc_(pool, signature->elements, signature->count * sizeof(struct Element), (signature->count + 1) * sizeof(struct Element));
59 | _assert(signature->elements != NULL);
60 |
61 | struct Element *element = &signature->elements[signature->count++];
62 |
63 | if (**name != '"')
64 | element->name = NULL;
65 | else {
66 | const char *quote = strchr(++*name, '"');
67 | element->name = apr_pstrmemdup(pool, *name, quote - *name);
68 | *name = quote + 1;
69 | }
70 |
71 | element->type = Parse_(pool, name, eos, named, callback);
72 |
73 | if (**name < '0' || **name > '9')
74 | element->offset = _not(size_t);
75 | else {
76 | element->offset = 0;
77 |
78 | do
79 | element->offset = element->offset * 10 + (*(*name)++ - '0');
80 | while (**name >= '0' && **name <= '9');
81 | }
82 | }
83 | }
84 |
85 | struct Type *Parse_(apr_pool_t *pool, const char **name, char eos, bool named, Callback callback) {
86 | char next = *(*name)++;
87 | if (next == '?')
88 | return NULL;
89 |
90 | struct Type *type = (struct Type *) apr_palloc(pool, sizeof(struct Type));
91 | _assert(type != NULL);
92 | memset(type, 0, sizeof(struct Type));
93 |
94 | parse:
95 | switch (next) {
96 | case '#': type->primitive = typename_P; break;
97 |
98 | case '(':
99 | if (type->data.signature.count < 2)
100 | type->primitive = struct_P;
101 | else
102 | type->primitive = union_P;
103 | next = ')';
104 | goto aggregate;
105 |
106 | case '*': type->primitive = string_P; break;
107 | case ':': type->primitive = selector_P; break;
108 |
109 | case '@': {
110 | char next(**name);
111 |
112 | if (next == '?') {
113 | type->primitive = block_P;
114 | ++*name;
115 | } else {
116 | type->primitive = object_P;
117 |
118 | if (next == '"') {
119 | const char *quote = strchr(*name + 1, '"');
120 | if (!named || quote[1] == eos || quote[1] == '"') {
121 | type->name = apr_pstrmemdup(pool, *name + 1, quote - *name - 1);
122 | *name = quote + 1;
123 | }
124 | }
125 | }
126 |
127 | } break;
128 |
129 | case 'B': type->primitive = boolean_P; break;
130 | case 'C': type->primitive = uchar_P; break;
131 | case 'I': type->primitive = uint_P; break;
132 | case 'L': type->primitive = ulong_P; break;
133 | case 'Q': type->primitive = ulonglong_P; break;
134 | case 'S': type->primitive = ushort_P; break;
135 |
136 | case '[':
137 | type->primitive = array_P;
138 | type->data.data.size = strtoul(*name, (char **) name, 10);
139 | type->data.data.type = Parse_(pool, name, eos, false, callback);
140 | if (**name != ']') {
141 | printf("']' != \"%s\"\n", *name);
142 | _assert(false);
143 | }
144 | ++*name;
145 | break;
146 |
147 | case '^':
148 | type->primitive = pointer_P;
149 | if (**name == '"') {
150 | type->data.data.type = NULL;
151 | } else {
152 | type->data.data.type = Parse_(pool, name, eos, named, callback);
153 | sig::Type *&target(type->data.data.type);
154 | if (target != NULL && target->primitive == void_P)
155 | target = NULL;
156 | }
157 | break;
158 |
159 | case 'b':
160 | type->primitive = bit_P;
161 | type->data.data.size = strtoul(*name, (char **) name, 10);
162 | break;
163 |
164 | case 'c': type->primitive = char_P; break;
165 | case 'd': type->primitive = double_P; break;
166 | case 'f': type->primitive = float_P; break;
167 | case 'i': type->primitive = int_P; break;
168 | case 'l': type->primitive = long_P; break;
169 | case 'q': type->primitive = longlong_P; break;
170 | case 's': type->primitive = short_P; break;
171 | case 'v': type->primitive = void_P; break;
172 |
173 | case '{':
174 | type->primitive = struct_P;
175 | next = '}';
176 | goto aggregate;
177 |
178 | aggregate: {
179 | char end = next;
180 | const char *begin = *name;
181 | do next = *(*name)++;
182 | while (
183 | next != '=' &&
184 | next != '}'
185 | );
186 | size_t length = *name - begin - 1;
187 | if (strncmp(begin, "?", length) != 0)
188 | type->name = (char *) apr_pstrmemdup(pool, begin, length);
189 | else
190 | type->name = NULL;
191 |
192 | // XXX: this types thing is a throwback to JocStrap
193 |
194 | if (next == '=')
195 | Parse_(pool, &type->data.signature, name, end, callback);
196 | } break;
197 |
198 | case 'N': type->flags |= JOC_TYPE_INOUT; goto next;
199 | case 'n': type->flags |= JOC_TYPE_IN; goto next;
200 | case 'O': type->flags |= JOC_TYPE_BYCOPY; goto next;
201 | case 'o': type->flags |= JOC_TYPE_OUT; goto next;
202 | case 'R': type->flags |= JOC_TYPE_BYREF; goto next;
203 | case 'r': type->flags |= JOC_TYPE_CONST; goto next;
204 | case 'V': type->flags |= JOC_TYPE_ONEWAY; goto next;
205 |
206 | next:
207 | next = *(*name)++;
208 | goto parse;
209 | break;
210 |
211 | default:
212 | printf("invalid type character: '%c' {%s}\n", next, *name - 10);
213 | _assert(false);
214 | }
215 |
216 | if (callback != NULL)
217 | (*callback)(pool, type);
218 |
219 | return type;
220 | }
221 |
222 | void Parse(apr_pool_t *pool, struct Signature *signature, const char *name, Callback callback) {
223 | const char *temp = name;
224 | Parse_(pool, signature, &temp, '\0', callback);
225 | _assert(temp[-1] == '\0');
226 | }
227 |
228 | const char *Unparse(apr_pool_t *pool, struct Signature *signature) {
229 | const char *value = "";
230 | size_t offset;
231 |
232 | for (offset = 0; offset != signature->count; ++offset) {
233 | const char *type = Unparse(pool, signature->elements[offset].type);
234 | value = apr_pstrcat(pool, value, type, NULL);
235 | }
236 |
237 | return value;
238 | }
239 |
240 | const char *Unparse(apr_pool_t *pool, struct Type *type) {
241 | if (type == NULL)
242 | return "?";
243 | else switch (type->primitive) {
244 | case typename_P: return "#";
245 | case union_P: return apr_psprintf(pool, "(%s)", Unparse(pool, &type->data.signature));
246 | case string_P: return "*";
247 | case selector_P: return ":";
248 | case block_P: return "@?";
249 | case object_P: return type->name == NULL ? "@" : apr_psprintf(pool, "@\"%s\"", type->name);
250 | case boolean_P: return "B";
251 | case uchar_P: return "C";
252 | case uint_P: return "I";
253 | case ulong_P: return "L";
254 | case ulonglong_P: return "Q";
255 | case ushort_P: return "S";
256 |
257 | case array_P: {
258 | const char *value = Unparse(pool, type->data.data.type);
259 | return apr_psprintf(pool, "[%"APR_SIZE_T_FMT"%s]", type->data.data.size, value);
260 | } break;
261 |
262 | case pointer_P: return apr_psprintf(pool, "^%s", type->data.data.type == NULL ? "v" : Unparse(pool, type->data.data.type));
263 | case bit_P: return apr_psprintf(pool, "b%"APR_SIZE_T_FMT"", type->data.data.size);
264 | case char_P: return "c";
265 | case double_P: return "d";
266 | case float_P: return "f";
267 | case int_P: return "i";
268 | case long_P: return "l";
269 | case longlong_P: return "q";
270 | case short_P: return "s";
271 | case void_P: return "v";
272 | case struct_P: return apr_psprintf(pool, "{%s=%s}", type->name == NULL ? "?" : type->name, Unparse(pool, &type->data.signature));
273 | }
274 |
275 | _assert(false);
276 | return NULL;
277 | }
278 |
279 | }
280 |
--------------------------------------------------------------------------------
/website/index.html:
--------------------------------------------------------------------------------
1 | Cycript
2 |
3 |
4 | Cycript: Objective-JavaScript
5 |
6 | What is Cycript?
7 |
8 | A programming language designed to blend the barrier between Objective-C and JavaScript. This project has similar goals to JSCocoa, but a very different set of starting technologies and a different guiding philosophy. In particular, Cycript has started life with a full-blown JavaScript parser/serializer, allowing it to have interesting hybrid syntax without constraints (such as those imposed on JSCocoa by JSLint).
9 |
10 | Is it done?
11 |
12 | Well, it works ;P. It is still "in flux": core language features are changing every few hours. However, it has already changed the workflow of the "elite" iPhone developers that write most of the extensions you see in Cydia: having a language that changes doesn't matter when you are mostly using it at the immediate console. I'm hoping, however, that I manage tolock it into something that feels "correct" in the very near future.
13 |
14 | How do you pronounce "Cycript"?
15 |
16 | I pronounce it "sscript" (with a geminate, aka long, 's'). I doubt anyone else will pronounce it like this, but I have my hopes.
17 |
18 | Where do I get it?
19 |
20 | Right now you can find releases of it at: http://www.cycript.org/debs/. This package depends on MobileSubstrate and libffi (both of which are in Cydia).
21 |
22 | So, how do I use it?!
23 |
24 | Although you can write full applications in Cycript, the fastest way to get playing with it is via the immediate console: just type "cycript".
25 |
26 |
iPhone:~$ cycript
27 | cy#
28 |
29 | Code typed at this prompt will be executed as it is able to be parsed: the immediate console is trying to eagerly parse lines of code as they come in (and thereby is not subject to automatic-semicolon insertion, for those JavaScript experts). Parse errors will be noted to the output in a hopefully useful fashion.
30 |
31 | cy# function a() {
32 | cy> a + q r
33 | | .........^
34 | | syntax error, unexpected Identifier, expecting ; or "\n"
35 | cy#
36 |
37 | It should be noted that it is possible that you will manage to break my JavaScript serializer. In these cases, parse errors may be thrown by the underlying JavaScript engine rather than Cycript. To debug these issues you can use the special console command ?debug.
38 |
39 | cy# ?debug
40 | debug == true
41 | cy# var a = ((0 + (1)) * (2 * 3)) + m['a']('\'')
42 | var a=(0+1)*(2*3)+m.a("'");
43 | ...
44 |
45 | In addition to standard JavaScript, you an also access anything in the Objective-C runtime. Attempts have been made, sparingly, to bridge syntax when possible between the two environments. In particular, you may notice interesting properties of arrays, dictonaries, strings, and numbers. Care has been taken to minimize the damage to the object model.
46 |
47 | cy# var a = [NSMutableArray arrayWithCapacity:4]
48 | cy# a instanceof Array
49 | true
50 | cy# [a class]
51 | "NSCFArray"
52 | cy# [a addObject:"hello"]; a
53 | ["hello"]
54 | cy# a[1] = 4; a.push(10); a
55 | ["hello",4,10]
56 | cy# a.splice(1, 1, 6, 7); a
57 | ["hello",6,7,10]
58 | cy# b = [1, 2]; [b replaceObjectAtIndex:0 withObject:5]; b
59 | [5,2]
60 |
61 | Memory management is mostly automatic, but instead of using the usual -[alloc] message you will need to use JavaScript's "new" operator, which returns a special "uninitialized" handle that can be used to send a single message (probably a form of init) before it "expires" and reverts to nil.
62 |
63 | cy# var a = new NSMutableDictionary
64 | cy# a
65 | "*** -[NSCFDictionary count]: method sent to an uninitialized mutable dictionary object"
66 | cy# var b = [a init]; b
67 | {}
68 | cy# a
69 | nil
70 | cy# var q = [new NSString init]; q
71 | ""
72 |
73 | One note in particular is made about selectors. Not only do they act as in Objective-C, including being typed using @selector notation, but they also have Function.prototype in their prototype-chain, allowing you to use them in interesting functional ways ala JavaScript. You can also generate one from a string using new Selector().
74 |
75 | cy# var sel = @selector(initWithFrame:)
76 | cy# sel
77 | @selector(initWithFrame:)
78 | cy# sel.call(new UIView, [UIHardware fullScreenApplicationContentRect])
79 | ">"
80 | cy# new Selector("initWithFrame:")
81 | @selector(initWithFrame:)
82 |
83 | As one would expect from JavaScript, objects have a property called constructor that references their class. You can also add methods along the prototype chain to instances. Eventually, all objects go through Instance, where you can put functions that should be available for all Objective-C classes.
84 |
85 | cy# Instance.prototype.getMethod = function (sel) { return class_getInstanceMethod(this, sel); }
86 | {}
87 | cy# NSObject.getMethod(@selector(init))
88 | 0x801354
89 | cy# NSObject.prototype.getMethod = function (sel) { return "ark"; }
90 | {}
91 | cy# NSObject.getMethod(@selector(init))
92 | "ark"
93 |
94 | Given that sending messages is actually a different namespace than function resolution, it is important to separate out the analog of a "prototype" in the world of Objective-C from that in JavaScript. Therefore, a field called "messages" (may change) is also added to Class objects. These messages can even be traded around and reassigned, with the results fully mapping back to the Objective-C runtime.
95 |
96 | cy# var view = [new UIView init]
97 | cy# view.constructor
98 | "UIView"
99 | cy# view.constructor.messages['description']
100 | 0x309d84f5
101 | cy# [view description]
102 | ">"
103 | cy# view.constructor.messages['description'] = function () { return "not!"; }
104 | {}
105 | cy# [view description]
106 | "not!"
107 |
108 | Structures are also supported (although unions are currently on the todo list and bitfields are still DOA): they are bridged back/forth as much as possible. You can specify them using either array syntax or in the form of dictionaries.
109 |
110 | cy# var rect = [UIHardware fullScreenApplicationContentRect]
111 | cy# rect
112 | {origin:{x:0,y:20},size:{width:320,height:460}}
113 | cy# rect.origin = [2, 3]
114 | [2,3]
115 | cy# rect.size = {width: 0, height: 1}
116 | {width:0,height:1}
117 | cy# rect
118 | {origin:{x:2,y:3},size:{width:0,height:1}}
119 |
120 | Access, allocation, and casting of pointers is possible through the usage of the Pointer and Type classes. Pointers can be indirected using the * and -> operators, as in C.
121 |
122 | cy# var count = new new Type("I")
123 | cy# var methods = class_copyMethodList(UIApplication, count)
124 | cy# *count
125 | 305
126 | cy# *new Pointer(count, "d")
127 | 7.304555902977629e-304
128 | cy# free(count)
129 | cy# methods
130 | 0x843800
131 | cy# methods[304]
132 | 0x825248
133 | cy# method_getName(methods[304])
134 | @selector(init)
135 |
136 | Objective-C @properties (some of which are auto-detected, as Apple doesn't always compile them into the resulting binaries) can be accessed using . notation. Currently, auto-detected @properties are usable, but aren't enumerable. This namespace is strictly separated from that of instance variables, which you can access by indirecting the object using * or ->.
137 |
138 | cy# var view = [new UIView init]
139 | cy# ps = []; for (var p in view) ps.push(p); ps
140 | ["skipsSubviewEnumeration","gestureRecognizers","gesturesEnabled","capturesDescendantTouches","deliversTouchesForGesturesToSuperview","userInteractionEnabled","layer","tag"]
141 | cy# vs = []; for (var v in *view) vs.push(v); vs
142 | ["isa","_layer","_tapInfo","_gestureInfo","_gestureRecognizers","_charge","_tag","_viewFlags"]
143 | cy# view.layer
144 | ""
145 | cy# view->_layer
146 | ""
147 | cy# (*view)._layer
148 | ""
149 |
150 | Fully-fledged Objective-C classes can also be declared using @class, which blurs the line between Objective-C's @interface and @implementation. Right now, declaring instance variables are not supported, but will be in a future version: for now you must provide an empty variable block.
151 |
152 | cy# @class TestClass : NSObject {
153 | cy> }
154 | cy> - description {
155 | cy> return "test";
156 | cy> }
157 | cy> @end
158 | cy# [new TestClass init]
159 | "test"
160 |
161 | The @class syntax can also be used to extend existing classes in a manner similar to categories. Note that type signatures, however, are not yet supported, so you end up heavily restricted in what you can add via this mechanism. In this case, one can also use a parenthesized expression as the class name.
162 |
163 | cy# @class NSObject
164 | cy> - description { return "replaced"; }
165 | cy> @end
166 | cy# var o = [new NSObject init]
167 | cy# o
168 | "replaced"
169 | cy# @class ([o class]) - description { return "again"; } @end
170 | cy# o
171 | "again"
172 |
173 | Cycript is also capable of accessing normal C functions and variables. Knowledge of the type signatures of various functions are provided in the bridge definition file, which is currently a plist stored at /usr/lib/libcycript.plist.
174 |
175 | cy# malloc
176 | 0x31d48389
177 | cy# var p = malloc(4)
178 | cy# p
179 | 0x22e0a0
180 | cy# free(p)
181 | cy#
182 |
183 | Cycript attempts to do its best to serialize information to the console about objects. In particular, CoreFoundaton objects bridged to Objective-C are detected and printed using CFCopyDescription.
184 |
185 | cy# UIGetScreenImage()
186 | ""
187 | cy# ABAddressBookCreate()
188 | ""
189 |
190 | How do I write an application with it?
191 |
192 | This isn't quite "ready for primetime", but you can download the example HelloCycript.app from http://www.cycript.org/examples/ and put it in /Applicatons.
193 |
194 | What else can it do?
195 |
196 | Probably the awesomest thing you can do with Cycript is to hook into an existing process using the -p argument to the console interpreter. As an example, let's hook our way into SpringBoard and start spelunking.
197 |
198 | iPhone:~$ ps ax | grep Spring
199 | 18110 ?? Us 0:03.03 /System/Library/CoreServices/SpringBoard.app/SpringBoard
200 | 18115 s006 S+ 0:00.02 grep --color=auto --exclude=.svn Spring
201 | iPhone:~$ cycript -p 18110
202 | cy# UIApp
203 | ""
204 | cy# UIApp->_uiController.window
205 | ">"
206 | cy# UIApp->_uiController.window.subviews
207 | [">","> enabled: yes, context array: (\n)","> enabled: yes, context array: (\n)"]
208 | cy# UIApp->_uiController.window.subviews[0].subviews
209 | [">",">"]
210 | cy# UIApp->_uiController.window.subviews[0].subviews[0].image.size
211 | {width:320,height:480}
212 | cy# UIApp->_uiController.window.subviews[0].subviews[1].subviews
213 | [">",">"]
214 | cy# UIApp->_uiController.window.subviews[0].subviews[1].subviews[0].subviews
215 | [">",">"]
216 | cy# var pages = UIApp->_uiController.window.subviews[0].subviews[1].subviews[0].subviews[0]
217 | cy# pages.currentPage
218 | 1
219 | cy# pages.numberOfPages
220 | 15
221 |
222 |
223 |
--------------------------------------------------------------------------------