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.bck2brwsr.aot;
20 import java.io.BufferedReader;
21 import java.io.ByteArrayInputStream;
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
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;
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;
42 /** Utilities to process JAR files and set a compiler
46 * @author Jaroslav Tulach
48 public final class Bck2BrwsrJars {
49 private static final Logger LOG = Logger.getLogger(Bck2BrwsrJars.class.getName());
51 private Bck2BrwsrJars() {
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
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
70 public static Bck2Brwsr configureFrom(Bck2Brwsr c, File jar) throws IOException {
71 if (jar.isDirectory()) {
72 return configureDir(c, jar);
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 {
83 public InputStream get(String resource) throws IOException {
84 InputStream is = jf.getInputStream(new ZipEntry(resource));
85 return is == null ? super.get(resource) : is;
88 JarRes jarRes = new JarRes();
90 listJAR(jf, jarRes, resources, exported);
92 String cp = jf.getManifest().getMainAttributes().getValue("Class-Path"); // NOI18N
93 String[] classpath = cp == null ? new String[0] : cp.split(" ");
96 c = Bck2Brwsr.newCompiler();
101 .addClasses(classes.toArray(new String[classes.size()]))
102 .addExported(exported.toArray(new String[exported.size()]))
103 .addResources(resources.toArray(new String[resources.size()]))
107 private static void listJAR(
108 JarFile j, EmulationResources classes,
109 List<String> resources, Set<String> keep
110 ) throws IOException {
111 Enumeration<JarEntry> en = j.entries();
112 while (en.hasMoreElements()) {
113 JarEntry e = en.nextElement();
114 final String n = e.getName();
115 if (n.endsWith("/")) {
118 if (n.startsWith("META-INF/maven/")) {
121 int last = n.lastIndexOf('/');
122 String pkg = n.substring(0, last + 1);
123 if (pkg.startsWith("java/")) {
126 if (n.endsWith(".class")) {
127 classes.addClassResource(n);
130 if (n.startsWith("META-INF/services/") && keep != null) {
131 BufferedReader r = new BufferedReader(new InputStreamReader(j.getInputStream(e)));
133 String l = r.readLine();
137 if (l.startsWith("#")) {
140 keep.add(l.replace('.', '/'));
145 String exp = j.getManifest().getMainAttributes().getValue("Export-Package");
146 if (exp != null && keep != null) {
147 for (String def : exp.split(",")) {
148 for (String sep : def.split(";")) {
149 keep.add(sep.replace('.', '/') + "/");
156 static byte[] readFrom(InputStream is) throws IOException {
157 int expLen = is.available();
161 byte[] arr = new byte[expLen];
164 int read = is.read(arr, pos, arr.length - pos);
169 if (pos == arr.length) {
170 byte[] tmp = new byte[arr.length * 2];
171 System.arraycopy(arr, 0, tmp, 0, arr.length);
175 if (pos != arr.length) {
176 byte[] tmp = new byte[pos];
177 System.arraycopy(arr, 0, tmp, 0, pos);
184 static class EmulationResources implements Bck2Brwsr.Resources {
185 private final List<String> classes;
186 private final Map<String,byte[]> converted = new HashMap<>();
187 private final BytecodeProcessor proc;
189 protected EmulationResources(List<String> classes) {
190 this.classes = classes;
193 Class<?> bpClass = Class.forName("org.apidesign.bck2brwsr.aot.RetroLambda");
194 p = (BytecodeProcessor) bpClass.newInstance();
195 } catch (Throwable t) {
202 public InputStream get(String name) throws IOException {
203 byte[] arr = converted.get(name);
205 return new ByteArrayInputStream(arr);
208 Enumeration<URL> en = Bck2BrwsrJars.class.getClassLoader().getResources(name);
210 while (en.hasMoreElements()) {
211 u = en.nextElement();
214 LOG.log(Level.WARNING, "Cannot find {0}", name);
217 if (u.toExternalForm().contains("/rt.jar!")) {
218 LOG.log(Level.WARNING, "{0}No bootdelegation for ", name);
221 return u.openStream();
224 private void addClassResource(String n) throws IOException {
226 try (InputStream is = this.get(n)) {
227 Map<String, byte[]> conv = proc.process(n, readFrom(is), this);
229 boolean found = false;
230 for (Map.Entry<String, byte[]> entrySet : conv.entrySet()) {
231 String res = entrySet.getKey();
232 byte[] bytes = entrySet.getValue();
236 assert res.endsWith(".class") : "Wrong resource: " + res;
237 converted.put(res, bytes);
238 classes.add(res.substring(0, res.length() - 6));
241 throw new IOException("Cannot find " + n + " among " + conv);
247 classes.add(n.substring(0, n.length() - 6));
251 private static Bck2Brwsr configureDir(Bck2Brwsr c, final File dir) throws IOException {
252 List<String> arr = new ArrayList<>();
253 List<String> classes = new ArrayList<>();
254 class DirRes extends EmulationResources {
255 public DirRes(List<String> classes) {
260 public InputStream get(String name) throws IOException {
261 InputStream is = super.get(name);
265 File r = new File(dir, name.replace('/', File.separatorChar));
267 return new FileInputStream(r);
272 DirRes dirRes = new DirRes(classes);
273 listDir(dir, null, dirRes, arr);
275 c = Bck2Brwsr.newCompiler();
278 .addRootClasses(classes.toArray(new String[0]))
279 .addResources(arr.toArray(new String[0]))
281 //.obfuscation(ObfuscationLevel.FULL)
285 private static void listDir(
286 File f, String pref, EmulationResources res, List<String> resources
287 ) throws IOException {
288 File[] arr = f.listFiles();
290 if (f.getName().endsWith(".class")) {
291 res.addClassResource(pref + f.getName());
293 resources.add(pref + f.getName());
296 for (File ch : arr) {
297 listDir(ch, pref == null ? "" : pref + f.getName() + "/", res, resources);