2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
24 /** Build your own virtual machine! Use methods in this class to generate
25 * a skeleton JVM in JavaScript that contains pre-compiled classes of your
28 * Writer w = new {@link java.io.StringWriter}();
29 * {@link #newCompiler() Bck2Brwsr.newCompiler}()
30 * .{@link #resources(org.apidesign.vm4brwsr.Bck2Brwsr.Resources)}
31 * .{@link #addRootClasses(java.lang.String...)}
32 * .{@link #addClasses(java.lang.String...)}
33 * .{@link #addExported(java.lang.String...)}
34 * .{@link #generate(java.lang.Appendable) generate(w)};
35 * System.out.{@link java.io.PrintStream#print(java.lang.String) print(w.toString())};
37 * The generated script defines one JavaScript method that can
38 * be used to bootstrap and load the virtual machine: <pre>
39 * var vm = bck2brwsr();
40 * var main = vm.loadClass('org.your.pkg.Main');
41 * main.invoke('main');
43 * In case one wants to initialize the virtual machine with ability to
44 * load classes lazily when needed, one can provide a loader function to
45 * when creating the virtual machine: <pre>
46 * var vm = bck2brwsr(function(resource) {
47 * return null; // byte[] for the resource
50 * In this scenario, when a request for an unknown class is made, the loader
51 * function is asked for its byte code and the system dynamically transforms
54 * Instead of a loader function, one can also provide a URL to a JAR file
55 * or a library JavaScript file generated with {@link #library(java.lang.String...)}
57 * The <code>bck2brwsr</code> system will do its best to download the file
58 * and provide loader function for it automatically. In order to use
59 * the JAR file <code>emul.zip</code> module needs to be available in the system.
61 * One can provide as many loader functions and URL references as necessary.
62 * Then the initialization code would look like:<pre>
63 * var vm = bck2brwsr(url1, url2, fnctn1, url3, functn2);
65 * The provided URLs and loader functions will be consulted one by one.
67 * The initialization of the <b>Bck2Brwsr</b> is done asynchronously since
68 * version 0.9. E.g. call to <pre>
69 * var vm = bck2brwsr('myapp.js');
70 * var main = vm.loadClass('org.your.pkg.Main');
71 * main.invoke('main');
73 * returns immediately and the call to the static main method will happen
74 * once the virtual machine is initialized and the class available.
76 * @author Jaroslav Tulach
78 public final class Bck2Brwsr {
79 private final ObfuscationLevel level;
80 private final StringArray exported;
81 private final StringArray classes;
82 private final StringArray resources;
83 private final Resources res;
84 private final Boolean extension;
85 private final StringArray classpath;
86 private final Flow.Analyzer flow;
89 ObfuscationLevel level, StringArray exported,
90 StringArray classes, StringArray resources, Resources res,
91 Boolean extension, StringArray classpath, Flow.Analyzer flow
94 this.exported = exported;
95 this.classes = classes;
96 this.resources = resources;
98 this.extension = extension;
99 this.classpath = classpath;
103 /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
106 * @param out the output to write the generated JavaScript to
107 * @param resources provider of class files to use
108 * @param classes additional classes to include in the generated script
109 * @throws IOException I/O exception can be thrown when something goes wrong
111 public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
112 newCompiler().resources(resources).addRootClasses(classes).generate(out);
115 /** Helper method to generate virtual machine from bytes served by a class loader.
117 * @param out the output to write the generated JavaScript to
118 * @param loader class loader to load needed classes from
119 * @param classes additional classes to include in the generated script
120 * @throws IOException I/O exception can be thrown when something goes wrong
122 public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
123 newCompiler().resources(loader).addRootClasses(classes).generate(out);
126 /** Creates new instance of Bck2Brwsr compiler which is ready to generate
127 * empty Bck2Brwsr virtual machine. The instance can be further
128 * configured by calling chain of methods. For example:
130 * {@link #newCompiler()}.{@link #resources(org.apidesign.vm4brwsr.Bck2Brwsr.Resources) resources(loader)}.{@link #addRootClasses(java.lang.String[]) addRootClasses("your/Clazz")}.{@link #generate(java.lang.Appendable) generate(out)};
133 * @return new instance of the Bck2Brwsr compiler
136 public static Bck2Brwsr newCompiler() {
137 return new Bck2Brwsr(
138 ObfuscationLevel.NONE,
139 new StringArray(), new StringArray(), new StringArray(),
140 null, false, null, null
144 /** Adds exported classes or packages. If the string ends
145 * with slash, it is considered a name of package. If it does not,
146 * it is a name of a class (without <code>.class</code> suffix).
147 * The exported classes are prevented from being obfuscated.
148 * All public classes in exported packages are prevented from
149 * being obfuscated. By listing the packages or classes in this
150 * method, these classes are not guaranteed to be included in
151 * the generated script. Use {@link #addClasses} to include
154 * @param exported names of classes and packages to treat as exported
155 * @return new instances of the Bck2Brwsr compiler which inherits
156 * all values from <code>this</code> except list of exported classes
158 public Bck2Brwsr addExported(String... exported) {
159 return new Bck2Brwsr(
160 level, this.exported.addAndNew(exported),
161 classes, resources, res, extension, classpath, flow
165 /** Adds additional classes
166 * to the list of those that should be included in the generated
168 * These classes are guaranteed to be available in the
169 * generated virtual machine code accessible using their fully
170 * qualified name. This brings the same behavior as if the
171 * classes were added by {@link #addClasses(java.lang.String...) } and
172 * exported via {@link #addExported(java.lang.String...)}.
174 * @param classes the classes to add to the compilation
175 * @return new instance of the Bck2Brwsr compiler which inherits
176 * all values from <code>this</code>
178 public Bck2Brwsr addRootClasses(String... classes) {
179 if (classes.length == 0) {
182 return addExported(classes).addClasses(classes);
185 /** Adds additional classes
186 * to the list of those that should be included in the generated
187 * JavaScript file. These classes are guaranteed to be present,
188 * but they may not be accessible through their fully qualified
191 * @param classes the classes to add to the compilation
192 * @return new instance of the Bck2Brwsr compiler which inherits
193 * all values from <code>this</code>
196 public Bck2Brwsr addClasses(String... classes) {
197 if (classes.length == 0) {
200 return new Bck2Brwsr(level, exported,
201 this.classes.addAndNew(classes), resources, res,
202 extension, classpath, flow);
206 /** These resources should be made available in the compiled file in
207 * binary form. These resources can then be loaded
208 * by {@link ClassLoader#getResource(java.lang.String)} and similar
211 * @param resources names of the resources to be loaded by {@link Resources#get(java.lang.String)}
212 * @return new instance of the Bck2Brwsr compiler which inherits
213 * all values from <code>this</code> just adds few more resource names
217 public Bck2Brwsr addResources(String... resources) {
218 if (resources.length == 0) {
221 return new Bck2Brwsr(level, exported, this.classes,
222 this.resources.addAndNew(resources), res, extension, classpath, flow
227 /** Changes the obfuscation level for the compiler by creating new instance
228 * which inherits all values from <code>this</code> and adjust the level
231 * @param level the new level of obfuscation
232 * @return new instance of the compiler with changed level of obfuscation
235 public Bck2Brwsr obfuscation(ObfuscationLevel level) {
236 return new Bck2Brwsr(level, exported, classes, resources, res, extension, classpath, flow);
239 /** A way to change the provider of additional resources (classes) for the
242 * @param res the implementation of resources provider
243 * @return new instance of the compiler with all values remaining the same, just
244 * with different resources provider
247 public Bck2Brwsr resources(Resources res) {
248 return new Bck2Brwsr(
249 level, exported, classes, resources,
250 res, extension, classpath, flow
254 /** Should one generate a library? By default the system generates
255 * all transitive classes needed by the the transitive closure of
256 * {@link #addRootClasses(java.lang.String...)} and {@link #addClasses(java.lang.String...)}.
257 * By turning on the library mode, only classes explicitly listed
258 * will be included in the archive. The others will be referenced
261 * A library archive may specify its <em>classpath</em> - e.g. link to
262 * other libraries that should also be included in the application.
263 * One can specify the list of libraries as vararg to this method.
264 * These are relative URL with respect to location of this library.
265 * The runtime system then prefers seek for ".js" suffix of the library
266 * and only then seeks for the classical ".jar" path.
268 * @param classpath the array of JARs that are referenced by this library -
269 * by default gets turned into
270 * @return new instance of the compiler with library flag changed
273 public Bck2Brwsr library(String... classpath) {
274 return new Bck2Brwsr(
275 level, exported, classes,
276 resources, res, true,
277 StringArray.asList(classpath), flow
281 /** Turns on the standalone mode. E.g. does the opposite of
282 * calling {@link #library(java.lang.String...)},
283 * but also allows to specify whether the <em>Bck2Brwsr VM</em> should
284 * be included at all. If not, only the skeleton of the launcher is
285 * generated without any additional VM classes referenced.
287 * @param includeVM should the VM be compiled in, or left out
288 * @return new instance of the compiler with standalone mode on
291 public Bck2Brwsr standalone(boolean includeVM) {
292 return new Bck2Brwsr(
293 level, exported, classes, resources,
294 res, includeVM ? false : null, null, flow
298 /** A way to change the provider of additional resources (classes) for the
299 * compiler by specifying classloader to use for loading them.
301 * @param loader class loader to load the resources from
302 * @return new instance of the compiler with all values being the same, just
303 * different resources provider
306 public Bck2Brwsr resources(final ClassLoader loader) {
307 return resources(loader, false);
310 /** A way to change the provider of additional resources (classes) for the
311 * compiler by specifying classloader to use for loading them.
313 * @param loader class loader to load the resources from
314 * @param ignoreBootClassPath <code>true</code> if classes loaded
315 * from <code>rt.jar</code>
316 * @return new instance of the compiler with all values being the same, just
317 * different resources provider
320 public Bck2Brwsr resources(final ClassLoader loader, boolean ignoreBootClassPath) {
321 return resources(new LdrRsrcs(loader, ignoreBootClassPath));
324 /** A way to register flow analyzer. Such analyzer can optimize the
325 * representation of cycles inside of method bodies.
327 * @param flow the analyzer to be consulted with each method body
328 * @return new instance of the compiler with all values being the same, just
329 * different flow analyzer
332 public Bck2Brwsr flowAnalyzer(Flow.Analyzer flow) {
333 return new Bck2Brwsr(
334 level, exported, classes, resources, res,
335 extension, classpath, flow
339 /** Generates virtual machine based on previous configuration of the
342 * @param out the output to write the generated JavaScript to
343 * @throws IOException I/O exception can be thrown when something goes wrong
346 public void generate(Appendable out) throws IOException {
347 if (level != ObfuscationLevel.NONE) {
349 ClosureWrapper.produceTo(out, level, this);
351 } catch (IOException ex) {
353 } catch (Throwable ex) {
354 out.append("/* Failed to obfuscate: " + ex.getMessage()
359 VM.compile(out, this);
366 Resources getResources() {
367 return res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader(), false);
370 StringArray allResources() {
374 StringArray classes() {
378 StringArray exported() {
382 boolean isExtension() {
383 return Boolean.TRUE.equals(extension);
386 boolean includeVM() {
387 return extension != null;
390 StringArray classpath() {
394 Flow.Analyzer flow() {
398 /** Provider of resources (classes and other files). The
399 * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[])
400 * generator method} will call back here for all classes needed during
401 * translation to JavaScript.
403 public interface Resources {
404 /** Loads given resource (class or other file like image). The
405 * resource name to load bytes for the {@link String} class
406 * would be <code>"java/lang/String.class"</code>.
408 * @param resource path to resource to load
409 * @return the input stream for the resource
410 * @throws IOException can be thrown if the loading fails on some error
411 * or the file cannot be found
413 public InputStream get(String resource) throws IOException;
416 /** Represents control flow inside single method.
417 * Passed into {@link Analyzer#analyze(byte[], org.apidesign.vm4brwsr.Bck2Brwsr.Flow)}
418 * method that can be registed via {@link Bck2Brwsr#flowAnalyzer(org.apidesign.vm4brwsr.Bck2Brwsr.Flow.Analyzer)}
423 public static final class Flow {
424 private final MethodData m;
429 /** Access to bytecode of the method to analyse.
431 * @return unmodifiable bytecode of the instructions in the method body
433 public byte[] getMethodByteCode() {
437 /** Name of the method that is being processed.
438 * @return simple method name
440 public String getMethodName() {
444 public void registerCycle(int offset) {
447 public void registerIf(int offset) {
450 /** Provider of advanced analysis of the code flow inside of
451 * method bodies. Register via {@link Bck2Brwsr#flowAnalyzer(org.apidesign.vm4brwsr.Bck2Brwsr.Flow.Analyzer)}
452 * when constructing the {@link Bck2Brwsr#newCompiler() compiler}.
456 public interface Analyzer {
457 /** Called to analyze method bodies and offer better control flow.
460 * @param request flow computation request and also a
461 * callback interface with methods to define the flow
462 * @return <code>true</code> if the analysis was successful,
463 * <code>false</code> otherwise
465 public boolean analyze(Flow request);