rt/vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Lubomir Nerad <lubomir.nerad@oracle.com>
Thu, 21 Mar 2013 18:48:46 +0100
branchclosure
changeset 869 151f4ccd7673
parent 833 32de22658040
child 1020 a6bacea2518f
child 1344 bb1e59f5cff3
permissions -rw-r--r--
Initial attempt for advanced obfuscation
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    13  *
    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.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 
    23 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    24  *
    25  * @author Jaroslav Tulach <jtulach@netbeans.org>
    26  */
    27 class VM extends ByteCodeToJavaScript {
    28     public VM(Appendable out) {
    29         super(out);
    30     }
    31 
    32     private VM(Appendable out, ObfuscationDelegate obfuscationDelegate) {
    33         super(out, obfuscationDelegate);
    34     }
    35 
    36     static {
    37         // uses VMLazy to load dynamic classes
    38         boolean assertsOn = false;
    39         assert assertsOn = true;
    40         if (assertsOn) {
    41             VMLazy.init();
    42             Zips.init();
    43         }
    44     }
    45 
    46     @Override
    47     boolean debug(String msg) throws IOException {
    48         return false;
    49     }
    50     
    51     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    52         new VM(out).doCompile(l, names);
    53     }
    54 
    55     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names,
    56                         ObfuscationDelegate obfuscationDelegate) throws IOException {
    57         new VM(out, obfuscationDelegate).doCompile(l, names);
    58     }
    59 
    60     protected void doCompile(Bck2Brwsr.Resources l, StringArray names) throws IOException {
    61         out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
    62         StringArray processed = new StringArray();
    63         StringArray initCode = new StringArray();
    64         for (String baseClass : names.toArray()) {
    65             references.add(baseClass);
    66             for (;;) {
    67                 String name = null;
    68                 for (String n : references.toArray()) {
    69                     if (processed.contains(n)) {
    70                         continue;
    71                     }
    72                     name = n;
    73                 }
    74                 if (name == null) {
    75                     break;
    76                 }
    77                 InputStream is = loadClass(l, name);
    78                 if (is == null) {
    79                     throw new IOException("Can't find class " + name); 
    80                 }
    81                 try {
    82                     String ic = compile(is);
    83                     processed.add(name);
    84                     initCode.add(ic == null ? "" : ic);
    85                 } catch (RuntimeException ex) {
    86                     if (out instanceof CharSequence) {
    87                         CharSequence seq = (CharSequence)out;
    88                         int lastBlock = seq.length();
    89                         while (lastBlock-- > 0) {
    90                             if (seq.charAt(lastBlock) == '{') {
    91                                 break;
    92                             }
    93                         }
    94                         throw new IOException("Error while compiling " + name + "\n" 
    95                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    96                         );
    97                     } else {
    98                         throw new IOException("Error while compiling " + name + "\n" 
    99                             + out, ex
   100                         );
   101                     }
   102                 }
   103             }
   104 
   105             for (String resource : scripts.toArray()) {
   106                 while (resource.startsWith("/")) {
   107                     resource = resource.substring(1);
   108                 }
   109                 InputStream emul = l.get(resource);
   110                 if (emul == null) {
   111                     throw new IOException("Can't find " + resource);
   112                 }
   113                 readResource(emul, out);
   114             }
   115             scripts = new StringArray();
   116             
   117             StringArray toInit = StringArray.asList(references.toArray());
   118             toInit.reverse();
   119 
   120             for (String ic : toInit.toArray()) {
   121                 int indx = processed.indexOf(ic);
   122                 if (indx >= 0) {
   123                     final String theCode = initCode.toArray()[indx];
   124                     if (!theCode.isEmpty()) {
   125                         out.append(theCode).append("\n");
   126                     }
   127                     initCode.toArray()[indx] = "";
   128                 }
   129             }
   130         }
   131         out.append(
   132               "  return vm;\n"
   133             + "  };\n"
   134             + "  global.bck2brwsr = function() {\n"
   135             + "    var args = Array.prototype.slice.apply(arguments);\n"
   136             + "    var vm = fillInVMSkeleton({});\n"
   137             + "    var loader = {};\n"
   138             + "    loader.vm = vm;\n"
   139             + "    loader.loadClass = function(name) {\n"
   140             + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   141             + "      var fn = vm[attr];\n"
   142             + "      if (fn) return fn(false);\n"
   143             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   144             + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   145             + "    }\n"
   146             + "    if (vm.loadClass) {\n"
   147             + "      throw 'Cannot initialize the bck2brwsr VM twice!';\n"
   148             + "    }\n"
   149             + "    vm.loadClass = loader.loadClass;\n"
   150             + "    vm.loadBytes = function(name) {\n"
   151             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   152             + "        loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   153             + "    }\n"
   154             + "    vm.java_lang_reflect_Array(false);\n"
   155             + "    vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   156             + "      loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
   157             + "    return loader;\n"
   158             + "  };\n");
   159         out.append("}(this));");
   160     }
   161     private static void readResource(InputStream emul, Appendable out) throws IOException {
   162         try {
   163             int state = 0;
   164             for (;;) {
   165                 int ch = emul.read();
   166                 if (ch == -1) {
   167                     break;
   168                 }
   169                 if (ch < 0 || ch > 255) {
   170                     throw new IOException("Invalid char in emulation " + ch);
   171                 }
   172                 switch (state) {
   173                     case 0: 
   174                         if (ch == '/') {
   175                             state = 1;
   176                         } else {
   177                             out.append((char)ch);
   178                         }
   179                         break;
   180                     case 1:
   181                         if (ch == '*') {
   182                             state = 2;
   183                         } else {
   184                             out.append('/').append((char)ch);
   185                             state = 0;
   186                         }
   187                         break;
   188                     case 2:
   189                         if (ch == '*') {
   190                             state = 3;
   191                         }
   192                         break;
   193                     case 3:
   194                         if (ch == '/') {
   195                             state = 0;
   196                         } else {
   197                             state = 2;
   198                         }
   199                         break;
   200                 }
   201             }
   202         } finally {
   203             emul.close();
   204         }
   205     }
   206 
   207     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   208         return l.get(name + ".class"); // NOI18N
   209     }
   210 
   211     static String toString(String name) throws IOException {
   212         StringBuilder sb = new StringBuilder();
   213 //        compile(sb, name);
   214         return sb.toString().toString();
   215     }
   216 
   217     private StringArray scripts = new StringArray();
   218     private StringArray references = new StringArray();
   219     
   220     @Override
   221     protected boolean requireReference(String cn) {
   222         if (references.contains(cn)) {
   223             return false;
   224         }
   225         references.add(cn);
   226         return true;
   227     }
   228 
   229     @Override
   230     protected void requireScript(String resourcePath) {
   231         scripts.add(resourcePath);
   232     }
   233 
   234     @Override
   235     String assignClass(String className) {
   236         return "vm." + className + " = ";
   237     }
   238     
   239     @Override
   240     String accessClass(String className) {
   241         return "vm." + className;
   242     }
   243 
   244     @Override
   245     String getVMObject() {
   246         return "vm";
   247     }
   248 }