rt/aot/src/main/java/org/apidesign/bck2brwsr/aot/Bck2BrwsrJars.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 14 Sep 2014 22:33:35 +0200
changeset 1696 ce34fdc36fac
parent 1684 3238bffeaf12
child 1710 6db177c4f72c
permissions -rw-r--r--
Fail the build if invokeDynamic instruction remains un-preprocessed
     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.bck2brwsr.aot;
    19 
    20 import java.io.BufferedReader;
    21 import java.io.ByteArrayInputStream;
    22 import java.io.File;
    23 import java.io.FileInputStream;
    24 import java.io.IOException;
    25 import java.io.InputStream;
    26 import java.io.InputStreamReader;
    27 import java.net.URL;
    28 import java.util.ArrayList;
    29 import java.util.Enumeration;
    30 import java.util.HashMap;
    31 import java.util.HashSet;
    32 import java.util.List;
    33 import java.util.Map;
    34 import java.util.Set;
    35 import java.util.jar.JarEntry;
    36 import java.util.jar.JarFile;
    37 import java.util.logging.Level;
    38 import java.util.logging.Logger;
    39 import java.util.zip.ZipEntry;
    40 import org.apidesign.vm4brwsr.Bck2Brwsr;
    41 
    42 /** Utilities to process JAR files and set a compiler
    43  * up.
    44  *
    45  * @since 0.9
    46  * @author Jaroslav Tulach
    47  */
    48 public final class Bck2BrwsrJars {
    49     private static final Logger LOG = Logger.getLogger(Bck2BrwsrJars.class.getName());
    50 
    51     private Bck2BrwsrJars() {
    52     }
    53     
    54     /** Creates new compiler pre-configured from the content of 
    55      * provided JAR file. The compiler will compile all classes.
    56      * The system understands OSGi manifest entries and will export
    57      * all packages that are exported in the JAR file. The system
    58      * also recognizes META-INF/services and makes sure the class names
    59      * are not mangled.
    60      * 
    61      * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
    62      *    {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
    63      *    {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
    64      *    Can be <code>null</code> - in such case an 
    65      *    {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
    66      * @param jar the file to process
    67      * @return newly configured compiler
    68      * @throws IOException if something goes wrong
    69      */
    70     public static Bck2Brwsr configureFrom(Bck2Brwsr c, File jar) throws IOException {
    71         if (jar.isDirectory()) {
    72             return configureDir(c, jar);
    73         }
    74         final JarFile jf = new JarFile(jar);
    75         final List<String> classes = new ArrayList<>();
    76         List<String> resources = new ArrayList<>();
    77         Set<String> exported = new HashSet<>();
    78         class JarRes extends EmulationResources implements Bck2Brwsr.Resources {
    79             JarRes() {
    80                 super(classes);
    81             }
    82             @Override
    83             public InputStream get(String resource) throws IOException {
    84                 InputStream is = getConverted(resource);
    85                 if (is != null) {
    86                     return is;
    87                 }
    88                 is = jf.getInputStream(new ZipEntry(resource));
    89                 return is == null ? super.get(resource) : is;
    90             }
    91         }
    92         JarRes jarRes = new JarRes();
    93 
    94         listJAR(jf, jarRes, resources, exported);
    95         
    96         String cp = jf.getManifest().getMainAttributes().getValue("Class-Path"); // NOI18N
    97         String[] classpath = cp == null ? new String[0] : cp.split(" ");
    98 
    99         if (c == null) {
   100             c = Bck2Brwsr.newCompiler();
   101         }
   102         
   103         return c
   104             .library(classpath)
   105             .addClasses(classes.toArray(new String[classes.size()]))
   106             .addExported(exported.toArray(new String[exported.size()]))
   107             .addResources(resources.toArray(new String[resources.size()]))
   108             .resources(jarRes);
   109     }
   110     
   111     private static void listJAR(
   112         JarFile j, EmulationResources classes,
   113         List<String> resources, Set<String> keep
   114     ) throws IOException {
   115         Enumeration<JarEntry> en = j.entries();
   116         while (en.hasMoreElements()) {
   117             JarEntry e = en.nextElement();
   118             final String n = e.getName();
   119             if (n.endsWith("/")) {
   120                 continue;
   121             }
   122             if (n.startsWith("META-INF/maven/")) {
   123                 continue;
   124             }
   125             int last = n.lastIndexOf('/');
   126             String pkg = n.substring(0, last + 1);
   127             if (pkg.startsWith("java/")) {
   128                 keep.add(pkg);
   129             }
   130             if (n.endsWith(".class")) {
   131                 classes.addClassResource(n);
   132             } else {
   133                 resources.add(n);
   134                 if (n.startsWith("META-INF/services/") && keep != null) {
   135                     BufferedReader r = new BufferedReader(new InputStreamReader(j.getInputStream(e)));
   136                     for (;;) {
   137                         String l = r.readLine();
   138                         if (l == null) {
   139                             break;
   140                         }
   141                         if (l.startsWith("#")) {
   142                             continue;
   143                         }
   144                         keep.add(l.replace('.', '/'));
   145                     }
   146                 }
   147             }
   148         }
   149         String exp = j.getManifest().getMainAttributes().getValue("Export-Package");
   150         if (exp != null && keep != null) {
   151             for (String def : exp.split(",")) {
   152                 for (String sep : def.split(";")) {
   153                     keep.add(sep.replace('.', '/') + "/");
   154                     break;
   155                 }
   156             }
   157         }
   158     }
   159     
   160     static byte[] readFrom(InputStream is) throws IOException {
   161         int expLen = is.available();
   162         if (expLen < 1) {
   163             expLen = 1;
   164         }
   165         byte[] arr = new byte[expLen];
   166         int pos = 0;
   167         for (;;) {
   168             int read = is.read(arr, pos, arr.length - pos);
   169             if (read == -1) {
   170                 break;
   171             }
   172             pos += read;
   173             if (pos == arr.length) {
   174                 byte[] tmp = new byte[arr.length * 2];
   175                 System.arraycopy(arr, 0, tmp, 0, arr.length);
   176                 arr = tmp;
   177             }
   178         }
   179         if (pos != arr.length) {
   180             byte[] tmp = new byte[pos];
   181             System.arraycopy(arr, 0, tmp, 0, pos);
   182             arr = tmp;
   183         }
   184         return arr;
   185     }
   186     
   187 
   188     static class EmulationResources implements Bck2Brwsr.Resources {
   189         private final List<String> classes;
   190         private final Map<String,byte[]> converted = new HashMap<>();
   191         private final BytecodeProcessor proc;
   192 
   193         protected EmulationResources(List<String> classes) {
   194             this.classes = classes;
   195             BytecodeProcessor p;
   196             try {
   197                 Class<?> bpClass = Class.forName("org.apidesign.bck2brwsr.aot.RetroLambda");
   198                 p = (BytecodeProcessor) bpClass.newInstance();
   199             } catch (Throwable t) {
   200                 p = null;
   201             }
   202             this.proc = p;
   203         }
   204 
   205         protected final InputStream getConverted(String name) throws IOException {
   206             byte[] arr = converted.get(name);
   207             if (arr != null) {
   208                 return new ByteArrayInputStream(arr);
   209             }
   210             return null;
   211         }
   212         
   213         @Override
   214         public InputStream get(String name) throws IOException {
   215             InputStream is = getConverted(name);
   216             if (is != null) {
   217                 return is;
   218             }
   219             Enumeration<URL> en = Bck2BrwsrJars.class.getClassLoader().getResources(name);
   220             URL u = null;
   221             while (en.hasMoreElements()) {
   222                 u = en.nextElement();
   223             }
   224             if (u == null) {
   225                 LOG.log(Level.WARNING, "Cannot find {0}", name);
   226                 return null;
   227             }
   228             if (u.toExternalForm().contains("/rt.jar!")) {
   229                 LOG.log(Level.WARNING, "{0}No bootdelegation for ", name);
   230                 return null;
   231             }
   232             return u.openStream();
   233         }
   234 
   235         private void addClassResource(String n) throws IOException {
   236             if (proc != null) {
   237                 try (InputStream is = this.get(n)) {
   238                     Map<String, byte[]> conv = proc.process(n, readFrom(is), this);
   239                     if (conv != null) {
   240                         boolean found = false;
   241                         for (Map.Entry<String, byte[]> entrySet : conv.entrySet()) {
   242                             String res = entrySet.getKey();
   243                             byte[] bytes = entrySet.getValue();
   244                             if (res.equals(n)) {
   245                                 found = true;
   246                             }
   247                             assert res.endsWith(".class") : "Wrong resource: " + res;
   248                             converted.put(res, bytes);
   249                             classes.add(res.substring(0, res.length() - 6));
   250                         }
   251                         if (!found) {
   252                             throw new IOException("Cannot find " + n + " among " + conv);
   253                         }
   254                         return;
   255                     }
   256                 }
   257             }
   258             classes.add(n.substring(0, n.length() - 6));
   259         }
   260     }
   261     
   262     private static Bck2Brwsr configureDir(Bck2Brwsr c, final File dir) throws IOException {
   263         List<String> arr = new ArrayList<>();
   264         List<String> classes = new ArrayList<>();
   265         class DirRes extends EmulationResources {
   266             public DirRes(List<String> classes) {
   267                 super(classes);
   268             }
   269 
   270             @Override
   271             public InputStream get(String name) throws IOException {
   272                 InputStream is = super.get(name);
   273                 if (is != null) {
   274                     return is;
   275                 }
   276                 File r = new File(dir, name.replace('/', File.separatorChar));
   277                 if (r.exists()) {
   278                     return new FileInputStream(r);
   279                 }
   280                 return null;
   281             }
   282         }
   283         DirRes dirRes = new DirRes(classes);
   284         listDir(dir, null, dirRes, arr);
   285         if (c == null) {
   286             c = Bck2Brwsr.newCompiler();
   287         }
   288         return c
   289         .addRootClasses(classes.toArray(new String[0]))
   290         .addResources(arr.toArray(new String[0]))
   291         .library()
   292         //.obfuscation(ObfuscationLevel.FULL)
   293         .resources(dirRes);
   294     }
   295 
   296     private static void listDir(
   297         File f, String pref, EmulationResources res, List<String> resources
   298     ) throws IOException {
   299         File[] arr = f.listFiles();
   300         if (arr == null) {
   301             if (f.getName().endsWith(".class")) {
   302                 res.addClassResource(pref + f.getName());
   303             } else {
   304                 resources.add(pref + f.getName());
   305             }
   306         } else {
   307             for (File ch : arr) {
   308                 listDir(ch, pref == null ? "" : pref + f.getName() + "/", res, resources);
   309             }
   310         }
   311     }
   312     
   313 }