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;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
27 import java.util.ArrayList;
28 import java.util.Enumeration;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
34 import java.util.jar.JarEntry;
35 import java.util.jar.JarFile;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import java.util.zip.ZipEntry;
39 import org.apidesign.vm4brwsr.Bck2Brwsr;
41 /** Utilities to process JAR files and set a compiler
45 * @author Jaroslav Tulach
47 public final class Bck2BrwsrJars {
48 private static final Logger LOG = Logger.getLogger(Bck2BrwsrJars.class.getName());
50 private Bck2BrwsrJars() {
53 /** Creates new compiler pre-configured from the content of
54 * provided JAR file. The compiler will compile all classes.
55 * The system understands OSGi manifest entries and will export
56 * all packages that are exported in the JAR file. The system
57 * also recognizes META-INF/services and makes sure the class names
60 * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
61 * {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
62 * {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
63 * Can be <code>null</code> - in such case an
64 * {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
65 * @param jar the file to process
66 * @return newly configured compiler
67 * @throws IOException if something goes wrong
69 public static Bck2Brwsr configureFrom(Bck2Brwsr c, File jar) throws IOException {
70 if (jar.isDirectory()) {
71 return configureDir(c, jar);
73 final JarFile jf = new JarFile(jar);
74 final List<String> classes = new ArrayList<>();
75 List<String> resources = new ArrayList<>();
76 Set<String> exported = new HashSet<>();
77 class JarRes extends EmulationResources implements Bck2Brwsr.Resources {
82 public InputStream get(String resource) throws IOException {
83 InputStream is = jf.getInputStream(new ZipEntry(resource));
84 return is == null ? super.get(resource) : is;
87 JarRes jarRes = new JarRes();
89 listJAR(jf, jarRes, resources, exported);
91 String cp = jf.getManifest().getMainAttributes().getValue("Class-Path"); // NOI18N
92 String[] classpath = cp == null ? new String[0] : cp.split(" ");
95 c = Bck2Brwsr.newCompiler();
100 .addClasses(classes.toArray(new String[classes.size()]))
101 .addExported(exported.toArray(new String[exported.size()]))
102 .addResources(resources.toArray(new String[resources.size()]))
106 private static void listJAR(
107 JarFile j, EmulationResources classes,
108 List<String> resources, Set<String> keep
109 ) throws IOException {
110 Enumeration<JarEntry> en = j.entries();
111 while (en.hasMoreElements()) {
112 JarEntry e = en.nextElement();
113 final String n = e.getName();
114 if (n.endsWith("/")) {
117 if (n.startsWith("META-INF/maven/")) {
120 int last = n.lastIndexOf('/');
121 String pkg = n.substring(0, last + 1);
122 if (pkg.startsWith("java/")) {
125 if (n.endsWith(".class")) {
126 classes.addClassResource(n);
129 if (n.startsWith("META-INF/services/") && keep != null) {
130 BufferedReader r = new BufferedReader(new InputStreamReader(j.getInputStream(e)));
132 String l = r.readLine();
136 if (l.startsWith("#")) {
139 keep.add(l.replace('.', '/'));
144 String exp = j.getManifest().getMainAttributes().getValue("Export-Package");
145 if (exp != null && keep != null) {
146 for (String def : exp.split(",")) {
147 for (String sep : def.split(";")) {
148 keep.add(sep.replace('.', '/') + "/");
155 static byte[] readFrom(InputStream is) throws IOException {
156 int expLen = is.available();
160 byte[] arr = new byte[expLen];
163 int read = is.read(arr, pos, arr.length - pos);
168 if (pos == arr.length) {
169 byte[] tmp = new byte[arr.length * 2];
170 System.arraycopy(arr, 0, tmp, 0, arr.length);
174 if (pos != arr.length) {
175 byte[] tmp = new byte[pos];
176 System.arraycopy(arr, 0, tmp, 0, pos);
183 static class EmulationResources implements Bck2Brwsr.Resources {
184 private final List<String> classes;
185 private final Map<String,byte[]> converted = new HashMap<>();
186 private final BytecodeProcessor proc;
188 protected EmulationResources(List<String> classes) {
189 this.classes = classes;
192 Class<?> bpClass = Class.forName("org.apidesign.bck2brwsr.aot.RetroLambda");
193 p = (BytecodeProcessor) bpClass.newInstance();
194 } catch (Throwable t) {
201 public InputStream get(String name) throws IOException {
202 Enumeration<URL> en = Bck2BrwsrJars.class.getClassLoader().getResources(name);
204 while (en.hasMoreElements()) {
205 u = en.nextElement();
208 LOG.log(Level.WARNING, "Cannot find {0}", name);
211 if (u.toExternalForm().contains("/rt.jar!")) {
212 LOG.log(Level.WARNING, "{0}No bootdelegation for ", name);
215 return u.openStream();
218 private void addClassResource(String n) throws IOException {
220 try (InputStream is = this.get(n)) {
221 Map<String, byte[]> conv = proc.process(n, readFrom(is), this);
223 boolean found = false;
224 for (Map.Entry<String, byte[]> entrySet : conv.entrySet()) {
225 String res = entrySet.getKey();
226 byte[] bytes = entrySet.getValue();
230 assert res.endsWith(".class");
231 converted.put(res, bytes);
232 classes.add(res.substring(0, res.length() - 6));
235 throw new IOException("Cannot find " + n + " among " + conv);
241 classes.add(n.substring(0, n.length() - 6));
245 private static Bck2Brwsr configureDir(Bck2Brwsr c, final File dir) throws IOException {
246 List<String> arr = new ArrayList<>();
247 List<String> classes = new ArrayList<>();
248 class DirRes extends EmulationResources {
249 public DirRes(List<String> classes) {
254 public InputStream get(String name) throws IOException {
255 InputStream is = super.get(name);
259 File r = new File(dir, name.replace('/', File.separatorChar));
261 return new FileInputStream(r);
266 DirRes dirRes = new DirRes(classes);
267 listDir(dir, null, dirRes, arr);
269 c = Bck2Brwsr.newCompiler();
272 .addRootClasses(classes.toArray(new String[0]))
273 .addResources(arr.toArray(new String[0]))
275 //.obfuscation(ObfuscationLevel.FULL)
279 private static void listDir(
280 File f, String pref, EmulationResources res, List<String> resources
281 ) throws IOException {
282 File[] arr = f.listFiles();
284 if (f.getName().endsWith(".class")) {
285 res.addClassResource(pref + f.getName());
287 resources.add(pref + f.getName());
290 for (File ch : arr) {
291 listDir(ch, pref == null ? "" : pref + f.getName() + "/", res, resources);