* configure.ac (AC_CHECK_ENABLE_ASSERTION): Added
[cacao.git] / src / lib / gnu / java / lang / VMClassLoader.java
1 /* VMClassLoader.java -- Reference implementation of native interface
2    required by ClassLoader
3    Copyright (C) 1998, 2001, 2002, 2004, 2005, 2006 Free Software Foundation
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING.  If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library.  Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module.  An independent module is a module which is not derived from
34 or based on this library.  If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so.  If you do not wish to do so, delete this
37 exception statement from your version. */
38
39
40 package java.lang;
41
42 import gnu.classpath.Configuration;
43 import gnu.classpath.SystemProperties;
44 import gnu.java.lang.InstrumentationImpl;
45
46 import java.io.BufferedReader;
47 import java.io.File;
48 import java.io.IOException;
49 import java.io.InputStreamReader;
50 import java.lang.instrument.Instrumentation;
51 import java.net.MalformedURLException;
52 import java.net.URL;
53 import java.security.ProtectionDomain;
54 import java.util.Enumeration;
55 import java.util.HashMap;
56 import java.util.HashSet;
57 import java.util.Map;
58 import java.util.Set;
59 import java.util.StringTokenizer;
60 import java.util.Vector;
61 import java.util.zip.ZipFile;
62 import java.util.Collections;
63 import java.lang.Boolean;
64
65 /**
66  * java.lang.VMClassLoader is a package-private helper for VMs to implement
67  * on behalf of java.lang.ClassLoader.
68  *
69  * @author John Keiser
70  * @author Mark Wielaard (mark@klomp.org)
71  * @author Eric Blake (ebb9@email.byu.edu)
72  */
73 final class VMClassLoader
74 {
75
76
77   /** packages loaded by the bootstrap class loader */
78   static final HashMap definedPackages = new HashMap();
79
80   /** jars from property java.boot.class.path */
81   static final HashMap bootjars = new HashMap();
82   
83
84   /**
85    * Converts the array string of native package names to
86    * Packages. The packages are then put into the
87    * definedPackages hashMap
88    */
89   static
90   {
91     String[] packages = getBootPackages();
92     
93     if( packages != null)
94       {
95         String specName = 
96               SystemProperties.getProperty("java.specification.name");
97         String vendor =
98               SystemProperties.getProperty("java.specification.vendor");
99         String version =
100               SystemProperties.getProperty("java.specification.version");
101         
102         Package p;
103               
104         for(int i = 0; i < packages.length; i++)
105           {
106             p = new Package(packages[i],
107                   specName,
108                   vendor,
109                   version,
110                   "GNU Classpath",
111                   "GNU",
112                   Configuration.CLASSPATH_VERSION,
113                   null,
114                   null);
115
116             definedPackages.put(packages[i], p);
117           }
118       }
119   }
120
121   
122   /**
123    * Helper to define a class using a string of bytes. This assumes that
124    * the security checks have already been performed, if necessary.
125    *
126    * Implementations of this method are advised to consider the
127    * situation where user code modifies the byte array after it has
128    * been passed to defineClass.  This can be handled by making a
129    * private copy of the array, or arranging to only read any given
130    * byte a single time.
131    *
132    * @param name the name to give the class, or null if unknown
133    * @param data the data representing the classfile, in classfile format
134    * @param offset the offset into the data where the classfile starts
135    * @param len the length of the classfile data in the array
136    * @param pd the protection domain
137    * @return the class that was defined
138    * @throws ClassFormatError if data is not in proper classfile format
139    */
140   static final native Class defineClass(ClassLoader cl, String name,
141                                  byte[] data, int offset, int len,
142                                  ProtectionDomain pd)
143     throws ClassFormatError;
144
145   /**
146    * Helper to resolve all references to other classes from this class.
147    *
148    * @param c the class to resolve
149    */
150   static final native void resolveClass(Class c);
151
152   /**
153    * Helper to load a class from the bootstrap class loader.
154    *
155    * @param name the class name to load
156    * @param resolve whether to resolve it
157    * @return the class, loaded by the bootstrap classloader or null
158    * if the class wasn't found. Returning null is equivalent to throwing
159    * a ClassNotFoundException (but a possible performance optimization).
160    */
161   static final native Class loadClass(String name, boolean resolve)
162     throws ClassNotFoundException;
163
164   /**
165    * Helper to load a resource from the bootstrap class loader.
166    *
167    * @param name the resource to find
168    * @return the URL to the resource
169    */
170   static URL getResource(String name)
171   {
172     Enumeration e = getResources(name);
173     if (e.hasMoreElements())
174       return (URL)e.nextElement();
175     return null;
176   }
177   /**
178    * Helper to get a list of resources from the bootstrap class loader.
179    *
180    * @param name the resource to find
181    * @return an enumeration of resources
182    */
183   static Enumeration getResources(String name)
184   {
185 //     StringTokenizer st = new StringTokenizer(
186 //       SystemProperties.getProperty("java.boot.class.path", "."),
187 //       File.pathSeparator);
188 //     Vector v = new Vector();
189 //     while (st.hasMoreTokens())
190 //       {
191 //      File file = new File(st.nextToken());
192 //      if (file.isDirectory())
193 //        {
194 //          try
195 //            {
196 //                 File f = new File(file, name);
197 //                 if (!f.exists()) continue;
198 //                 v.add(new URL("file://" + f.getAbsolutePath()));
199 //            }
200 //          catch (MalformedURLException e)
201 //            {
202 //              throw new Error(e);
203 //            }
204 //        }
205 //      else if (file.isFile())
206 //        {
207 //          ZipFile zip;
208 //             synchronized(bootjars)
209 //               {
210 //                 zip = (ZipFile) bootjars.get(file.getName());
211 //               }
212 //             if(zip == null)
213 //               {
214 //                 try
215 //                {
216 //                     zip = new ZipFile(file);
217 //                     synchronized(bootjars)
218 //                       {
219 //                         bootjars.put(file.getName(), zip);
220 //                       }
221 //                }
222 //              catch (IOException e)
223 //                {
224 //                  continue;
225 //                }
226 //               }
227 //          String zname = name.startsWith("/") ? name.substring(1) : name;
228 //          if (zip.getEntry(zname) == null)
229 //            continue;
230 //          try
231 //            {
232 //              v.add(new URL("jar:file://"
233 //                + file.getAbsolutePath() + "!/" + zname));
234 //            }
235 //          catch (MalformedURLException e)
236 //            {
237 //              throw new Error(e);
238 //            }
239 //        }
240 //       }
241 //     return v.elements();
242 //   }
243     Vector urls = nativeGetResources(name);
244     Vector v = new Vector();
245     for (Enumeration en = urls.elements(); en.hasMoreElements();)
246       {
247         try
248           {
249             v.add(new URL((String) en.nextElement()));
250           }
251         catch (MalformedURLException e)
252           {
253             throw new Error(e);
254           }
255       }
256     return v.elements();
257   }
258
259   private native static final Vector nativeGetResources(String name);
260
261
262   /**
263    * Returns a String[] of native package names. The default
264    * implementation tries to load a list of package from
265    * the META-INF/INDEX.LIST file in the boot jar file.
266    * If not found or if any exception is raised, it returns
267    * an empty array. You may decide this needs native help.
268    */
269   private static String[] getBootPackages()
270   {
271     try
272       {
273         Enumeration indexListEnumeration = getResources("META-INF/INDEX.LIST");
274         Set packageSet = new HashSet();
275
276         while (indexListEnumeration.hasMoreElements())
277           {
278             try
279               {
280                 String line;
281                 int lineToSkip = 3;
282                 BufferedReader reader = new BufferedReader(
283                                                            new InputStreamReader(
284                                                                                  ((URL) indexListEnumeration.nextElement()).openStream()));
285                 while ((line = reader.readLine()) != null)
286                   {
287                     if (lineToSkip == 0)
288                       {
289                         if (line.length() == 0)
290                           lineToSkip = 1;
291                         else
292                           packageSet.add(line.replace('/', '.'));
293                       }
294                     else
295                       lineToSkip--;
296                   }
297                 reader.close();
298               }
299             catch (IOException e)
300               {
301                 // Empty catch block on purpose
302               }
303           }
304         return (String[]) packageSet.toArray(new String[packageSet.size()]);
305       }
306     catch (Exception e)
307       {
308         return new String[0];
309       }
310   }
311
312
313   /**
314    * Helper to get a package from the bootstrap class loader.
315    *
316    * @param name the name to find
317    * @return the named package, if it exists
318    */
319   static Package getPackage(String name)
320   {
321     return (Package)definedPackages.get(name);
322   }
323
324
325   
326   /**
327    * Helper to get all packages from the bootstrap class loader.  
328    *
329    * @return all named packages, if any exist
330    */
331   static Package[] getPackages()
332   {
333     Package[] packages = new Package[definedPackages.size()];
334     definedPackages.values().toArray(packages);
335     return packages;
336   }
337
338   /**
339    * Helper for java.lang.Integer, Byte, etc to get the TYPE class
340    * at initialization time. The type code is one of the chars that
341    * represents the primitive type as in JNI.
342    *
343    * <ul>
344    * <li>'Z' - boolean</li>
345    * <li>'B' - byte</li>
346    * <li>'C' - char</li>
347    * <li>'D' - double</li>
348    * <li>'F' - float</li>
349    * <li>'I' - int</li>
350    * <li>'J' - long</li>
351    * <li>'S' - short</li>
352    * <li>'V' - void</li>
353    * </ul>
354    *
355    * @param type the primitive type
356    * @return a "bogus" class representing the primitive type
357    */
358   static final native Class getPrimitiveClass(char type);
359
360   /**
361    * The system default for assertion status. This is used for all system
362    * classes (those with a null ClassLoader), as well as the initial value for
363    * every ClassLoader's default assertion status.
364    *
365    * @return the system-wide default assertion status
366    */
367   static native final boolean defaultAssertionStatus();
368
369   static native final boolean defaultUserAssertionStatus();
370
371
372   static final Map packageAssertionMap = 
373     Collections.unmodifiableMap(packageAssertionStatus0(Boolean.TRUE, Boolean.FALSE));
374   
375   static native final Map packageAssertionStatus0(Boolean jtrue, Boolean jfalse);
376   /**
377    * The system default for package assertion status. This is used for all
378    * ClassLoader's packageAssertionStatus defaults. It must be a map of
379    * package names to Boolean.TRUE or Boolean.FALSE, with the unnamed package
380    * represented as a null key.
381    *
382    * @return a (read-only) map for the default packageAssertionStatus
383    */
384    
385   static final Map packageAssertionStatus() {
386     return packageAssertionMap;
387   }
388
389   static final Map classAssertionMap = 
390     Collections.unmodifiableMap(classAssertionStatus0(Boolean.TRUE, Boolean.FALSE));
391   
392   static native final Map classAssertionStatus0(Boolean jtrue, Boolean jfalse);
393
394   /**
395    * The system default for class assertion status. This is used for all
396    * ClassLoader's classAssertionStatus defaults. It must be a map of
397    * class names to Boolean.TRUE or Boolean.FALSE
398    *
399    * @return a (read-only) map for the default classAssertionStatus
400    */
401   static final Map classAssertionStatus() {
402     return classAssertionMap;
403   }
404   
405   static ClassLoader getSystemClassLoader()
406   {
407     return ClassLoader.defaultGetSystemClassLoader();
408   }
409
410   /**
411    * Find the class if this class loader previously defined this class
412    * or if this class loader has been recorded as the initiating class loader
413    * for this class.
414    */
415   static native Class findLoadedClass(ClassLoader cl, String name);
416
417   /**
418    * The Instrumentation object created by the vm when agents are defined.
419    */
420   static final Instrumentation instrumenter = null;
421
422   /**
423    * Call the transformers of the possible Instrumentation object. This
424    * implementation assumes the instrumenter is a
425    * <code>InstrumentationImpl</code> object. VM implementors would
426    * have to redefine this method if they provide their own implementation
427    * of the <code>Instrumentation</code> interface.
428    *
429    * @param loader the initiating loader
430    * @param name the name of the class
431    * @param data the data representing the classfile, in classfile format
432    * @param offset the offset into the data where the classfile starts
433    * @param len the length of the classfile data in the array
434    * @param pd the protection domain
435    * @return the new data representing the classfile
436    */
437   static final Class defineClassWithTransformers(ClassLoader loader,
438       String name, byte[] data, int offset, int len, ProtectionDomain pd)
439   {
440     
441     if (instrumenter != null)
442       {
443         byte[] modifiedData = new byte[len];
444         System.arraycopy(data, offset, modifiedData, 0, len);
445         modifiedData =
446           ((InstrumentationImpl)instrumenter).callTransformers(loader, name,
447             null, pd, modifiedData);
448         
449         return defineClass(loader, name, modifiedData, 0, modifiedData.length,
450             pd);
451       }
452     else
453       {
454         return defineClass(loader, name, data, offset, len, pd);
455       }
456   }
457 }