]> git.saurik.com Git - cycript.git/blob - libcycript.cy
libcycript.cy needs to be set as symlink, for zip.
[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 this.toString();
77 return `new Number(${this.toString()})`;
78 },
79 });
80
81 $cy_set(RegExp.prototype, {
82 toCYON: function() {
83 return this.toString();
84 },
85 });
86
87 // XXX: Java should just always be available
88 if ("Java" in Cycript) {
89
90 // XXX: this is a half-assed EventEmitter
91 // XXX: this doesn't even have the same semantics
92
93 Java.handlers_ = {};
94
95 Java.on = function(event, handler) {
96 var handlers;
97 if (event in this.handlers_)
98 handlers = this.handlers_[event];
99 else {
100 handlers = [];
101 this.handlers_[event] = handlers;
102 }
103
104 if (this.handlers_ == null)
105 handler();
106 else
107 handlers.push(handler);
108 };
109
110 Java.emit = function(event) {
111 if (event in this.handlers_) {
112 var handlers = this.handlers_[event];
113 if (handlers != null)
114 for (var handler of handlers)
115 handler();
116 }
117
118 this.handlers_[event] = null;
119 };
120
121 Java.on('setup', function() {
122 $cy_set(java.lang.Boolean.prototype, {
123 toCYON: function() {
124 return `new java.lang.Boolean(${this->value})`;
125 },
126 });
127
128 $cy_set(java.lang.Byte.prototype, {
129 toCYON: function() {
130 return `new java.lang.Byte(${this->value})`;
131 },
132 });
133
134 $cy_set(java.lang.Character.prototype, {
135 toCYON: function() {
136 return `new java.lang.Character(${this->value})`;
137 },
138 });
139
140 $cy_set(java.lang.Short.prototype, {
141 toCYON: function() {
142 return `new java.lang.Short(${this->value})`;
143 },
144 });
145
146 $cy_set(java.lang.Integer.prototype, {
147 toCYON: function() {
148 return `new java.lang.Integer(${this->value})`;
149 },
150 });
151
152 $cy_set(java.lang.Long.prototype, {
153 toCYON: function() {
154 return `new java.lang.Long(${this->value})`;
155 },
156 });
157
158 $cy_set(java.lang.Float.prototype, {
159 toCYON: function() {
160 return `new java.lang.Float(${this->value})`;
161 },
162 });
163
164 $cy_set(java.lang.Double.prototype, {
165 toCYON: function() {
166 return `new java.lang.Double(${this->value})`;
167 },
168 });
169
170 $cy_set(java.lang.Object.prototype, {
171 toCYON: function(key) {
172 return "#" + this.toString().toCYON();
173 },
174
175 // XXX: due to lack of interface prototypes :(
176 $cyg: function(key) {
177 return this.get(key);
178 },
179
180 // XXX: due to lack of interface prototypes :(
181 $cys: function(key, value) {
182 if ("set" in this)
183 this.set(key, value);
184 else
185 this.put(key, value);
186 },
187 });
188
189 $cy_set(java.lang.Throwable.prototype, {
190 toCYON: function() {
191 var message = this.getMessage();
192 if (message == null)
193 message = '';
194 else
195 message = message.toCYON();
196
197 let stack = this.getStackTrace();
198 if (stack.length == 0)
199 stack = '';
200 else {
201 stack = stack.join('\n ');
202 stack = ` /*\n ${stack} */`;
203 }
204
205 return `new ${this.constructor.class.getName()}(${message})${stack}`;
206 },
207 });
208 });
209
210 }
211
212 if ("ObjectiveC" in Cycript) {
213 $cy_set(NSArray.prototype, {
214 $cyg: function(key) {
215 return objc_msgSend(this, "objectAtIndex:", key);
216 },
217
218 $cys: function(key, value) {
219 return objc_msgSend(this, "setObject:atIndex:", value, key);
220 },
221 });
222
223 $cy_set(NSDictionary.prototype, {
224 $cyg: function(key) {
225 return objc_msgSend(this, "objectForKey:", key);
226 },
227
228 $cys: function(key, value) {
229 return objc_msgSend(this, "setObject:forKey:", value, key);
230 },
231 });
232 }
233
234 let IsFile = function(path) {
235 // XXX: this doesn't work on symlinks, but I don't want to fix stat :/
236 return access(path, F_OK) == 0 && access(path + '/', F_OK) == -1;
237 };
238
239 let StartsWith = function(lhs, rhs) {
240 return lhs.substring(0, rhs.length) == rhs;
241 };
242
243 let ResolveFile = function(exact, name) {
244 if (exact && IsFile(name))
245 return name;
246 for (let suffix of ['.js', '.json'])
247 if (IsFile(name + suffix))
248 return name + suffix;
249 return null;
250 };
251
252
253 let GetLibraryPath = function() {
254 let handle = dlopen("/usr/lib/libcycript.dylib", RTLD_NOLOAD);
255 if (handle == null)
256 return null;
257
258 try {
259 let CYHandleServer = dlsym(handle, "CYHandleServer");
260 if (CYHandleServer == null)
261 return null;
262
263 let info = new Dl_info;
264 if (dladdr(CYHandleServer, info) == 0)
265 return null;
266
267 let path = info->dli_fname;
268 let slash = path.lastIndexOf('/');
269 if (slash == -1)
270 return null;
271
272 path = path.substr(0, slash);
273
274 GetLibraryPath = function() {
275 return path;
276 };
277
278 return GetLibraryPath();
279 } finally {
280 dlclose(handle);
281 }
282 };
283
284 let ResolveFolder = function(name) {
285 if (access(name + '/', F_OK) == -1)
286 return null;
287
288 if (IsFile(name + "/package.json")) {
289 let package = require(name + "/package.json");
290 let path = ResolveFile(true, name + "/" + package.main);
291 if (path != null)
292 return path;
293 }
294
295 return ResolveFile(false, name + "/index");
296 };
297
298 let ResolveEither = function(name) {
299 let path = null;
300 if (path == null)
301 path = ResolveFile(true, name);
302 if (path == null)
303 path = ResolveFolder(name);
304 return path;
305 };
306
307 require.resolve = function(name) {
308 if (StartsWith(name, '/')) {
309 let path = ResolveEither(name);
310 if (path != null)
311 return path;
312 } else {
313 let cwd = *new (typedef char[1024]);
314 cwd = getcwd(cwd, cwd.length).toString();
315 cwd = cwd.split('/');
316
317 if (StartsWith(name, './') || StartsWith(name, '../')) {
318 let path = ResolveEither(cwd + '/' + name);
319 if (path != null)
320 return path;
321 } else {
322 for (let i = cwd.length; i != 0; --i) {
323 let modules = cwd.slice(0, i).concat("node_modules").join('/');
324 let path = ResolveEither(modules + "/" + name);
325 if (path != null)
326 return path;
327 }
328
329 let library = GetLibraryPath();
330 let path = ResolveFile(true, library + "/cycript0.9/" + name + ".cy");
331 if (path != null)
332 return path;
333 }
334 }
335
336 throw new Error("Cannot find module '" + name + "'");
337 };
338
339 var _syscall = function(value) {
340 if (value == -1)
341 throw new Error(strerror(errno));
342 };
343
344 var info = *new (struct stat);
345 if (false) {
346 } else if ("st_atim" in info) {
347 var st_atime = "st_atim";
348 var st_mtime = "st_mtim";
349 var st_ctime = "st_ctim";
350 } else if ("st_atimespec" in info) {
351 var st_atime = "st_atimespec";
352 var st_mtime = "st_mtimespec";
353 var st_ctime = "st_ctimespec";
354 } else {
355 var st_atime = "st_atime";
356 var st_mtime = "st_mtime";
357 var st_ctime = "st_ctime";
358 }
359
360 var toDate = function(timespec) {
361 return new Date(timespec.tv_sec * 1000 + timespec.tv_nsec / 1000);
362 };
363
364 var bindings = {};
365
366 process.binding = function(name) {
367 let binding = bindings[name];
368 if (typeof binding != 'undefined')
369 return binding;
370
371 switch (name) {
372 case 'buffer': binding = {
373 setupBufferJS() {
374 },
375 }; break;
376
377 case 'cares_wrap': binding = {
378 }; break;
379
380 case 'constants': binding = {
381 }; break;
382
383 case 'fs': binding = {
384 FSInitialize() {
385 },
386
387 lstat(path) {
388 var info = new (struct stat);
389 _syscall(lstat(path, info));
390
391 return {
392 dev: info->st_dev,
393 mode: info->st_mode,
394 nlink: info->st_nlink,
395 uid: info->st_uid,
396 gid: info->st_gid,
397 rdev: info->st_rdev,
398 blksize: info->st_blksize,
399 ino: info->st_ino,
400 size: info->st_size,
401 blocks: info->st_blocks,
402
403 atime: toDate(info->[st_atime]),
404 mtime: toDate(info->[st_mtime]),
405 ctime: toDate(info->[st_ctime]),
406
407 isSymbolicLink() {
408 return S_ISLNK(this.mode);
409 },
410 };
411 },
412 }; break;
413
414 case 'pipe_wrap': binding = {
415 }; break;
416
417 case 'smalloc': binding = {
418 alloc() {
419 },
420 }; break;
421
422 case 'stream_wrap': binding = {
423 }; break;
424
425 case 'tcp_wrap': binding = {
426 }; break;
427
428 case 'timer_wrap': binding = {
429 kOnTimeout: 0,
430 Timer: {
431 },
432 }; break;
433
434 case 'tty_wrap': binding = {
435 }; break;
436
437 case 'uv': binding = {
438 }; break;
439
440 default:
441 throw new Error('No such module: ' + name);
442 }
443
444 bindings[name] = binding;
445 return binding;
446 };
447
448 process.env = {};
449
450 let environ = *(typedef char ***)(dlsym(RTLD_DEFAULT, "environ"));
451 for (let i = 0; environ[i] != null; ++i) {
452 let assign = environ[i];
453 let equal = assign.indexOf('=');
454 let name = assign.substr(0, equal);
455 let value = assign.substr(equal + 1);
456 process.env[name.toString()] = value;
457 }
458
459 process.cwd = function() {
460 let cwd = new (typedef char[1024]);
461 return getcwd(cwd, cwd.length).toString();
462 };
463
464 process.pid = getpid();
465
466 })();