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