Merge from mainline.
[official-gcc.git] / libjava / java / lang / VMCompiler.java
blob789445e4f56e26a196366332a34caa3cc6959042
1 /* VMClassLoader.java -- Reference implementation of compiler interface
2 Copyright (C) 2004, 2005, 2006 Free Software Foundation
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 02110-1301 USA.
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library. Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module. An independent module is a module which is not derived from
33 or based on this library. If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so. If you do not wish to do so, delete this
36 exception statement from your version. */
38 package java.lang;
40 import java.io.File;
41 import java.io.FileOutputStream;
42 import java.io.InputStreamReader;
43 import java.security.MessageDigest;
44 import java.security.ProtectionDomain;
45 import java.security.NoSuchAlgorithmException;
46 import java.util.WeakHashMap;
47 import java.util.HashSet;
48 import java.util.Enumeration;
49 import java.util.StringTokenizer;
50 import java.util.Vector;
51 import gnu.gcj.runtime.SharedLibHelper;
52 import gnu.gcj.runtime.PersistentByteMap;
53 import gnu.java.security.hash.MD5;
55 /**
56 * This class is just a per-VM reflection of java.lang.Compiler.
57 * All methods are defined identically.
59 final class VMCompiler
61 // True if we want to use gcj-jit.
62 public static boolean useCompiler = true;
64 // True if we're able to use gcj-jit.
65 public static final boolean canUseCompiler;
67 // Compiler to use.
68 public static String gcjJitCompiler;
70 // Compiler options.
71 public static String gcjJitCompilerOptions;
73 // Temporary directory to use.
74 public static String gcjJitTmpdir;
76 // This maps a ClassLoader to a set of SharedLibHelper objects that
77 // it has used. We do things this way to ensure that a
78 // SharedLibHelper is collected if and only if the ClassLoader is.
79 private static WeakHashMap sharedHelperMap = new WeakHashMap();
81 private static Vector precompiledMapFiles;
83 // We create a single MD5 engine and then clone it whenever we want
84 // a new one.
86 // We don't use
88 // md5Digest = MessageDigest.getInstance("MD5");
90 // here because that loads a great deal of security provider code as
91 // interpreted bytecode -- before we're able to use this class to
92 // load precompiled classes.
94 private static final MD5 md5Digest
95 = new gnu.java.security.hash.MD5();
97 static
99 gcjJitCompiler = System.getProperty("gnu.gcj.jit.compiler");
100 if (gcjJitCompiler == null)
101 canUseCompiler = false;
102 else
104 gcjJitCompilerOptions = System.getProperty("gnu.gcj.jit.options",
105 "-g");
106 gcjJitTmpdir = System.getProperty("gnu.gcj.jit.cachedir");
107 // Note that we *don't* choose java.io.tmpdir as a default --
108 // that would allow easy attacks against the VM.
109 if (gcjJitTmpdir == null)
110 canUseCompiler = false;
111 else
112 canUseCompiler = true;
115 String prop = System.getProperty ("gnu.gcj.precompiled.db.path");
116 if (prop != null)
118 precompiledMapFiles = new Vector();
119 // Add the
120 StringTokenizer st
121 = new StringTokenizer (prop,
122 System.getProperty ("path.separator", ":"));
124 while (st.hasMoreElements ())
126 String e = st.nextToken ();
129 PersistentByteMap map
130 = new PersistentByteMap
131 (e, PersistentByteMap.AccessMode.READ_ONLY);
132 precompiledMapFiles.add(map);
134 catch (IllegalArgumentException _)
136 // Not a map file
138 catch (java.io.IOException _)
141 catch (java.nio.BufferUnderflowException _)
143 // Invalid map file.
151 * Don't allow new `Compiler's to be made.
153 private VMCompiler()
157 private static Class loadSharedLibrary(ClassLoader loader,
158 String fileName,
159 ProtectionDomain domain,
160 String className)
162 Class c = null;
163 SharedLibHelper helper
164 = SharedLibHelper.findHelper (loader, fileName, domain.getCodeSource(),
165 domain, false);
166 c = helper.findClass (className);
167 if (c != null)
169 HashSet hs = (HashSet) sharedHelperMap.get(loader);
170 if (hs == null)
172 hs = new HashSet();
173 sharedHelperMap.put(loader, hs);
175 hs.add(helper);
177 return c;
181 * Compile a class given the bytes for it. Returns the Class, or
182 * null if compilation failed or otherwise could not be done.
184 public static Class compileClass(ClassLoader loader,
185 String name, byte[] data,
186 int offset, int len,
187 ProtectionDomain domain)
189 if (precompiledMapFiles == null
190 && (! useCompiler || ! canUseCompiler))
191 return null;
193 byte digest[];
197 MD5 md = (MD5) md5Digest.clone();
198 md.update(data);
199 digest = md.digest();
201 catch (NullPointerException _)
203 // If md5Digest==null -- but really this should never happen
204 // either, since the MD5 digest is in libgcj.
205 return null;
208 // We use lookaside cache files to determine whether these bytes
209 // correspond to a class file that is part of a precompiled DSO.
210 if (precompiledMapFiles != null)
214 Enumeration elements = precompiledMapFiles.elements();
215 while (elements.hasMoreElements())
217 PersistentByteMap map = (PersistentByteMap)elements.nextElement();
218 byte[] soName = map.get(digest);
219 if (soName != null)
220 return loadSharedLibrary(loader,
221 new String(soName),
222 domain, name);
225 catch (Exception _)
228 catch (UnknownError _)
230 // SharedLibHelper will throw UnknownError if the dlopen
231 // fails for some reason. We ignore it and continue on.
235 if (! useCompiler || ! canUseCompiler)
236 return null;
240 // FIXME: Make sure that the class represented by the
241 // bytes in DATA really is the class named in NAME. Make
242 // sure it's not "java.*".
243 StringBuffer hexBytes = new StringBuffer(gcjJitTmpdir);
244 hexBytes.append(File.separatorChar);
245 int digestLength = digest.length;
246 for (int i = 0; i < digestLength; ++i)
247 hexBytes.append(Integer.toHexString(digest[i] & 0xff));
249 // FIXME: use System.mapLibraryName?
250 // I'm thinking we should use that, plus a class specified
251 // via a property that determines lookup policy.
252 File soFile = new File(hexBytes + ".so");
253 if (soFile.isFile())
254 return loadSharedLibrary (loader, soFile.toString(), domain,
255 name);
257 File classFile = new File(hexBytes + ".class");
258 classFile.delete();
259 if (classFile.createNewFile() != true)
260 return null;
262 FileOutputStream f = new FileOutputStream (classFile);
263 // FIXME: race condition if bytes change... ?
264 f.write(data, offset, len);
266 // Invoke the compiler.
267 StringBuffer command = new StringBuffer(gcjJitCompiler);
268 command.append(" ");
269 command.append(classFile);
270 command.append(" ");
271 command.append(gcjJitCompilerOptions);
272 // These options are required.
273 command.append(" -findirect-dispatch -fjni -shared -fPIC -o ");
274 command.append(soFile);
275 Process p = Runtime.getRuntime().exec(command.toString());
277 // Read the process' stderr into a string.
278 StringBuffer err = new StringBuffer();
279 InputStreamReader stderr = new InputStreamReader (p.getErrorStream());
280 char[] inBuf = new char[500];
281 int bytesRead;
282 while ((bytesRead = stderr.read (inBuf)) != -1)
283 err.append(inBuf, 0, bytesRead);
285 if (p.waitFor() != 0)
287 // FIXME: we could log err.toString() somewhere...
288 return null;
291 return loadSharedLibrary(loader, soFile.toString(), domain, name);
293 catch (Exception _)
295 return null;
300 * Compile the class named by <code>oneClass</code>.
302 * @param oneClass the class to compile
303 * @return <code>false</code> if no compiler is available or
304 * compilation failed, <code>true</code> if compilation succeeded
305 * @throws NullPointerException if oneClass is null
307 public static boolean compileClass(Class oneClass)
309 // Never succeed.
310 return false;
314 * Compile the classes whose name matches <code>classNames</code>.
316 * @param classNames the name of classes to compile
317 * @return <code>false</code> if no compiler is available or
318 * compilation failed, <code>true</code> if compilation succeeded
319 * @throws NullPointerException if classNames is null
321 public static boolean compileClasses(String classNames)
323 // Note the incredibly lame interface. Always fail.
324 return false;
328 * This method examines the argument and performs an operation
329 * according to the compilers documentation. No specific operation
330 * is required.
332 * @param arg a compiler-specific argument
333 * @return a compiler-specific value, including null
334 * @throws NullPointerException if the compiler doesn't like a null arg
336 public static Object command(Object arg)
338 // Our implementation defines this to a no-op.
339 return null;
343 * Calling <code>Compiler.enable()</code> will cause the compiler
344 * to resume operation if it was previously disabled; provided that a
345 * compiler even exists.
347 public static void enable()
349 useCompiler = true;
353 * Calling <code>Compiler.disable()</code> will cause the compiler
354 * to be suspended; provided that a compiler even exists.
356 public static void disable()
358 useCompiler = false;