]> git.saurik.com Git - cycript.git/blob - libcycript.cy
Hold JavaRef<jstring> throughout CYJavaUTF8String.
[cycript.git] / libcycript.cy
1 /* Cycript - The Truly Universal Scripting Language
2 * Copyright (C) 2009-2016 Jay Freeman (saurik)
3 */
4
5 /* GNU Affero General Public License, Version 3 {{{ */
6 /*
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 **/
20 /* }}} */
21
22 (function() {
23
24 this.typeid = function(object) {
25 return object.$cyt;
26 };
27
28 let $cy_set = function(object, properties) {
29 for (const name in properties)
30 Object.defineProperty(object, name, {
31 configurable: true,
32 enumerable: false,
33 writable: true,
34 value: properties[name],
35 });
36 };
37
38 $cy_set(Boolean.prototype, {
39 toCYON: function() {
40 return `new Boolean(${this.toString()})`;
41 },
42 });
43
44 $cy_set(Date.prototype, {
45 toCYON: function() {
46 return `new ${this.constructor.name}(${this.toUTCString().toCYON()})`;
47 },
48 });
49
50 $cy_set(Error.prototype, {
51 toCYON: function() {
52 let stack = this.stack;
53 if (typeof stack == 'undefined')
54 stack = '';
55 else {
56 stack = stack.split('\n');
57 if (stack.slice(-1)[0] == "global code")
58 stack = stack.slice(0, -1);
59 for (let i = 0; i != stack.length; ++i)
60 stack[i] = '\n ' + stack[i];
61 if (stack.length == 0)
62 stack = '';
63 else {
64 stack = stack.join('');
65 stack = ` /*${stack} */`;
66 }
67 }
68 return `new ${this.constructor.name}(${this.message.toCYON()})${stack}`;
69 },
70 });
71
72 $cy_set(Number.prototype, {
73 toCYON: function() {
74 if ("$cyt" in this)
75 return `${this.$cyt.toCYON()}(${this.toString()})`;
76 return `new Number(${this.toString()})`;
77 },
78 });
79
80 $cy_set(RegExp.prototype, {
81 toCYON: function() {
82 return this.toString();
83 },
84 });
85
86 // XXX: Java should just always be available
87 if ("Java" in Cycript) {
88
89 // XXX: this is a half-assed EventEmitter
90 // XXX: this doesn't even have the same semantics
91
92 Java.handlers_ = {};
93
94 Java.on = function(event, handler) {
95 var handlers;
96 if (event in this.handlers_)
97 handlers = this.handlers_[event];
98 else {
99 handlers = [];
100 this.handlers_[event] = handlers;
101 }
102
103 if (this.handlers_ == null)
104 handler();
105 else
106 handlers.push(handler);
107 };
108
109 Java.emit = function(event) {
110 if (event in this.handlers_) {
111 var handlers = this.handlers_[event];
112 if (handlers != null)
113 for (var handler of handlers)
114 handler();
115 }
116
117 this.handlers_[event] = null;
118 };
119
120 Java.on('setup', function() {
121 $cy_set(java.lang.Boolean.prototype, {
122 toCYON: function() {
123 return `new java.lang.Boolean(${this->value})`;
124 },
125 });
126
127 $cy_set(java.lang.Byte.prototype, {
128 toCYON: function() {
129 return `new java.lang.Byte(${this->value})`;
130 },
131 });
132
133 $cy_set(java.lang.Character.prototype, {
134 toCYON: function() {
135 return `new java.lang.Character(${this->value})`;
136 },
137 });
138
139 $cy_set(java.lang.Short.prototype, {
140 toCYON: function() {
141 return `new java.lang.Short(${this->value})`;
142 },
143 });
144
145 $cy_set(java.lang.Integer.prototype, {
146 toCYON: function() {
147 return `new java.lang.Integer(${this->value})`;
148 },
149 });
150
151 $cy_set(java.lang.Long.prototype, {
152 toCYON: function() {
153 return `new java.lang.Long(${this->value})`;
154 },
155 });
156
157 $cy_set(java.lang.Float.prototype, {
158 toCYON: function() {
159 return `new java.lang.Float(${this->value})`;
160 },
161 });
162
163 $cy_set(java.lang.Double.prototype, {
164 toCYON: function() {
165 return `new java.lang.Double(${this->value})`;
166 },
167 });
168
169 $cy_set(java.lang.Object.prototype, {
170 toCYON: function(key) {
171 return "#" + this.toString().toCYON();
172 },
173
174 // XXX: due to lack of interface prototypes :(
175 $cyg: function(key) {
176 return this.get(key);
177 },
178
179 // XXX: due to lack of interface prototypes :(
180 $cys: function(key, value) {
181 if ("set" in this)
182 this.set(key, value);
183 else
184 this.put(key, value);
185 },
186 });
187
188 $cy_set(java.lang.Throwable.prototype, {
189 toCYON: function() {
190 var message = this.getMessage();
191 if (message == null)
192 message = '';
193 else
194 message = message.toCYON();
195
196 let stack = this.getStackTrace();
197 if (stack.length == 0)
198 stack = '';
199 else {
200 stack = stack.join('\n ');
201 stack = ` /*\n ${stack} */`;
202 }
203
204 return `new ${this.constructor.class.getName()}(${message})${stack}`;
205 },
206 });
207 });
208
209 }
210
211 if ("ObjectiveC" in Cycript) {
212 $cy_set(NSArray.prototype, {
213 $cyg: function(key) {
214 return objc_msgSend(this, "objectAtIndex:", key);
215 },
216
217 $cys: function(key, value) {
218 return objc_msgSend(this, "setObject:atIndex:", value, key);
219 },
220 });
221
222 $cy_set(NSDictionary.prototype, {
223 $cyg: function(key) {
224 return objc_msgSend(this, "objectForKey:", key);
225 },
226
227 $cys: function(key, value) {
228 return objc_msgSend(this, "setObject:forKey:", value, key);
229 },
230 });
231 }
232
233 let IsFile = function(path) {
234 // XXX: this doesn't work on symlinks, but I don't want to fix stat :/
235 return access(path, F_OK) == 0 && access(path + '/', F_OK) == -1;
236 };
237
238 let StartsWith = function(lhs, rhs) {
239 return lhs.substring(0, rhs.length) == rhs;
240 };
241
242 let ResolveFile = function(exact, name) {
243 if (exact && IsFile(name))
244 return name;
245 for (let suffix of ['.js', '.json'])
246 if (IsFile(name + suffix))
247 return name + suffix;
248 return null;
249 };
250
251
252 let GetLibraryPath = function() {
253 let handle = dlopen("/usr/lib/libcycript.dylib", RTLD_NOLOAD);
254 if (handle == null)
255 return null;
256
257 try {
258 let CYHandleServer = dlsym(handle, "CYHandleServer");
259 if (CYHandleServer == null)
260 return null;
261
262 let info = new Dl_info;
263 if (dladdr(CYHandleServer, info) == 0)
264 return null;
265
266 let path = info->dli_fname;
267 let slash = path.lastIndexOf('/');
268 if (slash == -1)
269 return null;
270
271 path = path.substr(0, slash);
272
273 GetLibraryPath = function() {
274 return path;
275 };
276
277 return GetLibraryPath();
278 } finally {
279 dlclose(handle);
280 }
281 };
282
283 let ResolveFolder = function(name) {
284 if (access(name + '/', F_OK) == -1)
285 return null;
286
287 if (IsFile(name + "/package.json")) {
288 let package = require(name + "/package.json");
289 let path = ResolveFile(true, name + "/" + package.main);
290 if (path != null)
291 return path;
292 }
293
294 return ResolveFile(false, name + "/index");
295 };
296
297 let ResolveEither = function(name) {
298 let path = null;
299 if (path == null)
300 path = ResolveFile(true, name);
301 if (path == null)
302 path = ResolveFolder(name);
303 return path;
304 };
305
306 require.resolve = function(name) {
307 if (StartsWith(name, '/')) {
308 let path = ResolveEither(name);
309 if (path != null)
310 return path;
311 } else {
312 let cwd = new (typedef char[1024]);
313 cwd = getcwd(cwd, cwd.length).toString();
314 cwd = cwd.split('/');
315
316 if (StartsWith(name, './') || StartsWith(name, '../')) {
317 let path = ResolveEither(cwd + '/' + name);
318 if (path != null)
319 return path;
320 } else {
321 for (let i = cwd.length; i != 0; --i) {
322 let modules = cwd.slice(0, i).concat("node_modules").join('/');
323 let path = ResolveEither(modules + "/" + name);
324 if (path != null)
325 return path;
326 }
327
328 let library = GetLibraryPath();
329 let path = ResolveFile(true, library + "/cycript0.9/" + name + ".cy");
330 if (path != null)
331 return path;
332 }
333 }
334
335 throw new Error("Cannot find module '" + name + "'");
336 };
337
338 var _syscall = function(value) {
339 if (value == -1)
340 throw new Error(strerror(errno));
341 };
342
343 var info = *new (struct stat);
344 if (false) {
345 } else if ("st_atim" in info) {
346 var st_atime = "st_atim";
347 var st_mtime = "st_mtim";
348 var st_ctime = "st_ctim";
349 } else if ("st_atimespec" in info) {
350 var st_atime = "st_atimespec";
351 var st_mtime = "st_mtimespec";
352 var st_ctime = "st_ctimespec";
353 } else {
354 var st_atime = "st_atime";
355 var st_mtime = "st_mtime";
356 var st_ctime = "st_ctime";
357 }
358
359 var toDate = function(timespec) {
360 return new Date(timespec.tv_sec * 1000 + timespec.tv_nsec / 1000);
361 };
362
363 var bindings = {};
364
365 process.binding = function(name) {
366 let binding = bindings[name];
367 if (typeof binding != 'undefined')
368 return binding;
369
370 switch (name) {
371 case 'buffer': binding = {
372 setupBufferJS() {
373 },
374 }; break;
375
376 case 'cares_wrap': binding = {
377 }; break;
378
379 case 'constants': binding = {
380 }; break;
381
382 case 'fs': binding = {
383 FSInitialize() {
384 },
385
386 lstat(path) {
387 var info = new (struct stat);
388 _syscall(lstat(path, info));
389
390 return {
391 dev: info->st_dev,
392 mode: info->st_mode,
393 nlink: info->st_nlink,
394 uid: info->st_uid,
395 gid: info->st_gid,
396 rdev: info->st_rdev,
397 blksize: info->st_blksize,
398 ino: info->st_ino,
399 size: info->st_size,
400 blocks: info->st_blocks,
401
402 atime: toDate(info->[st_atime]),
403 mtime: toDate(info->[st_mtime]),
404 ctime: toDate(info->[st_ctime]),
405
406 isSymbolicLink() {
407 return S_ISLNK(this.mode);
408 },
409 };
410 },
411 }; break;
412
413 case 'pipe_wrap': binding = {
414 }; break;
415
416 case 'smalloc': binding = {
417 alloc() {
418 },
419 }; break;
420
421 case 'stream_wrap': binding = {
422 }; break;
423
424 case 'tcp_wrap': binding = {
425 }; break;
426
427 case 'timer_wrap': binding = {
428 kOnTimeout: 0,
429 Timer: {
430 },
431 }; break;
432
433 case 'tty_wrap': binding = {
434 }; break;
435
436 case 'uv': binding = {
437 }; break;
438
439 default:
440 throw new Error('No such module: ' + name);
441 }
442
443 bindings[name] = binding;
444 return binding;
445 };
446
447 process.env = {};
448
449 let environ = *(typedef char ***)(dlsym(RTLD_DEFAULT, "environ"));
450 for (let i = 0; environ[i] != null; ++i) {
451 let assign = environ[i];
452 let equal = assign.indexOf('=');
453 let name = assign.substr(0, equal);
454 let value = assign.substr(equal + 1);
455 process.env[name.toString()] = value;
456 }
457
458 process.cwd = function() {
459 let cwd = new (typedef char[1024]);
460 return getcwd(cwd, cwd.length).toString();
461 };
462
463 process.pid = getpid();
464
465 })();