rt/aot/src/main/java/org/apidesign/bck2brwsr/aot/Bck2BrwsrJars.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 26 Sep 2014 13:42:15 +0200
changeset 1710 6db177c4f72c
parent 1696 ce34fdc36fac
child 1724 50ad005d1597
permissions -rw-r--r--
Need to be able to load classes from classpath to find out if a method overrides something in a superclass.
jaroslav@1599
     1
/**
jaroslav@1599
     2
 * Back 2 Browser Bytecode Translator
jaroslav@1599
     3
 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@1599
     4
 *
jaroslav@1599
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@1599
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@1599
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@1599
     8
 *
jaroslav@1599
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@1599
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@1599
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@1599
    12
 * GNU General Public License for more details.
jaroslav@1599
    13
 *
jaroslav@1599
    14
 * You should have received a copy of the GNU General Public License
jaroslav@1599
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@1599
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@1599
    17
 */
jaroslav@1599
    18
package org.apidesign.bck2brwsr.aot;
jaroslav@1599
    19
jaroslav@1599
    20
import java.io.BufferedReader;
jaroslav@1684
    21
import java.io.ByteArrayInputStream;
jaroslav@1599
    22
import java.io.File;
jaroslav@1679
    23
import java.io.FileInputStream;
jaroslav@1599
    24
import java.io.IOException;
jaroslav@1599
    25
import java.io.InputStream;
jaroslav@1599
    26
import java.io.InputStreamReader;
jaroslav@1599
    27
import java.net.URL;
jaroslav@1599
    28
import java.util.ArrayList;
jaroslav@1599
    29
import java.util.Enumeration;
jaroslav@1678
    30
import java.util.HashMap;
jaroslav@1599
    31
import java.util.HashSet;
jaroslav@1599
    32
import java.util.List;
jaroslav@1678
    33
import java.util.Map;
jaroslav@1599
    34
import java.util.Set;
jaroslav@1599
    35
import java.util.jar.JarEntry;
jaroslav@1599
    36
import java.util.jar.JarFile;
jaroslav@1599
    37
import java.util.logging.Level;
jaroslav@1599
    38
import java.util.logging.Logger;
jaroslav@1599
    39
import java.util.zip.ZipEntry;
jaroslav@1599
    40
import org.apidesign.vm4brwsr.Bck2Brwsr;
jaroslav@1599
    41
jaroslav@1599
    42
/** Utilities to process JAR files and set a compiler
jaroslav@1603
    43
 * up.
jaroslav@1599
    44
 *
jaroslav@1603
    45
 * @since 0.9
jaroslav@1599
    46
 * @author Jaroslav Tulach
jaroslav@1599
    47
 */
jaroslav@1599
    48
