* src/vm/jit/replace.c (replace_find_replacement_point_for_pc): Added assertion.
[cacao.git] / src / lib / vm / reference / 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
63 /**
64  * java.lang.VMClassLoader is a package-private helper for VMs to implement
65  * on behalf of java.lang.ClassLoader.
66  *
67  * @author John Keiser
68  * @author Mark Wielaard (mark@klomp.org)
69  * @author Eric Blake (ebb9@email.byu.edu)
70  */
71 final class VMClassLoader
72 {
73
74
75   /** packages loaded by the bootstrap class loader */
76   static final HashMap definedPackages = new HashMap();
77
78   /** jars from property java.boot.class.path */
79   static final HashMap bootjars = new HashMap();
80   
81
82   /**
83    * Converts the array string of native package names to
84    * Packages. The packages are then put into the
85    * definedPackages hashMap
86    */
87   static
88   {
89     String[] packages = getBootPackages();
90     
91     if( packages != null)
92       {
93         String specName = 
94               SystemProperties.getProperty("java.specification.name");
95         String vendor =
96               SystemProperties.getProperty("java.specification.vendor");
97         String version =
98               SystemProperties.getProperty("java.specification.version");
99         
100         Package p;
101               
102         for(int i = 0; i < packages.length; i++)
103           {
104             p = new Package(packages[i],
105                   specName,
106                   vendor,
107                   version,
108                   "GNU Classpath",
109                   "GNU",
110                   Configuration.CLASSPATH_VERSION,
111                   null,
112                   null);
113
114             definedPackages.put(packages[i], p);
115           }
116       }
117   }
118
119   
120   /**
121    * Helper to define a class using a string of bytes. This assumes that
122    * the security checks have already been performed, if necessary.
123    *
124    * Implementations of this method are advised to consider the
125    * situation where user code modifies the byte array after it has
126    * been passed to defineClass.  This can be handled by making a
127    * private copy of the array, or arranging to only read any given
128    * byte a single time.
129    *
130    * @param name the name to give the class, or null if unknown
131    * @param data the data representing the classfile, in classfile format
132    * @param offset the offset into the data where the classfile starts
133    * @param len the length of the classfile data in the array
134    * @param pd the protection domain
135    * @return the class that was defined
136    * @throws ClassFormatError if data is not in proper classfile format
137    */
138   static final native Class defineClass(ClassLoader cl, String name,
139                                  byte[] data, int offset, int len,
140                                  ProtectionDomain pd)
141     throws ClassFormatError;
142
143   /**
144    * Helper to resolve all references to other classes from this class.
145    *
146    * @param c the class to resolve
147    */
148   static final native void resolveClass(Class c);
149
150   /**
151    * Helper to load a class from the bootstrap class loader.
152    *
153    * @param name the class name to load
154    * @param resolve whether to resolve it
155    * @return the class, loaded by the bootstrap classloader or null
156    * if the class wasn't found. Returning null is equivalent to throwing
157    * a ClassNotFoundException (but a possible performance optimization).
158    */
159   static final native Class loadClass(String name, boolean resolve)
160     throws ClassNotFoundException;
161
162   /**
163    * Helper to load a resource from the bootstrap class loader.
164    *
165    * @param name the resource to find
166    * @return the URL to the resource
167    */
168   static URL getResource(String name)
169   {
170     Enumeration e = getResources(name);
171     if (e.hasMoreElements())
172       return (URL)e.nextElement();
173     return null;
174   }
175   /**
176    * Helper to get a list of resources from the bootstrap class loader.
177    *
178    * @param name the resource to find
179    * @return an enumeration of resources
180    */
181   static Enumeration getResources(String name)
182   {
183 //     StringTokenizer st = new StringTokenizer(
184 //       SystemProperties.getProperty("java.boot.class.path", "."),
185 //       File.pathSeparator);
186 //     Vector v = new Vector();
187 //     while (st.hasMoreTokens())
188 //       {
189 //      File file = new File(st.nextToken());
190 //      if (file.isDirectory())
191 //        {
192 //          try
193 //            {
194 //                 File f = new File(file, name);
195 //                 if (!f.exists()) continue;
196 //                 v.add(new URL("file://" + f.getAbsolutePath()));
197 //            }
198 //          catch (MalformedURLException e)
199 //            {
200 //              throw new Error(e);
201 //            }
202 //        }
203 //      else if (file.isFile())
204 //        {
205 //          ZipFile zip;
206 //             synchronized(bootjars)
207 //               {
208 //                 zip = (ZipFile) bootjars.get(file.getName());
209 //               }
210 //             if(zip == null)
211 //               {
212 //                 try
213 //                {
214 //                     zip = new ZipFile(file);
215 //                     synchronized(bootjars)
216 //                       {
217 //                         bootjars.put(file.getName(), zip);
218 //                       }
219 //                }
220 //              catch (IOException e)
221 //                {
222 //                  continue;
223 //                }
224 //               }
225 //          String zname = name.startsWith("/") ? name.substring(1) : name;
226 //          if (zip.getEntry(zname) == null)
227 //            continue;
228 //          try
229 //            {
230 //              v.add(new URL("jar:file://"
231 //                + file.getAbsolutePath() + "!/" + zname));
232 //            }
233 //          catch (MalformedURLException e)
234 //            {
235 //              throw new Error(e);
236 //            }
237 //        }
238 //       }
239 //     return v.elements();
240 //   }
241     Vector urls = nativeGetResources(name);
242     Vector v = new Vector();
243     for (Enumeration en = urls.elements(); en.hasMoreElements();)
244       {
245         try
246           {
247             v.add(new URL((String) en.nextElement()));
248           }
249         catch (MalformedURLException e)
250           {
251             throw new Error(e);
252           }
253       }
254     return v.elements();
255   }
256
257   private native static final Vector nativeGetResources(String name);
258
259
260   /**
261    * Returns a String[] of native package names. The default
262    * implementation tries to load a list of package from
263    * the META-INF/INDEX.LIST file in the boot jar file.
264    * If not found or if any exception is raised, it returns
265    * an empty array. You may decide this needs native help.
266    */
267   private static String[] getBootPackages()
268   {
269     try
270       {
271         Enumeration indexListEnumeration = getResources("META-INF/INDEX.LIST");
272         Set packageSet = new HashSet();
273
274         while (indexListEnumeration.hasMoreElements())
275           {
276             try
277               {
278                 String line;
279                 int lineToSkip = 3;
280                 BufferedReader reader = new BufferedReader(
281                                                            new InputStreamReader(
282                                                                                  ((URL) indexListEnumeration.nextElement()).openStream()));
283                 while ((line = reader.readLine()) != null)
284                   {
285                     if (lineToSkip == 0)
286                       {
287                         if (line.length() == 0)
288                           lineToSkip = 1;
289                         else
290                           packageSet.add(line.replace('/', '.'));
291                       }
292                     else
293                       lineToSkip--;
294                   }
295                 reader.close();
296               }
297             catch (IOException e)
298               {
299                 // Empty catch block on purpose
300               }
301           }
302         return (String[]) packageSet.toArray(new String[packageSet.size()]);
303       }
304     catch (Exception e)
305       {
306         return new String[0];
307       }
308   }
309
310
311   /**
312    * Helper to get a package from the bootstrap class loader.
313    *
314    * @param name the name to find
315    * @return the named package, if it exists
316    */
317   static Package getPackage(String name)
318   {
319     return (Package)definedPackages.get(name);
320   }
321
322
323   
324   /**
325    * Helper to get all packages from the bootstrap class loader.  
326    *
327    * @return all named packages, if any exist
328    */
329   static Package[] getPackages()
330   {
331     Package[] packages = new Package[definedPackages.size()];
332     definedPackages.values().toArray(packages);
333     return packages;
334   }
335
336   /**
337    * Helper for java.lang.Integer, Byte, etc to get the TYPE class
338    * at initialization time. The type code is one of the chars that
339    * represents the primitive type as in JNI.
340    *
341    * <ul>
342    * <li>'Z' - boolean</li>
343    * <li>'B' - byte</li>
344    * <li>'C' - char</li>
345    * <li>'D' - double</li>
346    * <li>'F' - float</li>
347    * <li>'I' - int</li>
348    * <li>'J' - long</li>
349    * <li>'S' - short</li>
350    * <li>'V' - void</li>
351    * </ul>
352    *
353    * @param type the primitive type
354    * @return a "bogus" class representing the primitive type
355    */
356   static final native Class getPrimitiveClass(char type);
357
358   /**
359    * The system default for assertion status. This is used for all system
360    * classes (those with a null ClassLoader), as well as the initial value for
361    * every ClassLoader's default assertion status.
362    *
363    * XXX - Not implemented yet; this requires native help.
364    *
365    * @return the system-wide default assertion status
366    */
367 //   static final boolean defaultAssertionStatus()
368 //   {
369 //     return true;
370 //   }
371   static native final boolean defaultAssertionStatus();
372
373   /**
374    * The system default for package assertion status. This is used for all
375    * ClassLoader's packageAssertionStatus defaults. It must be a map of
376    * package names to Boolean.TRUE or Boolean.FALSE, with the unnamed package
377    * represented as a null key.
378    *
379    * XXX - Not implemented yet; this requires native help.
380    *
381    * @return a (read-only) map for the default packageAssertionStatus
382    */
383   static final Map packageAssertionStatus()
384   {
385     return new HashMap();
386   }
387
388   /**
389    * The system default for class assertion status. This is used for all
390    * ClassLoader's classAssertionStatus defaults. It must be a map of
391    * class names to Boolean.TRUE or Boolean.FALSE
392    *
393    * XXX - Not implemented yet; this requires native help.
394    *
395    * @return a (read-only) map for the default classAssertionStatus
396    */
397   static final Map classAssertionStatus()
398   {
399     return new HashMap();
400   }
401
402   static ClassLoader getSystemClassLoader()
403   {
404     return ClassLoader.defaultGetSystemClassLoader();
405   }
406
407   /**
408    * Find the class if this class loader previously defined this class
409    * or if this class loader has been recorded as the initiating class loader
410    * for this class.
411    */
412   static native Class findLoadedClass(ClassLoader cl, String name);
413
414   /**
415    * The Instrumentation object created by the vm when agents are defined.
416    */
417   static final Instrumentation instrumenter = null;
418
419   /**
420    * Call the transformers of the possible Instrumentation object. This
421    * implementation assumes the instrumenter is a
422    * <code>InstrumentationImpl</code> object. VM implementors would
423    * have to redefine this method if they provide their own implementation
424    * of the <code>Instrumentation</code> interface.
425    *
426    * @param loader the initiating loader
427    * @param name the name of the class
428    * @param data the data representing the classfile, in classfile format
429    * @param offset the offset into the data where the classfile starts
430    * @param len the length of the classfile data in the array
431    * @param pd the protection domain
432    * @return the new data representing the classfile
433    */
434   static final Class defineClassWithTransformers(ClassLoader loader,
435       String name, byte[] data, int offset, int len, ProtectionDomain pd)
436   {
437     
438     if (instrumenter != null)
439       {
440         byte[] modifiedData = new byte[len];
441         System.arraycopy(data, offset, modifiedData, 0, len);
442         modifiedData =
443           ((InstrumentationImpl)instrumenter).callTransformers(loader, name,
444             null, pd, modifiedData);
445         
446         return defineClass(loader, name, modifiedData, 0, modifiedData.length,
447             pd);
448       }
449     else
450       {
451         return defineClass(loader, name, data, offset, len, pd);
452       }
453   }
454 }