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 StringBuilder argsCnt = new StringBuilder();
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.length(); i++) {
154 out.append("arg").append(String.valueOf(index));
156 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
157 if (argsCnt.charAt(i) == '1') {
163 out.append(") {").append("\n");
164 final byte[] code = m.getCode();
166 int len = m.getMaxLocals();
167 for (int index = argsCnt.length(), i = argsCnt.length(); 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, new StringBuilder());
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 StringBuilder argsCnt = new StringBuilder();
191 out.append("\nfunction ").append(
193 ).append('_').append(findMethodName(m, argsCnt));
196 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
198 out.append("arg").append(String.valueOf(index));
199 if (argsCnt.charAt(i) == '1') {
205 out.append(") {").append("\n");
206 final byte[] code = m.getCode();
208 int len = m.getMaxLocals();
209 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
211 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
213 out.append(";\n var stack = new Array();\n");
216 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
221 private void produceCode(byte[] byteCodes) throws IOException {
222 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
223 for (int i = 0; i < byteCodes.length; i++) {
225 out.append(" case " + i).append(": ");
226 final int c = readByte(byteCodes, i);
233 out.append("stack.push(arg0);");
240 out.append("stack.push(arg1);");
247 out.append("stack.push(arg2);");
254 out.append("stack.push(arg3);");
261 final int indx = readByte(byteCodes, ++i);
262 out.append("stack.push(arg").append(indx + ");");
270 final int indx = readByte(byteCodes, ++i);
271 out.append("arg" + indx).append(" = stack.pop();");
279 out.append("arg0 = stack.pop();");
286 out.append("arg1 = stack.pop();");
293 out.append("arg2 = stack.pop();");
300 out.append("arg3 = stack.pop();");
306 out.append("stack.push(stack.pop() + stack.pop());");
312 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
318 out.append("stack.push(stack.pop() * stack.pop());");
322 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
326 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
330 out.append("stack.push(stack.pop() & stack.pop());");
334 out.append("stack.push(stack.pop() | stack.pop());");
338 out.append("stack.push(stack.pop() ^ stack.pop());");
344 out.append("stack.push(- stack.pop());");
348 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
352 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
356 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
359 final int varIndx = readByte(byteCodes, ++i);
360 final int incrBy = byteCodes[++i];
362 out.append("arg" + varIndx).append("++;");
364 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
369 out.append("return;");
376 out.append("return stack.pop();");
387 out.append("/* number conversion */");
393 out.append("stack.push(Math.floor(stack.pop()));");
398 out.append("/* number conversion */");
400 case opc_aconst_null:
401 out.append("stack.push(null);");
404 out.append("stack.push(-1);");
410 out.append("stack.push(0);");
416 out.append("stack.push(1);");
420 out.append("stack.push(2);");
423 out.append("stack.push(3);");
426 out.append("stack.push(4);");
429 out.append("stack.push(5);");
432 int indx = readByte(byteCodes, ++i);
433 String v = encodeConstant(indx);
434 out.append("stack.push(").append(v).append(");");
439 int indx = readIntArg(byteCodes, i);
441 String v = encodeConstant(indx);
442 out.append("stack.push(").append(v).append(");");
450 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
454 i = generateIf(byteCodes, i, "===");
457 i = generateIf(byteCodes, i, "!=");
459 case opc_if_icmpeq: {
460 i = generateIf(byteCodes, i, "==");
464 int indx = i + readIntArg(byteCodes, i);
465 out.append("if (stack.pop() == 0) { gt = " + indx);
466 out.append("; continue; }");
471 int indx = i + readIntArg(byteCodes, i);
472 out.append("if (stack.pop() != 0) { gt = " + indx);
473 out.append("; continue; }");
478 int indx = i + readIntArg(byteCodes, i);
479 out.append("if (stack.pop() < 0) { gt = " + indx);
480 out.append("; continue; }");
485 int indx = i + readIntArg(byteCodes, i);
486 out.append("if (stack.pop() <= 0) { gt = " + indx);
487 out.append("; continue; }");
492 int indx = i + readIntArg(byteCodes, i);
493 out.append("if (stack.pop() > 0) { gt = " + indx);
494 out.append("; continue; }");
499 int indx = i + readIntArg(byteCodes, i);
500 out.append("if (stack.pop() >= 0) { gt = " + indx);
501 out.append("; continue; }");
505 case opc_ifnonnull: {
506 int indx = i + readIntArg(byteCodes, i);
507 out.append("if (stack.pop()) { gt = " + indx);
508 out.append("; continue; }");
513 int indx = i + readIntArg(byteCodes, i);
514 out.append("if (!stack.pop()) { gt = " + indx);
515 out.append("; continue; }");
520 i = generateIf(byteCodes, i, "!=");
523 i = generateIf(byteCodes, i, ">");
526 i = generateIf(byteCodes, i, ">=");
529 i = generateIf(byteCodes, i, "<");
532 i = generateIf(byteCodes, i, "<=");
535 int indx = i + readIntArg(byteCodes, i);
536 out.append("gt = " + indx).append("; continue;");
540 case opc_lookupswitch: {
541 int table = i / 4 * 4 + 4;
542 int dflt = i + readInt4(byteCodes, table);
544 int n = readInt4(byteCodes, table);
546 out.append("switch (stack.pop()) {\n");
548 int cnstnt = readInt4(byteCodes, table);
550 int offset = i + readInt4(byteCodes, table);
552 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
554 out.append(" default: gt = " + dflt).append("; continue;\n}");
558 case opc_tableswitch: {
559 int table = i / 4 * 4 + 4;
560 int dflt = i + readInt4(byteCodes, table);
562 int low = readInt4(byteCodes, table);
564 int high = readInt4(byteCodes, table);
566 out.append("switch (stack.pop()) {\n");
567 while (low <= high) {
568 int offset = i + readInt4(byteCodes, table);
570 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
573 out.append(" default: gt = " + dflt).append("; continue;\n}");
577 case opc_invokeinterface: {
578 i = invokeVirtualMethod(byteCodes, i) + 2;
581 case opc_invokevirtual:
582 i = invokeVirtualMethod(byteCodes, i);
584 case opc_invokespecial:
585 i = invokeStaticMethod(byteCodes, i, false);
587 case opc_invokestatic:
588 i = invokeStaticMethod(byteCodes, i, true);
591 int indx = readIntArg(byteCodes, i);
592 String ci = jc.getClassName(indx);
593 out.append("stack.push(");
594 out.append("new ").append(ci.replace('/','_'));
601 int type = byteCodes[i++];
602 out.append("stack.push(new Array(stack.pop()));");
605 case opc_anewarray: {
606 i += 2; // skip type of array
607 out.append("stack.push(new Array(stack.pop()));");
610 case opc_multianewarray: {
612 int dim = readByte(byteCodes, ++i);
613 out.append("{ var a0 = new Array(stack.pop());");
614 for (int d = 1; d < dim; d++) {
615 out.append("\n var l" + d).append(" = stack.pop();");
616 out.append("\n for (var i" + d).append (" = 0; i" + d).
617 append(" < a" + (d - 1)).
618 append(".length; i" + d).append("++) {");
619 out.append("\n var a" + d).
620 append (" = new Array(l" + d).append(");");
621 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
624 for (int d = 1; d < dim; d++) {
627 out.append("\nstack.push(a0); }");
630 case opc_arraylength:
631 out.append("stack.push(stack.pop().length);");
641 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
652 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
656 out.append("stack.pop();");
658 out.append("stack.pop();");
661 out.append("stack.push(stack[stack.length - 1]);");
664 out.append("stack.push(" + byteCodes[++i] + ");");
667 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
671 int indx = readIntArg(byteCodes, i);
672 String[] fi = jc.getFieldInfoName(indx);
673 out.append("stack.push(stack.pop().fld_").
674 append(fi[1]).append(");");
678 case opc_getstatic: {
679 int indx = readIntArg(byteCodes, i);
680 String[] fi = jc.getFieldInfoName(indx);
681 out.append("stack.push(").append(fi[0].replace('/', '_'));
682 out.append('_').append(fi[1]).append(");");
687 case opc_putstatic: {
688 int indx = readIntArg(byteCodes, i);
689 String[] fi = jc.getFieldInfoName(indx);
690 out.append(fi[0].replace('/', '_'));
691 out.append('_').append(fi[1]).append(" = stack.pop();");
697 int indx = readIntArg(byteCodes, i);
698 String[] fi = jc.getFieldInfoName(indx);
699 out.append("{ var v = stack.pop(); stack.pop().fld_")
700 .append(fi[1]).append(" = v; }");
704 case opc_checkcast: {
705 int indx = readIntArg(byteCodes, i);
706 final String type = jc.getClassName(indx);
707 if (!type.startsWith("[")) {
708 // no way to check arrays right now
709 out.append("if(stack[stack.length - 1].$instOf_")
710 .append(type.replace('/', '_'))
711 .append(" != 1) throw {};"); // XXX proper exception
716 case opc_instanceof: {
717 int indx = readIntArg(byteCodes, i);
718 final String type = jc.getClassName(indx);
719 out.append("stack.push(stack.pop().$instOf_")
720 .append(type.replace('/', '_'))
721 .append(" ? 1 : 0);");
726 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
730 out.append("throw 'unknown bytecode " + c + "';");
735 for (int j = prev; j <= i; j++) {
737 final int cc = readByte(byteCodes, j);
738 out.append(Integer.toString(cc));
745 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
746 int indx = i + readIntArg(byteCodes, i);
747 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
748 out.append("; continue; }");
752 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
753 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
754 final int indxLo = byteCodes[offsetInstruction + 2];
755 return (indxHi & 0xffffff00) | (indxLo & 0xff);
757 private int readInt4(byte[] byteCodes, int offsetInstruction) {
758 final int d = byteCodes[offsetInstruction + 0] << 24;
759 final int c = byteCodes[offsetInstruction + 1] << 16;
760 final int b = byteCodes[offsetInstruction + 2] << 8;
761 final int a = byteCodes[offsetInstruction + 3];
762 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
764 private int readByte(byte[] byteCodes, int offsetInstruction) {
765 return (byteCodes[offsetInstruction] + 256) % 256;
768 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
770 Boolean count = null;
771 boolean array = false;
772 int firstPos = sig.length();
773 while (i < descriptor.length()) {
774 char ch = descriptor.charAt(i++);
798 if (ch == 'J' || ch == 'D') {
804 hasReturnType[0] = true;
805 sig.insert(firstPos, ch);
807 sig.insert(firstPos, 'A');
814 hasReturnType[0] = false;
815 sig.insert(firstPos, 'V');
818 int next = descriptor.indexOf(';', i);
824 sig.append(descriptor.substring(i, next).replace('/', '_'));
827 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
828 sig.insert(firstPos, ch);
830 sig.insert(firstPos, 'A');
832 hasReturnType[0] = true;
840 break; // invalid character
845 private void generateStaticField(FieldData v) throws IOException {
847 .append(className(jc))
848 .append('_').append(v.getName()).append(" = 0;");
851 private String findMethodName(MethodData m, StringBuilder cnt) {
852 StringBuilder name = new StringBuilder();
853 if ("<init>".equals(m.getName())) { // NOI18N
854 name.append("cons"); // NOI18N
855 } else if ("<clinit>".equals(m.getName())) { // NOI18N
856 name.append("class"); // NOI18N
858 name.append(m.getName());
861 boolean hasReturn[] = { false };
862 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
863 return name.toString();
866 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
867 StringBuilder name = new StringBuilder();
868 String descr = mi[2];//mi.getDescriptor();
870 if ("<init>".equals(nm)) { // NOI18N
871 name.append("cons"); // NOI18N
875 countArgs(findDescriptor(descr), hasReturn, name, cnt);
876 return name.toString();
879 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
881 int methodIndex = readIntArg(byteCodes, i);
882 String[] mi = jc.getFieldInfoName(methodIndex);
883 boolean[] hasReturn = { false };
884 StringBuilder cnt = new StringBuilder();
885 String mn = findMethodName(mi, cnt, hasReturn);
887 for (int j = cnt.length() - 1; j >= 0; j--) {
888 out.append("var v" + j).append(" = stack.pop(); ");
892 out.append("stack.push(");
894 final String in = mi[0];
895 out.append(in.replace('/', '_'));
897 out.append(".prototype.");
905 out.append("stack.pop()");
908 for (int j = 0; j < cnt.length(); j++) {
922 private int invokeVirtualMethod(byte[] byteCodes, int i)
924 int methodIndex = readIntArg(byteCodes, i);
925 String[] mi = jc.getFieldInfoName(methodIndex);
926 boolean[] hasReturn = { false };
927 StringBuilder cnt = new StringBuilder();
928 String mn = findMethodName(mi, cnt, hasReturn);
930 for (int j = cnt.length() - 1; j >= 0; j--) {
931 out.append("var v" + j).append(" = stack.pop(); ");
933 out.append("var self = stack.pop(); ");
935 out.append("stack.push(");
941 for (int j = 0; j < cnt.length(); j++) {
954 private void addReference(String cn) throws IOException {
955 if (references != null) {
956 if (references.add(cn)) {
957 out.append(" /* needs ").append(cn).append(" */");
962 private void outType(String d, StringBuilder out) {
964 while (d.charAt(0) == '[') {
968 if (d.charAt(0) == 'L') {
969 assert d.charAt(d.length() - 1) == ';';
970 out.append(d.replace('/', '_').substring(0, d.length() - 1));
976 private String encodeConstant(int entryIndex) {
977 String s = jc.stringValue(entryIndex, true);
981 private String findDescriptor(String d) {
982 return d.replace('[', 'A');
985 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
986 byte[] arr = m.findAnnotationData(true);
990 final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
991 class P extends AnnotationParser {
993 String[] args = new String[30];
997 protected void visitAttr(String type, String attr, String value) {
998 if (type.equals(jvmType)) {
999 if ("body".equals(attr)) {
1001 } else if ("args".equals(attr)) {
1002 args[cnt++] = value;
1004 throw new IllegalArgumentException(attr);
1011 if (p.body == null) {
1014 StringBuilder cnt = new StringBuilder();
1015 out.append("\nfunction ").append(className(jc)).append('_').
1016 append(findMethodName(m, cnt));
1021 out.append(p.args[0]);
1028 for (int i = 0; i < cnt.length(); i++) {
1030 out.append(p.args[index]);
1034 out.append(") {").append("\n");
1036 out.append("\n}\n");
1039 private static String className(ClassData jc) {
1040 //return jc.getName().getInternalName().replace('/', '_');
1041 return jc.getClassName().replace('/', '_');
1044 private static String[] findAnnotation(
1045 byte[] arr, ClassData cd, final String className,
1046 final String... attrNames
1047 ) throws IOException {
1051 final String[] values = new String[attrNames.length];
1052 final boolean[] found = { false };
1053 final String jvmType = "L" + className.replace('.', '/') + ";";
1054 AnnotationParser ap = new AnnotationParser() {
1056 protected void visitAttr(String type, String attr, String value) {
1057 if (type.equals(jvmType)) {
1059 for (int i = 0; i < attrNames.length; i++) {
1060 if (attrNames[i].equals(attr)) {
1069 return found[0] ? values : null;