public final class Bck2BrwsrJars {
jaroslav@1599
    49
    private static final Logger LOG = Logger.getLogger(Bck2BrwsrJars.class.getName());
jaroslav@1679
    50
jaroslav@1599
    51
    private Bck2BrwsrJars() {
jaroslav@1599
    52
    }
jaroslav@1599
    53
    
jaroslav@1599
    54
    /** Creates new compiler pre-configured from the content of 
jaroslav@1599
    55
     * provided JAR file. The compiler will compile all classes.
jaroslav@1599
    56
     * The system understands OSGi manifest entries and will export
jaroslav@1599
    57
     * all packages that are exported in the JAR file. The system
jaroslav@1628
    58
     * also recognizes META-INF/services and makes sure the class names
jaroslav@1599
    59
     * are not mangled.
jaroslav@1599
    60
     * 
jaroslav@1599
    61
     * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
jaroslav@1599
    62
     *    {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
jaroslav@1599
    63
     *    {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
jaroslav@1599
    64
     *    Can be <code>null</code> - in such case an 
jaroslav@1599
    65
     *    {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
jaroslav@1599
    66
     * @param jar the file to process
jaroslav@1599
    67
     * @return newly configured compiler
jaroslav@1599
    68
     * @throws IOException if something goes wrong
jaroslav@1599
    69
     */
jaroslav@1599
    70
    public static Bck2Brwsr configureFrom(Bck2Brwsr c, File jar) throws IOException {
jaroslav@1710
    71
        return configureFrom(c, jar, null);
jaroslav@1710
    72
    }
jaroslav@1710
    73
    
jaroslav@1710
    74
    /** Creates new compiler pre-configured from the content of 
jaroslav@1710
    75
     * provided JAR file. The compiler will compile all classes.
jaroslav@1710
    76
     * The system understands OSGi manifest entries and will export
jaroslav@1710
    77
     * all packages that are exported in the JAR file. The system
jaroslav@1710
    78
     * also recognizes META-INF/services and makes sure the class names
jaroslav@1710
    79
     * are not mangled.
jaroslav@1710
    80
     * 
jaroslav@1710
    81
     * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
jaroslav@1710
    82
     *    {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
jaroslav@1710
    83
     *    {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
jaroslav@1710
    84
     *    Can be <code>null</code> - in such case an 
jaroslav@1710
    85
     *    {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
jaroslav@1710
    86
     * @param jar the file to process
jaroslav@1710
    87
     * @param classpath additional resources to make available during
jaroslav@1710
    88
     *   compilation, but not include them in the generated JavaScript
jaroslav@1710
    89
     * @return newly configured compiler
jaroslav@1710
    90
     * @throws IOException if something goes wrong
jaroslav@1710
    91
     * @since 0.11
jaroslav@1710
    92
     */
jaroslav@1710
    93
    public static Bck2Brwsr configureFrom(
jaroslav@1710
    94
        Bck2Brwsr c, File jar, final ClassLoader classpath
jaroslav@1710
    95
    ) throws IOException {
jaroslav@1679
    96
        if (jar.isDirectory()) {
jaroslav@1710
    97
            return configureDir(c, jar, classpath);
jaroslav@1679
    98
        }
jaroslav@1601
    99
        final JarFile jf = new JarFile(jar);
jaroslav@1678
   100
        final List<String> classes = new ArrayList<>();
jaroslav@1601
   101
        List<String> resources = new ArrayList<>();
jaroslav@1601
   102
        Set<String> exported = new HashSet<>();
jaroslav@1601
   103
        class JarRes extends EmulationResources implements Bck2Brwsr.Resources {
jaroslav@1678
   104
            JarRes() {
jaroslav@1710
   105
                super(classpath, classes);
jaroslav@1678
   106
            }
jaroslav@1601
   107
            @Override
jaroslav@1601
   108
            public InputStream get(String resource) throws IOException {
jaroslav@1696
   109
                InputStream is = getConverted(resource);
jaroslav@1696
   110
                if (is != null) {
jaroslav@1696
   111
                    return is;
jaroslav@1696
   112
                }
jaroslav@1696
   113
                is = jf.getInputStream(new ZipEntry(resource));
jaroslav@1601
   114
                return is == null ? super.get(resource) : is;
jaroslav@1599
   115
            }
jaroslav@1599
   116
        }
jaroslav@1678
   117
        JarRes jarRes = new JarRes();
jaroslav@1678
   118
jaroslav@1678
   119
        listJAR(jf, jarRes, resources, exported);
jaroslav@1678
   120
        
jaroslav@1678
   121
        String cp = jf.getManifest().getMainAttributes().getValue("Class-Path"); // NOI18N
jaroslav@1710
   122
        String[] parts = cp == null ? new String[0] : cp.split(" ");
jaroslav@1678
   123
jaroslav@1622
   124
        if (c == null) {
jaroslav@1622
   125
            c = Bck2Brwsr.newCompiler();
jaroslav@1622
   126
        }
jaroslav@1622
   127
        
jaroslav@1622
   128
        return c
jaroslav@1710
   129
            .library(parts)
jaroslav@1601
   130
            .addClasses(classes.toArray(new String[classes.size()]))
jaroslav@1601
   131
            .addExported(exported.toArray(new String[exported.size()]))
jaroslav@1601
   132
            .addResources(resources.toArray(new String[resources.size()]))
jaroslav@1678
   133
            .resources(jarRes);
jaroslav@1599
   134
    }
jaroslav@1599
   135
    
jaroslav@1599
   136
    private static void listJAR(
jaroslav@1678
   137
        JarFile j, EmulationResources classes,
jaroslav@1599
   138
        List<String> resources, Set<String> keep
jaroslav@1599
   139
    ) throws IOException {
jaroslav@1599
   140
        Enumeration<JarEntry> en = j.entries();
jaroslav@1599
   141
        while (en.hasMoreElements()) {
jaroslav@1599
   142
            JarEntry e = en.nextElement();
jaroslav@1599
   143
            final String n = e.getName();
jaroslav@1599
   144
            if (n.endsWith("/")) {
jaroslav@1599
   145
                continue;
jaroslav@1599
   146
            }
jaroslav@1602
   147
            if (n.startsWith("META-INF/maven/")) {
jaroslav@1602
   148
                continue;
jaroslav@1602
   149
            }
jaroslav@1599
   150
            int last = n.lastIndexOf('/');
jaroslav@1599
   151
            String pkg = n.substring(0, last + 1);
jaroslav@1599
   152
            if (pkg.startsWith("java/")) {
jaroslav@1599
   153
                keep.add(pkg);
jaroslav@1599
   154
            }
jaroslav@1599
   155
            if (n.endsWith(".class")) {
jaroslav@1678
   156
                classes.addClassResource(n);
jaroslav@1599
   157
            } else {
jaroslav@1599
   158
                resources.add(n);
jaroslav@1599
   159
                if (n.startsWith("META-INF/services/") && keep != null) {
jaroslav@1599
   160
                    BufferedReader r = new BufferedReader(new InputStreamReader(j.getInputStream(e)));
jaroslav@1599
   161
                    for (;;) {
jaroslav@1599
   162
                        String l = r.readLine();
jaroslav@1599
   163
                        if (l == null) {
jaroslav@1599
   164
                            break;
jaroslav@1599
   165
                        }
jaroslav@1599
   166
                        if (l.startsWith("#")) {
jaroslav@1599
   167
                            continue;
jaroslav@1599
   168
                        }
jaroslav@1599
   169
                        keep.add(l.replace('.', '/'));
jaroslav@1599
   170
                    }
jaroslav@1599
   171
                }
jaroslav@1599
   172
            }
jaroslav@1599
   173
        }
jaroslav@1599
   174
        String exp = j.getManifest().getMainAttributes().getValue("Export-Package");
jaroslav@1599
   175
        if (exp != null && keep != null) {
jaroslav@1599
   176
            for (String def : exp.split(",")) {
jaroslav@1599
   177
                for (String sep : def.split(";")) {
jaroslav@1599
   178
                    keep.add(sep.replace('.', '/') + "/");
jaroslav@1599
   179
                    break;
jaroslav@1599
   180
                }
jaroslav@1599
   181
            }
jaroslav@1599
   182
        }
jaroslav@1599
   183
    }
jaroslav@1678
   184
    
jaroslav@1678
   185
    static byte[] readFrom(InputStream is) throws IOException {
jaroslav@1678
   186
        int expLen = is.available();
jaroslav@1678
   187
        if (expLen < 1) {
jaroslav@1678
   188
            expLen = 1;
jaroslav@1678
   189
        }
jaroslav@1678
   190
        byte[] arr = new byte[expLen];
jaroslav@1678
   191
        int pos = 0;
jaroslav@1678
   192
        for (;;) {
jaroslav@1678
   193
            int read = is.read(arr, pos, arr.length - pos);
jaroslav@1678
   194
            if (read == -1) {
jaroslav@1678
   195
                break;
jaroslav@1678
   196
            }
jaroslav@1678
   197
            pos += read;
jaroslav@1678
   198
            if (pos == arr.length) {
jaroslav@1678
   199
                byte[] tmp = new byte[arr.length * 2];
jaroslav@1678
   200
                System.arraycopy(arr, 0, tmp, 0, arr.length);
jaroslav@1678
   201
                arr = tmp;
jaroslav@1678
   202
            }
jaroslav@1678
   203
        }
jaroslav@1678
   204
        if (pos != arr.length) {
jaroslav@1678
   205
            byte[] tmp = new byte[pos];
jaroslav@1678
   206
            System.arraycopy(arr, 0, tmp, 0, pos);
jaroslav@1678
   207
            arr = tmp;
jaroslav@1678
   208
        }
jaroslav@1678
   209
        return arr;
jaroslav@1678
   210
    }
jaroslav@1678
   211
    
jaroslav@1599
   212
jaroslav@1599
   213
    static class EmulationResources implements Bck2Brwsr.Resources {
jaroslav@1678
   214
        private final List<String> classes;
jaroslav@1678
   215
        private final Map<String,byte[]> converted = new HashMap<>();
jaroslav@1678
   216
        private final BytecodeProcessor proc;
jaroslav@1710
   217
        private final ClassLoader cp;
jaroslav@1678
   218
jaroslav@1710
   219
        protected EmulationResources(ClassLoader cp, List<String> classes) {
jaroslav@1678
   220
            this.classes = classes;
jaroslav@1710
   221
            this.cp = cp != null ? cp : Bck2BrwsrJars.class.getClassLoader();
jaroslav@1678
   222
            BytecodeProcessor p;
jaroslav@1678
   223
            try {
jaroslav@1678
   224
                Class<?> bpClass = Class.forName("org.apidesign.bck2brwsr.aot.RetroLambda");
jaroslav@1678
   225
                p = (BytecodeProcessor) bpClass.newInstance();
jaroslav@1678
   226
            } catch (Throwable t) {
jaroslav@1678
   227
                p = null;
jaroslav@1678
   228
            }
jaroslav@1678
   229
            this.proc = p;
jaroslav@1678
   230
        }
jaroslav@1599
   231
jaroslav@1696
   232
        protected final InputStream getConverted(String name) throws IOException {
jaroslav@1684
   233
            byte[] arr = converted.get(name);
jaroslav@1684
   234
            if (arr != null) {
jaroslav@1684
   235
                return new ByteArrayInputStream(arr);
jaroslav@1684
   236
            }
jaroslav@1696
   237
            return null;
jaroslav@1696
   238
        }
jaroslav@1696
   239
        
jaroslav@1696
   240
        @Override
jaroslav@1696
   241
        public InputStream get(String name) throws IOException {
jaroslav@1696
   242
            InputStream is = getConverted(name);
jaroslav@1696
   243
            if (is != null) {
jaroslav@1696
   244
                return is;
jaroslav@1696
   245
            }
jaroslav@1710
   246
            Enumeration<URL> en = cp.getResources(name);
jaroslav@1599
   247
            URL u = null;
jaroslav@1599
   248
            while (en.hasMoreElements()) {
jaroslav@1599
   249
                u = en.nextElement();
jaroslav@1599
   250
            }
jaroslav@1599
   251
            if (u == null) {
jaroslav@1599
   252
                LOG.log(Level.WARNING, "Cannot find {0}", name);
jaroslav@1599
   253
                return null;
jaroslav@1599
   254
            }
jaroslav@1599
   255
            if (u.toExternalForm().contains("/rt.jar!")) {
jaroslav@1599
   256
                LOG.log(Level.WARNING, "{0}No bootdelegation for ", name);
jaroslav@1599
   257
                return null;
jaroslav@1599
   258
            }
jaroslav@1599
   259
            return u.openStream();
jaroslav@1599
   260
        }
jaroslav@1678
   261
jaroslav@1678
   262
        private void addClassResource(String n) throws IOException {
jaroslav@1678
   263
            if (proc != null) {
jaroslav@1678
   264
                try (InputStream is = this.get(n)) {
jaroslav@1678
   265
                    Map<String, byte[]> conv = proc.process(n, readFrom(is), this);
jaroslav@1678
   266
                    if (conv != null) {
jaroslav@1681
   267
                        boolean found = false;
jaroslav@1681
   268
                        for (Map.Entry<String, byte[]> entrySet : conv.entrySet()) {
jaroslav@1681
   269
                            String res = entrySet.getKey();
jaroslav@1681
   270
                            byte[] bytes = entrySet.getValue();
jaroslav@1681
   271
                            if (res.equals(n)) {
jaroslav@1681
   272
                                found = true;
jaroslav@1681
   273
                            }
jaroslav@1684
   274
                            assert res.endsWith(".class") : "Wrong resource: " + res;
jaroslav@1681
   275
                            converted.put(res, bytes);
jaroslav@1681
   276
                            classes.add(res.substring(0, res.length() - 6));
jaroslav@1681
   277
                        }
jaroslav@1681
   278
                        if (!found) {
jaroslav@1678
   279
                            throw new IOException("Cannot find " + n + " among " + conv);
jaroslav@1678
   280
                        }
jaroslav@1678
   281
                        return;
jaroslav@1678
   282
                    }
jaroslav@1678
   283
                }
jaroslav@1678
   284
            }
jaroslav@1678
   285
            classes.add(n.substring(0, n.length() - 6));
jaroslav@1678
   286
        }
jaroslav@1599
   287
    }
jaroslav@1599
   288
    
jaroslav@1710
   289
    private static Bck2Brwsr configureDir(Bck2Brwsr c, final File dir, ClassLoader cp) throws IOException {
jaroslav@1679
   290
        List<String> arr = new ArrayList<>();
jaroslav@1679
   291
        List<String> classes = new ArrayList<>();
jaroslav@1679
   292
        class DirRes extends EmulationResources {
jaroslav@1710
   293
            public DirRes(ClassLoader cp, List<String> classes) {
jaroslav@1710
   294
                super(cp, classes);
jaroslav@1679
   295
            }
jaroslav@1679
   296
jaroslav@1679
   297
            @Override
jaroslav@1679
   298
            public InputStream get(String name) throws IOException {
jaroslav@1679
   299
                InputStream is = super.get(name);
jaroslav@1679
   300
                if (is != null) {
jaroslav@1679
   301
                    return is;
jaroslav@1679
   302
                }
jaroslav@1679
   303
                File r = new File(dir, name.replace('/', File.separatorChar));
jaroslav@1679
   304
                if (r.exists()) {
jaroslav@1679
   305
                    return new FileInputStream(r);
jaroslav@1679
   306
                }
jaroslav@1679
   307
                return null;
jaroslav@1679
   308
            }
jaroslav@1679
   309
        }
jaroslav@1710
   310
        DirRes dirRes = new DirRes(cp, classes);
jaroslav@1679
   311
        listDir(dir, null, dirRes, arr);
jaroslav@1679
   312
        if (c == null) {
jaroslav@1679
   313
            c = Bck2Brwsr.newCompiler();
jaroslav@1679
   314
        }
jaroslav@1679
   315
        return c
jaroslav@1679
   316
        .addRootClasses(classes.toArray(new String[0]))
jaroslav@1679
   317
        .addResources(arr.toArray(new String[0]))
jaroslav@1679
   318
        .library()
jaroslav@1679
   319
        //.obfuscation(ObfuscationLevel.FULL)
jaroslav@1679
   320
        .resources(dirRes);
jaroslav@1679
   321
    }
jaroslav@1679
   322
jaroslav@1679
   323
    private static void listDir(
jaroslav@1679
   324
        File f, String pref, EmulationResources res, List<String> resources
jaroslav@1679
   325
    ) throws IOException {
jaroslav@1679
   326
        File[] arr = f.listFiles();
jaroslav@1679
   327
        if (arr == null) {
jaroslav@1679
   328
            if (f.getName().endsWith(".class")) {
jaroslav@1679
   329
                res.addClassResource(pref + f.getName());
jaroslav@1679
   330
            } else {
jaroslav@1679
   331
                resources.add(pref + f.getName());
jaroslav@1679
   332
            }
jaroslav@1679
   333
        } else {
jaroslav@1679
   334
            for (File ch : arr) {
jaroslav@1679
   335
                listDir(ch, pref == null ? "" : pref + f.getName() + "/", res, resources);
jaroslav@1679
   336
            }
jaroslav@1679
   337
        }
jaroslav@1679
   338
    }
jaroslav@1678
   339
    
jaroslav@1599
   340
}