OSDN Git Service

Merged gcj-eclipse branch to trunk.
[pf3gnuchains/gcc-fork.git] / libjava / classpath / java / lang / System.java
1 /* System.java -- useful methods to interface with the system
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3    Free Software Foundation, Inc.
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.SystemProperties;
43 import gnu.classpath.VMStackWalker;
44
45 import java.io.InputStream;
46 import java.io.PrintStream;
47 import java.util.AbstractCollection;
48 import java.util.Collection;
49 import java.util.Collections;
50 import java.util.HashMap;
51 import java.util.Iterator;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Set;
55 import java.util.Properties;
56 import java.util.PropertyPermission;
57
58 /**
59  * System represents system-wide resources; things that represent the
60  * general environment.  As such, all methods are static.
61  *
62  * @author John Keiser
63  * @author Eric Blake (ebb9@email.byu.edu)
64  * @since 1.0
65  * @status still missing 1.4 functionality
66  */
67 public final class System
68 {
69   // WARNING: System is a CORE class in the bootstrap cycle. See the comments
70   // in vm/reference/java/lang/Runtime for implications of this fact.
71
72   /**
73    * The standard InputStream. This is assigned at startup and starts its
74    * life perfectly valid. Although it is marked final, you can change it
75    * using {@link #setIn(InputStream)} through some hefty VM magic.
76    *
77    * <p>This corresponds to the C stdin and C++ cin variables, which
78    * typically input from the keyboard, but may be used to pipe input from
79    * other processes or files.  That should all be transparent to you,
80    * however.
81    */
82   public static final InputStream in = VMSystem.makeStandardInputStream();
83
84   /**
85    * The standard output PrintStream.  This is assigned at startup and
86    * starts its life perfectly valid. Although it is marked final, you can
87    * change it using {@link #setOut(PrintStream)} through some hefty VM magic.
88    *
89    * <p>This corresponds to the C stdout and C++ cout variables, which
90    * typically output normal messages to the screen, but may be used to pipe
91    * output to other processes or files.  That should all be transparent to
92    * you, however.
93    */
94   public static final PrintStream out = VMSystem.makeStandardOutputStream();
95
96   /**
97    * The standard output PrintStream.  This is assigned at startup and
98    * starts its life perfectly valid. Although it is marked final, you can
99    * change it using {@link #setErr(PrintStream)} through some hefty VM magic.
100    *
101    * <p>This corresponds to the C stderr and C++ cerr variables, which
102    * typically output error messages to the screen, but may be used to pipe
103    * output to other processes or files.  That should all be transparent to
104    * you, however.
105    */
106   public static final PrintStream err = VMSystem.makeStandardErrorStream();
107
108   /**
109    * A cached copy of the environment variable map.
110    */
111   private static Map<String,String> environmentMap;
112
113   /**
114    * This class is uninstantiable.
115    */
116   private System()
117   {
118   }
119
120   /**
121    * Set {@link #in} to a new InputStream. This uses some VM magic to change
122    * a "final" variable, so naturally there is a security check,
123    * <code>RuntimePermission("setIO")</code>.
124    *
125    * @param in the new InputStream
126    * @throws SecurityException if permission is denied
127    * @since 1.1
128    */
129   public static void setIn(InputStream in)
130   {
131     SecurityManager sm = SecurityManager.current; // Be thread-safe.
132     if (sm != null)
133       sm.checkPermission(new RuntimePermission("setIO"));
134     
135     VMSystem.setIn(in);
136   }
137
138   /**
139    * Set {@link #out} to a new PrintStream. This uses some VM magic to change
140    * a "final" variable, so naturally there is a security check,
141    * <code>RuntimePermission("setIO")</code>.
142    *
143    * @param out the new PrintStream
144    * @throws SecurityException if permission is denied
145    * @since 1.1
146    */
147   public static void setOut(PrintStream out)
148   {
149     SecurityManager sm = SecurityManager.current; // Be thread-safe.
150     if (sm != null)
151       sm.checkPermission(new RuntimePermission("setIO"));    
152     VMSystem.setOut(out);
153   }
154
155   /**
156    * Set {@link #err} to a new PrintStream. This uses some VM magic to change
157    * a "final" variable, so naturally there is a security check,
158    * <code>RuntimePermission("setIO")</code>.
159    *
160    * @param err the new PrintStream
161    * @throws SecurityException if permission is denied
162    * @since 1.1
163    */
164   public static void setErr(PrintStream err)
165   {
166     SecurityManager sm = SecurityManager.current; // Be thread-safe.
167     if (sm != null)
168       sm.checkPermission(new RuntimePermission("setIO"));
169     VMSystem.setErr(err);
170   }
171
172   /**
173    * Set the current SecurityManager. If a security manager already exists,
174    * then <code>RuntimePermission("setSecurityManager")</code> is checked
175    * first. Since this permission is denied by the default security manager,
176    * setting the security manager is often an irreversible action.
177    *
178    * <STRONG>Spec Note:</STRONG> Don't ask me, I didn't write it.  It looks
179    * pretty vulnerable; whoever gets to the gate first gets to set the policy.
180    * There is probably some way to set the original security manager as a
181    * command line argument to the VM, but I don't know it.
182    *
183    * @param sm the new SecurityManager
184    * @throws SecurityException if permission is denied
185    */
186   public static synchronized void setSecurityManager(SecurityManager sm)
187   {
188     // Implementation note: the field lives in SecurityManager because of
189     // bootstrap initialization issues. This method is synchronized so that
190     // no other thread changes it to null before this thread makes the change.
191     if (SecurityManager.current != null)
192       SecurityManager.current.checkPermission
193         (new RuntimePermission("setSecurityManager"));
194
195     // java.security.Security's class initialiser loads and parses the
196     // policy files.  If it hasn't been run already it will be run
197     // during the first permission check.  That initialisation will
198     // fail if a very restrictive security manager is in force, so we
199     // preload it here.
200     if (SecurityManager.current == null)
201       {
202         try
203           {
204             Class.forName("java.security.Security");
205           }
206         catch (ClassNotFoundException e)
207           {
208           }
209       }
210     
211     SecurityManager.current = sm;
212   }
213
214   /**
215    * Get the current SecurityManager. If the SecurityManager has not been
216    * set yet, then this method returns null.
217    *
218    * @return the current SecurityManager, or null
219    */
220   public static SecurityManager getSecurityManager()
221   {
222     return SecurityManager.current;
223   }
224
225   /**
226    * Get the current time, measured in the number of milliseconds from the
227    * beginning of Jan. 1, 1970. This is gathered from the system clock, with
228    * any attendant incorrectness (it may be timezone dependent).
229    *
230    * @return the current time
231    * @see java.util.Date
232    */
233   public static long currentTimeMillis()
234   {
235     return VMSystem.currentTimeMillis();
236   }
237   
238   /** 
239    * <p>
240    * Returns the current value of a nanosecond-precise system timer.
241    * The value of the timer is an offset relative to some arbitrary fixed
242    * time, which may be in the future (making the value negative).  This
243    * method is useful for timing events where nanosecond precision is
244    * required.  This is achieved by calling this method before and after the
245    * event, and taking the difference betweent the two times:
246    * </p>
247    * <p>
248    * <code>long startTime = System.nanoTime();</code><br />
249    * <code>... <emph>event code</emph> ...</code><br />
250    * <code>long endTime = System.nanoTime();</code><br />
251    * <code>long duration = endTime - startTime;</code><br />
252    * </p>
253    * <p>
254    * Note that the value is only nanosecond-precise, and not accurate; there
255    * is no guarantee that the difference between two values is really a
256    * nanosecond.  Also, the value is prone to overflow if the offset
257    * exceeds 2^63.
258    * </p>
259    *
260    * @return the time of a system timer in nanoseconds.
261    * @since 1.5 
262    */
263   public static long nanoTime()
264   {
265     return VMSystem.nanoTime();
266   }
267
268   /**
269    * Copy one array onto another from <code>src[srcStart]</code> ...
270    * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ...
271    * <code>dest[destStart+len-1]</code>. First, the arguments are validated:
272    * neither array may be null, they must be of compatible types, and the
273    * start and length must fit within both arrays. Then the copying starts,
274    * and proceeds through increasing slots.  If src and dest are the same
275    * array, this will appear to copy the data to a temporary location first.
276    * An ArrayStoreException in the middle of copying will leave earlier
277    * elements copied, but later elements unchanged.
278    *
279    * @param src the array to copy elements from
280    * @param srcStart the starting position in src
281    * @param dest the array to copy elements to
282    * @param destStart the starting position in dest
283    * @param len the number of elements to copy
284    * @throws NullPointerException if src or dest is null
285    * @throws ArrayStoreException if src or dest is not an array, if they are
286    *         not compatible array types, or if an incompatible runtime type
287    *         is stored in dest
288    * @throws IndexOutOfBoundsException if len is negative, or if the start or
289    *         end copy position in either array is out of bounds
290    */
291   public static void arraycopy(Object src, int srcStart,
292                                Object dest, int destStart, int len)
293   {
294     VMSystem.arraycopy(src, srcStart, dest, destStart, len);
295   }
296
297   /**
298    * Get a hash code computed by the VM for the Object. This hash code will
299    * be the same as Object's hashCode() method.  It is usually some
300    * convolution of the pointer to the Object internal to the VM.  It
301    * follows standard hash code rules, in that it will remain the same for a
302    * given Object for the lifetime of that Object.
303    *
304    * @param o the Object to get the hash code for
305    * @return the VM-dependent hash code for this Object
306    * @since 1.1
307    */
308   public static int identityHashCode(Object o)
309   {
310     return VMSystem.identityHashCode(o);
311   }
312
313   /**
314    * Get all the system properties at once. A security check may be performed,
315    * <code>checkPropertiesAccess</code>. Note that a security manager may
316    * allow getting a single property, but not the entire group.
317    *
318    * <p>The required properties include:
319    * <dl>
320    * <dt>java.version</dt>         <dd>Java version number</dd>
321    * <dt>java.vendor</dt>          <dd>Java vendor specific string</dd>
322    * <dt>java.vendor.url</dt>      <dd>Java vendor URL</dd>
323    * <dt>java.home</dt>            <dd>Java installation directory</dd>
324    * <dt>java.vm.specification.version</dt> <dd>VM Spec version</dd>
325    * <dt>java.vm.specification.vendor</dt>  <dd>VM Spec vendor</dd>
326    * <dt>java.vm.specification.name</dt>    <dd>VM Spec name</dd>
327    * <dt>java.vm.version</dt>      <dd>VM implementation version</dd>
328    * <dt>java.vm.vendor</dt>       <dd>VM implementation vendor</dd>
329    * <dt>java.vm.name</dt>         <dd>VM implementation name</dd>
330    * <dt>java.specification.version</dt>    <dd>Java Runtime Environment version</dd>
331    * <dt>java.specification.vendor</dt>     <dd>Java Runtime Environment vendor</dd>
332    * <dt>java.specification.name</dt>       <dd>Java Runtime Environment name</dd>
333    * <dt>java.class.version</dt>   <dd>Java class version number</dd>
334    * <dt>java.class.path</dt>      <dd>Java classpath</dd>
335    * <dt>java.library.path</dt>    <dd>Path for finding Java libraries</dd>
336    * <dt>java.io.tmpdir</dt>       <dd>Default temp file path</dd>
337    * <dt>java.compiler</dt>        <dd>Name of JIT to use</dd>
338    * <dt>java.ext.dirs</dt>        <dd>Java extension path</dd>
339    * <dt>os.name</dt>              <dd>Operating System Name</dd>
340    * <dt>os.arch</dt>              <dd>Operating System Architecture</dd>
341    * <dt>os.version</dt>           <dd>Operating System Version</dd>
342    * <dt>file.separator</dt>       <dd>File separator ("/" on Unix)</dd>
343    * <dt>path.separator</dt>       <dd>Path separator (":" on Unix)</dd>
344    * <dt>line.separator</dt>       <dd>Line separator ("\n" on Unix)</dd>
345    * <dt>user.name</dt>            <dd>User account name</dd>
346    * <dt>user.home</dt>            <dd>User home directory</dd>
347    * <dt>user.dir</dt>             <dd>User's current working directory</dd>
348    * </dl>
349    *
350    * In addition, gnu defines several other properties, where ? stands for
351    * each character in '0' through '9':
352    * <dl>
353    * <dt>gnu.classpath.home</dt>         <dd>Path to the classpath libraries.</dd>
354    * <dt>gnu.classpath.version</dt>      <dd>Version of the classpath libraries.</dd>
355    * <dt>gnu.classpath.vm.shortname</dt> <dd>Succinct version of the VM name;
356    *     used for finding property files in file system</dd>
357    * <dt>gnu.classpath.home.url</dt>     <dd> Base URL; used for finding
358    *     property files in file system</dd>
359    * <dt>gnu.cpu.endian</dt>             <dd>big or little</dd>
360    * <dt>gnu.java.io.encoding_scheme_alias.iso-8859-?</dt>   <dd>8859_?</dd>
361    * <dt>gnu.java.io.encoding_scheme_alias.iso8859_?</dt>    <dd>8859_?</dd>
362    * <dt>gnu.java.io.encoding_scheme_alias.iso-latin-_?</dt> <dd>8859_?</dd>
363    * <dt>gnu.java.io.encoding_scheme_alias.latin?</dt>       <dd>8859_?</dd>
364    * <dt>gnu.java.io.encoding_scheme_alias.utf-8</dt>        <dd>UTF8</dd>
365    * <dt>gnu.javax.print.server</dt>     <dd>Hostname of external CUPS server.</dd>
366    * </dl>
367    *
368    * @return the system properties, will never be null
369    * @throws SecurityException if permission is denied
370    */
371   public static Properties getProperties()
372   {
373     SecurityManager sm = SecurityManager.current; // Be thread-safe.
374     if (sm != null)
375       sm.checkPropertiesAccess();
376     return SystemProperties.getProperties();
377   }
378
379   /**
380    * Set all the system properties at once. A security check may be performed,
381    * <code>checkPropertiesAccess</code>. Note that a security manager may
382    * allow setting a single property, but not the entire group. An argument
383    * of null resets the properties to the startup default.
384    *
385    * @param properties the new set of system properties
386    * @throws SecurityException if permission is denied
387    */
388   public static void setProperties(Properties properties)
389   {
390     SecurityManager sm = SecurityManager.current; // Be thread-safe.
391     if (sm != null)
392       sm.checkPropertiesAccess();
393     SystemProperties.setProperties(properties);
394   }
395
396   /**
397    * Get a single system property by name. A security check may be performed,
398    * <code>checkPropertyAccess(key)</code>.
399    *
400    * @param key the name of the system property to get
401    * @return the property, or null if not found
402    * @throws SecurityException if permission is denied
403    * @throws NullPointerException if key is null
404    * @throws IllegalArgumentException if key is ""
405    */
406   public static String getProperty(String key)
407   {
408     SecurityManager sm = SecurityManager.current; // Be thread-safe.
409     if (sm != null)
410       sm.checkPropertyAccess(key);
411     if (key.length() == 0)
412       throw new IllegalArgumentException("key can't be empty");
413     return SystemProperties.getProperty(key);
414   }
415
416   /**
417    * Get a single system property by name. A security check may be performed,
418    * <code>checkPropertyAccess(key)</code>.
419    *
420    * @param key the name of the system property to get
421    * @param def the default
422    * @return the property, or def if not found
423    * @throws SecurityException if permission is denied
424    * @throws NullPointerException if key is null
425    * @throws IllegalArgumentException if key is ""
426    */
427   public static String getProperty(String key, String def)
428   {
429     SecurityManager sm = SecurityManager.current; // Be thread-safe.
430     if (sm != null)
431       sm.checkPropertyAccess(key);
432     // This handles both the null pointer exception and the illegal
433     // argument exception.
434     if (key.length() == 0)
435       throw new IllegalArgumentException("key can't be empty");
436     return SystemProperties.getProperty(key, def);
437   }
438
439   /**
440    * Set a single system property by name. A security check may be performed,
441    * <code>checkPropertyAccess(key, "write")</code>.
442    *
443    * @param key the name of the system property to set
444    * @param value the new value
445    * @return the previous value, or null
446    * @throws SecurityException if permission is denied
447    * @throws NullPointerException if key is null
448    * @throws IllegalArgumentException if key is ""
449    * @since 1.2
450    */
451   public static String setProperty(String key, String value)
452   {
453     SecurityManager sm = SecurityManager.current; // Be thread-safe.
454     if (sm != null)
455       sm.checkPermission(new PropertyPermission(key, "write"));
456     // This handles both the null pointer exception and the illegal
457     // argument exception.
458     if (key.length() == 0)
459       throw new IllegalArgumentException("key can't be empty");
460     return SystemProperties.setProperty(key, value);
461   }
462
463   /**
464    * Remove a single system property by name. A security check may be
465    * performed, <code>checkPropertyAccess(key, "write")</code>.
466    *
467    * @param key the name of the system property to remove
468    * @return the previous value, or null
469    * @throws SecurityException if permission is denied
470    * @throws NullPointerException if key is null
471    * @throws IllegalArgumentException if key is ""
472    * @since 1.5
473    */
474   public static String clearProperty(String key)
475   {
476     SecurityManager sm = SecurityManager.current; // Be thread-safe.
477     if (sm != null)
478       sm.checkPermission(new PropertyPermission(key, "write"));
479     // This handles both the null pointer exception and the illegal
480     // argument exception.
481     if (key.length() == 0)
482       throw new IllegalArgumentException("key can't be empty");
483     return SystemProperties.remove(key);
484   }
485
486   /**
487    * Gets the value of an environment variable.
488    *
489    * @param name the name of the environment variable
490    * @return the string value of the variable or null when the
491    *         environment variable is not defined.
492    * @throws NullPointerException
493    * @throws SecurityException if permission is denied
494    * @since 1.5
495    * @specnote This method was deprecated in some JDK releases, but
496    *           was restored in 1.5.
497    */
498   public static String getenv(String name)
499   {
500     if (name == null)
501       throw new NullPointerException();
502     SecurityManager sm = SecurityManager.current; // Be thread-safe.
503     if (sm != null)
504       sm.checkPermission(new RuntimePermission("getenv." + name));
505     return VMSystem.getenv(name);
506   }
507
508   /**
509    * <p>
510    * Returns an unmodifiable view of the system environment variables.
511    * If the underlying system does not support environment variables,
512    * an empty map is returned.
513    * </p>
514    * <p>
515    * The returned map is read-only and does not accept queries using
516    * null keys or values, or those of a type other than <code>String</code>.
517    * Attempts to modify the map will throw an
518    * <code>UnsupportedOperationException</code>, while attempts
519    * to pass in a null value will throw a
520    * <code>NullPointerException</code>.  Types other than <code>String</code>
521    * throw a <code>ClassCastException</code>.
522    * </p>
523    * <p>
524    * As the returned map is generated using data from the underlying
525    * platform, it may not comply with the <code>equals()</code>
526    * and <code>hashCode()</code> contracts.  It is also likely that
527    * the keys of this map will be case-sensitive.
528    * </p>
529    * <p>
530    * Use of this method may require a security check for the
531    * RuntimePermission "getenv.*".
532    * </p>
533    *
534    * @return a map of the system environment variables.
535    * @throws SecurityException if the checkPermission method of
536    *         an installed security manager prevents access to
537    *         the system environment variables.
538    * @since 1.5
539    */
540   public static Map<String, String> getenv()
541   {
542     SecurityManager sm = SecurityManager.current; // Be thread-safe.
543     if (sm != null)
544       sm.checkPermission(new RuntimePermission("getenv.*"));
545     if (environmentMap == null)
546       {
547         List<String> environ = (List<String>)VMSystem.environ();
548         Map<String,String> variables = new EnvironmentMap();
549         for (String pair : environ)
550           {
551             String[] parts = pair.split("=");
552             if (parts.length == 2)
553               variables.put(parts[0], parts[1]);
554             else
555               variables.put(parts[0], "");
556           }
557         environmentMap = Collections.unmodifiableMap(variables);
558       }
559     return environmentMap;
560   }
561
562   /**
563    * Terminate the Virtual Machine. This just calls
564    * <code>Runtime.getRuntime().exit(status)</code>, and never returns.
565    * Obviously, a security check is in order, <code>checkExit</code>.
566    *
567    * @param status the exit status; by convention non-zero is abnormal
568    * @throws SecurityException if permission is denied
569    * @see Runtime#exit(int)
570    */
571   public static void exit(int status)
572   {
573     Runtime.getRuntime().exit(status);
574   }
575
576   /**
577    * Calls the garbage collector. This is only a hint, and it is up to the
578    * implementation what this hint suggests, but it usually causes a
579    * best-effort attempt to reclaim unused memory from discarded objects.
580    * This calls <code>Runtime.getRuntime().gc()</code>.
581    *
582    * @see Runtime#gc()
583    */
584   public static void gc()
585   {
586     Runtime.getRuntime().gc();
587   }
588
589   /**
590    * Runs object finalization on pending objects. This is only a hint, and
591    * it is up to the implementation what this hint suggests, but it usually
592    * causes a best-effort attempt to run finalizers on all objects ready
593    * to be reclaimed. This calls
594    * <code>Runtime.getRuntime().runFinalization()</code>.
595    *
596    * @see Runtime#runFinalization()
597    */
598   public static void runFinalization()
599   {
600     Runtime.getRuntime().runFinalization();
601   }
602
603   /**
604    * Tell the Runtime whether to run finalization before exiting the
605    * JVM.  This is inherently unsafe in multi-threaded applications,
606    * since it can force initialization on objects which are still in use
607    * by live threads, leading to deadlock; therefore this is disabled by
608    * default. There may be a security check, <code>checkExit(0)</code>. This
609    * calls <code>Runtime.runFinalizersOnExit()</code>.
610    *
611    * @param finalizeOnExit whether to run finalizers on exit
612    * @throws SecurityException if permission is denied
613    * @see Runtime#runFinalizersOnExit(boolean)
614    * @since 1.1
615    * @deprecated never rely on finalizers to do a clean, thread-safe,
616    *             mop-up from your code
617    */
618   public static void runFinalizersOnExit(boolean finalizeOnExit)
619   {
620     Runtime.runFinalizersOnExit(finalizeOnExit);
621   }
622
623   /**
624    * Load a code file using its explicit system-dependent filename. A security
625    * check may be performed, <code>checkLink</code>. This just calls
626    * <code>Runtime.getRuntime().load(filename)</code>.
627    *
628    * <p>
629    * The library is loaded using the class loader associated with the
630    * class associated with the invoking method.
631    *
632    * @param filename the code file to load
633    * @throws SecurityException if permission is denied
634    * @throws UnsatisfiedLinkError if the file cannot be loaded
635    * @see Runtime#load(String)
636    */
637   public static void load(String filename)
638   {
639     Runtime.getRuntime().load(filename, VMStackWalker.getCallingClassLoader());
640   }
641
642   /**
643    * Load a library using its explicit system-dependent filename. A security
644    * check may be performed, <code>checkLink</code>. This just calls
645    * <code>Runtime.getRuntime().load(filename)</code>.
646    *
647    * <p>
648    * The library is loaded using the class loader associated with the
649    * class associated with the invoking method.
650    *
651    * @param libname the library file to load
652    * @throws SecurityException if permission is denied
653    * @throws UnsatisfiedLinkError if the file cannot be loaded
654    * @see Runtime#load(String)
655    */
656   public static void loadLibrary(String libname)
657   {
658     Runtime.getRuntime().loadLibrary(libname,
659       VMStackWalker.getCallingClassLoader());
660   }
661
662   /**
663    * Convert a library name to its platform-specific variant.
664    *
665    * @param libname the library name, as used in <code>loadLibrary</code>
666    * @return the platform-specific mangling of the name
667    * @since 1.2
668    */
669   public static String mapLibraryName(String libname)
670   {
671     return VMRuntime.mapLibraryName(libname);
672   }
673
674
675   /**
676    * This is a specialised <code>Collection</code>, providing
677    * the necessary provisions for the collections used by the
678    * environment variable map.  Namely, it prevents
679    * querying anything but <code>String</code>s.
680    *
681    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
682    */
683   private static class EnvironmentCollection
684     extends AbstractCollection<String>
685   {
686
687     /**
688      * The wrapped collection.
689      */
690     protected Collection<String> c;
691
692     /**
693      * Constructs a new environment collection, which
694      * wraps the elements of the supplied collection.
695      *
696      * @param coll the collection to use as a base for
697      *             this collection.
698      */
699     public EnvironmentCollection(Collection<String> coll)
700     {
701       c = coll;
702     }
703         
704     /**
705      * Blocks queries containing a null object or an object which
706      * isn't of type <code>String</code>.  All other queries
707      * are forwarded to the underlying collection.
708      *
709      * @param obj the object to look for.
710      * @return true if the object exists in the collection.
711      * @throws NullPointerException if the specified object is null.
712      * @throws ClassCastException if the specified object is not a String.
713      */
714     public boolean contains(Object obj)
715     {
716       if (obj == null)
717           throw new
718             NullPointerException("This collection does not support " +
719                                  "null values.");
720       if (!(obj instanceof String))
721           throw new
722             ClassCastException("This collection only supports Strings.");
723       return c.contains(obj);
724     }
725     
726     /**
727      * Blocks queries where the collection contains a null object or
728      * an object which isn't of type <code>String</code>.  All other
729      * queries are forwarded to the underlying collection.
730      *
731      * @param coll the collection of objects to look for.
732      * @return true if the collection contains all elements in the collection.
733      * @throws NullPointerException if the collection is null.
734      * @throws NullPointerException if any collection entry is null.
735      * @throws ClassCastException if any collection entry is not a String.
736      */
737     public boolean containsAll(Collection<?> coll)
738     {
739       for (Object o: coll)
740         {
741           if (o == null)
742               throw new
743                 NullPointerException("This collection does not support " +
744                                      "null values.");
745           if (!(o instanceof String))
746               throw new
747                 ClassCastException("This collection only supports Strings.");
748         }
749       return c.containsAll(coll);
750     }
751
752     /**
753      * This returns an iterator over the map elements, with the
754      * same provisions as for the collection and underlying map.
755      *
756      * @return an iterator over the map elements.
757      */
758     public Iterator<String> iterator()
759     {
760       return c.iterator();
761     }
762     
763     /**
764      * Blocks the removal of elements from the collection.
765      *
766      * @return true if the removal was sucessful.
767      * @throws NullPointerException if the collection is null.
768      * @throws NullPointerException if any collection entry is null.
769      * @throws ClassCastException if any collection entry is not a String.
770      */
771     public boolean remove(Object key)
772     {
773       if (key == null)
774           throw new
775             NullPointerException("This collection does not support " +
776                                  "null values.");
777       if (!(key instanceof String))
778           throw new
779             ClassCastException("This collection only supports Strings.");
780       return c.contains(key);
781     }   
782         
783     /**
784      * Blocks the removal of all elements in the specified
785      * collection from the collection.
786      *
787      * @param coll the collection of elements to remove.
788      * @return true if the elements were removed.
789      * @throws NullPointerException if the collection is null.
790      * @throws NullPointerException if any collection entry is null.
791      * @throws ClassCastException if any collection entry is not a String.
792      */
793     public boolean removeAll(Collection<?> coll)
794     {
795       for (Object o: coll)
796         {
797           if (o == null)
798               throw new
799                 NullPointerException("This collection does not support " +
800                                      "null values.");
801           if (!(o instanceof String))
802             throw new
803               ClassCastException("This collection only supports Strings.");
804         }
805       return c.removeAll(coll);
806     }
807     
808     /**
809      * Blocks the retention of all elements in the specified
810      * collection from the collection.
811      *
812      * @param c the collection of elements to retain.
813      * @return true if the other elements were removed.
814      * @throws NullPointerException if the collection is null.
815      * @throws NullPointerException if any collection entry is null.
816      * @throws ClassCastException if any collection entry is not a String.
817      */
818     public boolean retainAll(Collection<?> coll)
819     {
820       for (Object o: coll)
821         {
822           if (o == null)
823               throw new
824                 NullPointerException("This collection does not support " +
825                                      "null values.");
826           if (!(o instanceof String))
827             throw new
828               ClassCastException("This collection only supports Strings.");
829         }
830       return c.containsAll(coll);
831     }
832
833     /**
834      * This simply calls the same method on the wrapped
835      * collection.
836      *
837      * @return the size of the underlying collection.
838      */
839     public int size()
840     {
841       return c.size();
842     }
843
844   } // class EnvironmentCollection<String>
845
846   /**
847    * This is a specialised <code>HashMap</code>, which
848    * prevents the addition or querying of anything other than
849    * <code>String</code> objects. 
850    *
851    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
852    */
853   static class EnvironmentMap
854     extends HashMap<String,String>
855   {
856     
857     /**
858      * Cache the entry set.
859      */
860     private transient Set<Map.Entry<String,String>> entries;
861
862     /**
863      * Cache the key set.
864      */
865     private transient Set<String> keys;
866
867     /**
868      * Cache the value collection.
869      */
870     private transient Collection<String> values;
871
872     /**
873      * Constructs a new empty <code>EnvironmentMap</code>.
874      */
875     EnvironmentMap()
876     {
877       super();
878     }
879
880     /**
881      * Constructs a new <code>EnvironmentMap</code> containing
882      * the contents of the specified map.
883      *
884      * @param m the map to be added to this.
885      * @throws NullPointerException if a key or value is null.
886      * @throws ClassCastException if a key or value is not a String.
887      */    
888     EnvironmentMap(Map<String,String> m)
889     {
890       super(m);
891     }
892
893     /**
894      * Blocks queries containing a null key or one which is not
895      * of type <code>String</code>.  All other queries
896      * are forwarded to the superclass.
897      *
898      * @param key the key to look for in the map.
899      * @return true if the key exists in the map.
900      * @throws NullPointerException if the specified key is null.
901      */
902     public boolean containsKey(Object key)
903     {
904       if (key == null)
905         throw new
906           NullPointerException("This map does not support null keys.");
907       if (!(key instanceof String))
908         throw new
909           ClassCastException("This map only allows queries using Strings.");
910       return super.containsKey(key);
911     }
912     
913     /**
914      * Blocks queries using a null or non-<code>String</code> value.
915      * All other queries are forwarded to the superclass.
916      *
917      * @param value the value to look for in the map.
918      * @return true if the value exists in the map.
919      * @throws NullPointerException if the specified value is null.
920      */
921     public boolean containsValue(Object value)
922     {
923       if (value == null)
924           throw new
925             NullPointerException("This map does not support null values.");
926       if (!(value instanceof String))
927         throw new
928           ClassCastException("This map only allows queries using Strings.");
929       return super.containsValue(value);
930     }
931
932     /**
933      * Returns a set view of the map entries, with the same
934      * provisions as for the underlying map.
935      *
936      * @return a set containing the map entries.
937      */
938     public Set<Map.Entry<String,String>> entrySet()
939     {
940       if (entries == null)
941         entries = super.entrySet();
942       return entries;
943     }
944
945     /**
946      * Blocks queries containing a null or non-<code>String</code> key.
947      * All other queries are passed on to the superclass.
948      *
949      * @param key the key to retrieve the value for.
950      * @return the value associated with the given key.
951      * @throws NullPointerException if the specified key is null.
952      * @throws ClassCastException if the specified key is not a String.
953      */
954     public String get(Object key)
955     {
956       if (key == null)
957         throw new
958           NullPointerException("This map does not support null keys.");
959       if (!(key instanceof String))
960         throw new
961           ClassCastException("This map only allows queries using Strings.");
962       return super.get(key);
963     }
964     
965     /**
966      * Returns a set view of the keys, with the same
967      * provisions as for the underlying map.
968      *
969      * @return a set containing the keys.
970      */
971     public Set<String> keySet()
972     {
973       if (keys == null)
974         keys = new EnvironmentSet(super.keySet());
975       return keys;
976     }
977
978     /**
979      * Associates the given key to the given value. If the
980      * map already contains the key, its value is replaced.
981      * The map does not accept null keys or values, or keys
982      * and values not of type {@link String}.
983      *
984      * @param key the key to map.
985      * @param value the value to be mapped.
986      * @return the previous value of the key, or null if there was no mapping
987      * @throws NullPointerException if a key or value is null.
988      * @throws ClassCastException if a key or value is not a String.
989      */
990     public String put(String key, String value)
991     {
992       if (key == null)
993         throw new NullPointerException("A new key is null.");
994       if (value == null)
995         throw new NullPointerException("A new value is null.");
996       if (!(key instanceof String))
997         throw new ClassCastException("A new key is not a String.");
998       if (!(value instanceof String))
999         throw new ClassCastException("A new value is not a String.");
1000       return super.put(key, value);
1001     }
1002
1003     /**
1004      * Removes a key-value pair from the map.  The queried key may not
1005      * be null or of a type other than a <code>String</code>.
1006      *
1007      * @param key the key of the entry to remove.
1008      * @return the removed value.
1009      * @throws NullPointerException if the specified key is null.
1010      * @throws ClassCastException if the specified key is not a String.
1011      */
1012     public String remove(Object key)
1013     {
1014       if (key == null)
1015         throw new
1016           NullPointerException("This map does not support null keys.");
1017       if (!(key instanceof String))
1018         throw new
1019           ClassCastException("This map only allows queries using Strings.");
1020       return super.remove(key);
1021     }
1022     
1023     /**
1024      * Returns a collection view of the values, with the same
1025      * provisions as for the underlying map.
1026      *
1027      * @return a collection containing the values.
1028      */
1029     public Collection<String> values()
1030     {
1031       if (values == null)
1032         values = new EnvironmentCollection(super.values());
1033       return values;
1034     }
1035     
1036   }
1037
1038   /**
1039    * This is a specialised <code>Set</code>, providing
1040    * the necessary provisions for the collections used by the
1041    * environment variable map.  Namely, it prevents
1042    * modifications and the use of queries with null
1043    * or non-<code>String</code> values.
1044    *
1045    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
1046    */
1047   private static class EnvironmentSet
1048     extends EnvironmentCollection
1049     implements Set<String>
1050   {
1051
1052     /**
1053      * Constructs a new environment set, which
1054      * wraps the elements of the supplied set.
1055      *
1056      * @param set the set to use as a base for
1057      *             this set.
1058      */
1059     public EnvironmentSet(Set<String> set)
1060     {
1061       super(set);
1062     }
1063
1064     /**
1065      * This simply calls the same method on the wrapped
1066      * collection.
1067      *
1068      * @param obj the object to compare with.
1069      * @return true if the two objects are equal.
1070      */
1071     public boolean equals(Object obj)
1072     {
1073       return c.equals(obj);
1074     }
1075
1076     /**
1077      * This simply calls the same method on the wrapped
1078      * collection.
1079      *
1080      * @return the hashcode of the collection.
1081      */
1082     public int hashCode()
1083     {
1084       return c.hashCode();
1085     }
1086
1087   } // class EnvironmentSet<String>
1088
1089 } // class System