2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 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 java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
26 import org.apidesign.bck2brwsr.core.JavaScriptBody;
27 import sun.tools.javap.AnnotationParser;
28 import sun.tools.javap.ClassData;
29 import sun.tools.javap.FieldData;
30 import sun.tools.javap.MethodData;
31 import static sun.tools.javap.RuntimeConstants.*;
33 /** Translator of the code inside class files to JavaScript.
35 * @author Jaroslav Tulach <jtulach@netbeans.org>
37 public final class ByteCodeToJavaScript {
38 private final ClassData jc;
39 private final Appendable out;
40 private final Collection<? super String> references;
42 private ByteCodeToJavaScript(
43 ClassData jc, Appendable out, Collection<? super String> references
47 this.references = references;
51 * Converts a given class file to a JavaScript version.
53 * @param classFile input stream with code of the .class file
54 * @param out a {@link StringBuilder} or similar to generate the output to
55 * @param references a write only collection where the system adds list of
56 * other classes that were referenced and should be loaded in order the
57 * generated JavaScript code works properly. The names are in internal
58 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
59 * if one is not interested in knowing references
60 * @param scripts write only collection with names of resources to read
61 * @return the initialization code for this class, if any. Otherwise <code>null</code>
63 * @throws IOException if something goes wrong during read or write or translating
66 public static String compile(
67 InputStream classFile, Appendable out,
68 Collection<? super String> references,
69 Collection<? super String> scripts
70 ) throws IOException {
71 ClassData jc = new ClassData(classFile);
72 byte[] arrData = jc.findAnnotationData(true);
73 String[] arr = findAnnotation(arrData, jc, ExtraJavaScript.class.getName(), "resource", "processByteCode");
76 if ("0".equals(arr[1])) {
80 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
83 List<String> toInitilize = new ArrayList<String>();
84 for (MethodData m : jc.getMethods()) {
86 compiler.generateStaticMethod(m, toInitilize);
88 compiler.generateInstanceMethod(m);
91 for (FieldData v : jc.getFields()) {
93 compiler.generateStaticField(v);
97 final String className = className(jc);
98 out.append("\nfunction ").append(className);
100 for (FieldData v : jc.getFields()) {
102 out.append("\n this.fld_").
103 append(v.getName()).append(" = 0;");
106 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
107 out.append("\n if (").append(className).
108 append(".prototype.$instOf_").append(className).append(") {");
109 out.append("\n return new ").append(className).append(";");
111 // ClassName sc = jc.getSuperClass();
112 String sc = jc.getSuperClassName(); // with _
114 out.append("\n var p = ").append(className)
115 .append(".prototype = ").
116 append(sc.replace('/', '_')).append("_proto();");
118 out.append("\n var p = ").append(className).append(".prototype;");
120 for (MethodData m : jc.getMethods()) {
121 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
122 compiler.generateMethodReference("\n p.", m);
125 out.append("\n p.$instOf_").append(className).append(" = true;");
126 for (String superInterface : jc.getSuperInterfaces()) {
127 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
129 out.append("\n return new ").append(className).append(";");
131 out.append("\n").append(className).append("_proto();");
132 StringBuilder sb = new StringBuilder();
133 for (String init : toInitilize) {
134 sb.append("\n").append(init).append("();");
136 return sb.toString();
138 private void generateStaticMethod(MethodData m, List<String> toInitilize) throws IOException {
139 if (javaScriptBody(m, true)) {
142 int[] argsCnt = { -1 };
143 final String mn = findMethodName(m, argsCnt);
144 out.append("\nfunction ").append(
146 ).append('_').append(mn);
147 if (mn.equals("classV")) {
148 toInitilize.add(className(jc) + '_' + mn);
152 for (int index = 0, i = 0; i < argsCnt[0]; i++) {
154 out.append("arg").append(String.valueOf(index));
156 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
157 if ("D".equals(desc) || "J".equals(desc)) {
163 out.append(") {").append("\n");
164 final byte[] code = m.getCode();
166 int len = m.getMaxLocals();
167 for (int index = argsCnt[0], i = argsCnt[0]; i < len; i++) {
169 out.append("arg").append(String.valueOf(i)).append(";\n");
171 out.append(" var stack = new Array();\n");
174 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
179 private void generateMethodReference(String prefix, MethodData m) throws IOException {
180 final String name = findMethodName(m, null);
181 out.append(prefix).append(name).append(" = ")
182 .append(className(jc))
183 .append('_').append(name).append(";");
186 private void generateInstanceMethod(MethodData m) throws IOException {
187 if (javaScriptBody(m, false)) {
190 int[] argsCnt = { -1 };
191 out.append("\nfunction ").append(
193 ).append('_').append(findMethodName(m, argsCnt));
196 for (int index = 1, i = 0; i < argsCnt[0]; i++) {
198 out.append("arg").append(String.valueOf(index));
199 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
200 if ("D".equals(desc) || "J".equals(desc)) {
206 out.append(") {").append("\n");
207 final byte[] code = m.getCode();
209 int len = m.getMaxLocals();
210 for (int index = argsCnt[0], i = argsCnt[0]; i < len; i++) {
212 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
214 out.append(";\n var stack = new Array();\n");
217 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
222 private void produceCode(byte[] byteCodes) throws IOException {
223 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
224 for (int i = 0; i < byteCodes.length; i++) {
226 out.append(" case " + i).append(": ");
227 final int c = readByte(byteCodes, i);
234 out.append("stack.push(arg0);");
241 out.append("stack.push(arg1);");
248 out.append("stack.push(arg2);");
255 out.append("stack.push(arg3);");
262 final int indx = readByte(byteCodes, ++i);
263 out.append("stack.push(arg").append(indx + ");");
271 final int indx = readByte(byteCodes, ++i);
272 out.append("arg" + indx).append(" = stack.pop();");
280 out.append("arg0 = stack.pop();");
287 out.append("arg1 = stack.pop();");
294 out.append("arg2 = stack.pop();");
301 out.append("arg3 = stack.pop();");
307 out.append("stack.push(stack.pop() + stack.pop());");
313 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
319 out.append("stack.push(stack.pop() * stack.pop());");
323 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
327 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
331 out.append("stack.push(stack.pop() & stack.pop());");
335 out.append("stack.push(stack.pop() | stack.pop());");
339 out.append("stack.push(stack.pop() ^ stack.pop());");
345 out.append("stack.push(- stack.pop());");
349 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
353 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
357 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
360 final int varIndx = readByte(byteCodes, ++i);
361 final int incrBy = byteCodes[++i];
363 out.append("arg" + varIndx).append("++;");
365 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
370 out.append("return;");
377 out.append("return stack.pop();");
388 out.append("/* number conversion */");
394 out.append("stack.push(Math.floor(stack.pop()));");
399 out.append("/* number conversion */");
401 case opc_aconst_null:
402 out.append("stack.push(null);");
405 out.append("stack.push(-1);");
411 out.append("stack.push(0);");
417 out.append("stack.push(1);");
421 out.append("stack.push(2);");
424 out.append("stack.push(3);");
427 out.append("stack.push(4);");
430 out.append("stack.push(5);");
433 int indx = readByte(byteCodes, ++i);
434 String v = encodeConstant(indx);
435 out.append("stack.push(").append(v).append(");");
440 int indx = readIntArg(byteCodes, i);
442 String v = encodeConstant(indx);
443 out.append("stack.push(").append(v).append(");");
451 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
455 i = generateIf(byteCodes, i, "===");
458 i = generateIf(byteCodes, i, "!=");
460 case opc_if_icmpeq: {
461 i = generateIf(byteCodes, i, "==");
465 int indx = i + readIntArg(byteCodes, i);
466 out.append("if (stack.pop() == 0) { gt = " + indx);
467 out.append("; continue; }");
472 int indx = i + readIntArg(byteCodes, i);
473 out.append("if (stack.pop() != 0) { gt = " + indx);
474 out.append("; continue; }");
479 int indx = i + readIntArg(byteCodes, i);
480 out.append("if (stack.pop() < 0) { gt = " + indx);
481 out.append("; continue; }");
486 int indx = i + readIntArg(byteCodes, i);
487 out.append("if (stack.pop() <= 0) { gt = " + indx);
488 out.append("; continue; }");
493 int indx = i + readIntArg(byteCodes, i);
494 out.append("if (stack.pop() > 0) { gt = " + indx);
495 out.append("; continue; }");
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (stack.pop() >= 0) { gt = " + indx);
502 out.append("; continue; }");
506 case opc_ifnonnull: {
507 int indx = i + readIntArg(byteCodes, i);
508 out.append("if (stack.pop()) { gt = " + indx);
509 out.append("; continue; }");
514 int indx = i + readIntArg(byteCodes, i);
515 out.append("if (!stack.pop()) { gt = " + indx);
516 out.append("; continue; }");
521 i = generateIf(byteCodes, i, "!=");
524 i = generateIf(byteCodes, i, ">");
527 i = generateIf(byteCodes, i, ">=");
530 i = generateIf(byteCodes, i, "<");
533 i = generateIf(byteCodes, i, "<=");
536 int indx = i + readIntArg(byteCodes, i);
537 out.append("gt = " + indx).append("; continue;");
541 case opc_lookupswitch: {
542 int table = i / 4 * 4 + 4;
543 int dflt = i + readInt4(byteCodes, table);
545 int n = readInt4(byteCodes, table);
547 out.append("switch (stack.pop()) {\n");
549 int cnstnt = readInt4(byteCodes, table);
551 int offset = i + readInt4(byteCodes, table);
553 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
555 out.append(" default: gt = " + dflt).append("; continue;\n}");
559 case opc_tableswitch: {
560 int table = i / 4 * 4 + 4;
561 int dflt = i + readInt4(byteCodes, table);
563 int low = readInt4(byteCodes, table);
565 int high = readInt4(byteCodes, table);
567 out.append("switch (stack.pop()) {\n");
568 while (low <= high) {
569 int offset = i + readInt4(byteCodes, table);
571 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
574 out.append(" default: gt = " + dflt).append("; continue;\n}");
578 case opc_invokeinterface: {
579 i = invokeVirtualMethod(byteCodes, i) + 2;
582 case opc_invokevirtual:
583 i = invokeVirtualMethod(byteCodes, i);
585 case opc_invokespecial:
586 i = invokeStaticMethod(byteCodes, i, false);
588 case opc_invokestatic:
589 i = invokeStaticMethod(byteCodes, i, true);
592 int indx = readIntArg(byteCodes, i);
593 String ci = jc.getClassName(indx);
594 out.append("stack.push(");
595 out.append("new ").append(ci.replace('/','_'));
602 int type = byteCodes[i++];
603 out.append("stack.push(new Array(stack.pop()));");
606 case opc_anewarray: {
607 i += 2; // skip type of array
608 out.append("stack.push(new Array(stack.pop()));");
611 case opc_multianewarray: {
613 int dim = readByte(byteCodes, ++i);
614 out.append("{ var a0 = new Array(stack.pop());");
615 for (int d = 1; d < dim; d++) {
616 out.append("\n var l" + d).append(" = stack.pop();");
617 out.append("\n for (var i" + d).append (" = 0; i" + d).
618 append(" < a" + (d - 1)).
619 append(".length; i" + d).append("++) {");
620 out.append("\n var a" + d).
621 append (" = new Array(l" + d).append(");");
622 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
625 for (int d = 1; d < dim; d++) {
628 out.append("\nstack.push(a0); }");
631 case opc_arraylength:
632 out.append("stack.push(stack.pop().length);");
642 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
653 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
657 out.append("stack.pop();");
659 out.append("stack.pop();");
662 out.append("stack.push(stack[stack.length - 1]);");
665 out.append("stack.push(" + byteCodes[++i] + ");");
668 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
672 int indx = readIntArg(byteCodes, i);
673 String[] fi = jc.getFieldInfoName(indx);
674 out.append("stack.push(stack.pop().fld_").
675 append(fi[1]).append(");");
679 case opc_getstatic: {
680 int indx = readIntArg(byteCodes, i);
681 String[] fi = jc.getFieldInfoName(indx);
682 out.append("stack.push(").append(fi[0].replace('/', '_'));
683 out.append('_').append(fi[1]).append(");");
688 case opc_putstatic: {
689 int indx = readIntArg(byteCodes, i);
690 String[] fi = jc.getFieldInfoName(indx);
691 out.append(fi[0].replace('/', '_'));
692 out.append('_').append(fi[1]).append(" = stack.pop();");
698 int indx = readIntArg(byteCodes, i);
699 String[] fi = jc.getFieldInfoName(indx);
700 out.append("{ var v = stack.pop(); stack.pop().fld_")
701 .append(fi[1]).append(" = v; }");
705 case opc_checkcast: {
706 int indx = readIntArg(byteCodes, i);
707 final String type = jc.getClassName(indx);
708 if (!type.startsWith("[")) {
709 // no way to check arrays right now
710 out.append("if(stack[stack.length - 1].$instOf_")
711 .append(type.replace('/', '_'))
712 .append(" != 1) throw {};"); // XXX proper exception
717 case opc_instanceof: {
718 int indx = readIntArg(byteCodes, i);
719 final String type = jc.getClassName(indx);
720 out.append("stack.push(stack.pop().$instOf_")
721 .append(type.replace('/', '_'))
722 .append(" ? 1 : 0);");
727 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
731 out.append("throw 'unknown bytecode " + c + "';");
736 for (int j = prev; j <= i; j++) {
738 final int cc = readByte(byteCodes, j);
739 out.append(Integer.toString(cc));
746 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
747 int indx = i + readIntArg(byteCodes, i);
748 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
749 out.append("; continue; }");
753 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
754 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
755 final int indxLo = byteCodes[offsetInstruction + 2];
756 return (indxHi & 0xffffff00) | (indxLo & 0xff);
758 private int readInt4(byte[] byteCodes, int offsetInstruction) {
759 final int d = byteCodes[offsetInstruction + 0] << 24;
760 final int c = byteCodes[offsetInstruction + 1] << 16;
761 final int b = byteCodes[offsetInstruction + 2] << 8;
762 final int a = byteCodes[offsetInstruction + 3];
763 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
765 private int readByte(byte[] byteCodes, int offsetInstruction) {
766 return (byteCodes[offsetInstruction] + 256) % 256;
769 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
772 Boolean count = null;
773 boolean array = false;
774 int firstPos = sig.length();
775 while (i < descriptor.length()) {
776 char ch = descriptor.charAt(i++);
802 hasReturnType[0] = true;
803 sig.insert(firstPos, ch);
805 sig.insert(firstPos, 'A');
812 hasReturnType[0] = false;
813 sig.insert(firstPos, 'V');
816 int next = descriptor.indexOf(';', i);
823 sig.append(descriptor.substring(i, next).replace('/', '_'));
825 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
826 sig.insert(firstPos, ch);
828 sig.insert(firstPos, 'A');
830 hasReturnType[0] = true;
838 break; // invalid character
844 private void generateStaticField(FieldData v) throws IOException {
846 .append(className(jc))
847 .append('_').append(v.getName()).append(" = 0;");
850 private String findMethodName(MethodData m, int[] cnt) {
851 StringBuilder name = new StringBuilder();
852 if ("<init>".equals(m.getName())) { // NOI18N
853 name.append("cons"); // NOI18N
854 } else if ("<clinit>".equals(m.getName())) { // NOI18N
855 name.append("class"); // NOI18N
857 name.append(m.getName());
860 boolean hasReturn[] = { false };
861 int argsCnt = countArgs(findDescriptor(m.getInternalSig()), hasReturn, name);
865 return name.toString();
868 private String findMethodName(String[] mi, int[] cnt, boolean[] hasReturn) {
869 StringBuilder name = new StringBuilder();
870 String descr = mi[2];//mi.getDescriptor();
872 if ("<init>".equals(nm)) { // NOI18N
873 name.append("cons"); // NOI18N
877 cnt[0] = countArgs(findDescriptor(descr), hasReturn, name);
878 return name.toString();
881 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
883 int methodIndex = readIntArg(byteCodes, i);
884 String[] mi = jc.getFieldInfoName(methodIndex);
885 boolean[] hasReturn = { false };
887 String mn = findMethodName(mi, cnt, hasReturn);
889 for (int j = cnt[0] - 1; j >= 0; j--) {
890 out.append("var v" + j).append(" = stack.pop(); ");
894 out.append("stack.push(");
896 final String in = mi[0];
897 out.append(in.replace('/', '_'));
899 out.append(".prototype.");
907 out.append("stack.pop()");
910 for (int j = 0; j < cnt[0]; j++) {
924 private int invokeVirtualMethod(byte[] byteCodes, int i)
926 int methodIndex = readIntArg(byteCodes, i);
927 String[] mi = jc.getFieldInfoName(methodIndex);
928 boolean[] hasReturn = { false };
930 String mn = findMethodName(mi, cnt, hasReturn);
932 for (int j = cnt[0] - 1; j >= 0; j--) {
933 out.append("var v" + j).append(" = stack.pop(); ");
935 out.append("var self = stack.pop(); ");
937 out.append("stack.push(");
943 for (int j = 0; j < cnt[0]; j++) {
956 private void addReference(String cn) throws IOException {
957 if (references != null) {
958 if (references.add(cn)) {
959 out.append(" /* needs ").append(cn).append(" */");
964 private void outType(String d, StringBuilder out) {
966 while (d.charAt(0) == '[') {
970 if (d.charAt(0) == 'L') {
971 assert d.charAt(d.length() - 1) == ';';
972 out.append(d.replace('/', '_').substring(0, d.length() - 1));
978 private String encodeConstant(int entryIndex) {
979 String s = jc.stringValue(entryIndex, true);
983 private String findDescriptor(String d) {
984 return d.replace('[', 'A');
987 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
988 byte[] arr = m.findAnnotationData(true);
992 final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
993 class P extends AnnotationParser {
995 String[] args = new String[30];
999 protected void visitAttr(String type, String attr, String value) {
1000 if (type.equals(jvmType)) {
1001 if ("body".equals(attr)) {
1003 } else if ("args".equals(attr)) {
1004 args[cnt++] = value;
1006 throw new IllegalArgumentException(attr);
1013 if (p.body == null) {
1016 int argsCnt[] = { -1 };
1017 out.append("\nfunction ").append(className(jc)).append('_').
1018 append(findMethodName(m, argsCnt));
1023 out.append(p.args[0]);
1030 for (int i = 0; i < argsCnt[0]; i++) {
1032 out.append(p.args[index]);
1036 out.append(") {").append("\n");
1038 out.append("\n}\n");
1041 private static String className(ClassData jc) {
1042 //return jc.getName().getInternalName().replace('/', '_');
1043 return jc.getClassName().replace('/', '_');
1046 private static String[] findAnnotation(
1047 byte[] arr, ClassData cd, final String className,
1048 final String... attrNames
1049 ) throws IOException {
1053 final String[] values = new String[attrNames.length];
1054 final boolean[] found = { false };
1055 final String jvmType = "L" + className.replace('.', '/') + ";";
1056 AnnotationParser ap = new AnnotationParser() {
1058 protected void visitAttr(String type, String attr, String value) {
1059 if (type.equals(jvmType)) {
1061 for (int i = 0; i < attrNames.length; i++) {
1062 if (attrNames[i].equals(attr)) {
1071 return found[0] ? values : null;