1 /* System.java -- useful methods to interface with the system
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3 
4 This file is part of GNU Classpath.
5 
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.
10 
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.
15 
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., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA.
20 
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.
25 
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. */
37 
38 
39 package java.lang;
40 
41 import java.io.BufferedInputStream;
42 import java.io.BufferedOutputStream;
43 import java.io.FileDescriptor;
44 import java.io.FileInputStream;
45 import java.io.FileOutputStream;
46 import java.io.InputStream;
47 import java.io.PrintStream;
48 import java.util.Properties;
49 import java.util.PropertyPermission;
50 import gnu.classpath.Configuration;
51 
52 /**
53  * System represents system-wide resources; things that represent the
54  * general environment.  As such, all methods are static.
55  *
56  * @author John Keiser
57  * @author Eric Blake <ebb9@email.byu.edu>
58  * @since 1.0
59  * @status still missing 1.4 functionality
60  */
61 public final class System
62 {
63   // WARNING: System is a CORE class in the bootstrap cycle. See the comments
64   // in vm/reference/java/lang/Runtime for implications of this fact.
65 
66   /**
67    * Add to the default properties. The field is stored in Runtime, because
68    * of the bootstrap sequence; but this adds several useful properties to
69    * the defaults. Once the default is stabilized, it should not be modified;
70    * instead it is passed as a parent properties for fast setup of the
71    * defaults when calling <code>setProperties(null)</code>.
72    */
73   static
74   {
75     // Note that this loadLibrary() takes precedence over the one in Object,
76     // since Object.<clinit> is waiting for System.<clinit> to complete
77     // first; but loading a library twice is harmless.
78     if (Configuration.INIT_LOAD_LIBRARY)
79       loadLibrary("javalang");
80 
81     Properties defaultProperties = Runtime.defaultProperties;
82 
83     // Set base URL if not already set.
84     if (defaultProperties.get("gnu.classpath.home.url") == null)
85       defaultProperties.put("gnu.classpath.home.url",
86 			    "file://"
87 			    + defaultProperties.get("gnu.classpath.home")
88 			    + "/lib");
89 
90     // Set short name if not already set.
91     if (defaultProperties.get("gnu.classpath.vm.shortname") == null)
92       {
93 	String value = defaultProperties.getProperty("java.vm.name");
94 	int index = value.lastIndexOf(' ');
95 	if (index != -1)
96 	  value = value.substring(index + 1);
97 	defaultProperties.put("gnu.classpath.vm.shortname", value);
98       }
99 
100     defaultProperties.put("gnu.cpu.endian",
101 			  isWordsBigEndian() ? "big" : "little");
102 
103     // GCJ LOCAL: Classpath sets common encoding aliases here.
104     // Since we don't (yet) have gnu.java.io.EncodingManager, these
105     // are a waste of time and just slow down system startup.
106 
107     // XXX FIXME - Temp hack for old systems that set the wrong property
108     if (defaultProperties.get("java.io.tmpdir") == null)
109       defaultProperties.put("java.io.tmpdir",
110                             defaultProperties.get("java.tmpdir"));
111   }
112 
113   /**
114    * Stores the current system properties. This can be modified by
115    * {@link #setProperties(Properties)}, but will never be null, because
116    * setProperties(null) sucks in the default properties.
117    */
118   // Note that we use clone here and not new.  Some programs assume
119   // that the system properties do not have a parent.
120   private static Properties properties
121     = (Properties) Runtime.defaultProperties.clone();
122 
123   /**
124    * The standard InputStream. This is assigned at startup and starts its
125    * life perfectly valid. Although it is marked final, you can change it
126    * using {@link #setIn(InputStream)} through some hefty VM magic.
127    *
128    * <p>This corresponds to the C stdin and C++ cin variables, which
129    * typically input from the keyboard, but may be used to pipe input from
130    * other processes or files.  That should all be transparent to you,
131    * however.
132    */
133   public static final InputStream in
134     = new BufferedInputStream(new FileInputStream(FileDescriptor.in));
135   /**
136    * The standard output PrintStream.  This is assigned at startup and
137    * starts its life perfectly valid. Although it is marked final, you can
138    * change it using {@link #setOut(PrintStream)} through some hefty VM magic.
139    *
140    * <p>This corresponds to the C stdout and C++ cout variables, which
141    * typically output normal messages to the screen, but may be used to pipe
142    * output to other processes or files.  That should all be transparent to
143    * you, however.
144    */
145   public static final PrintStream out
146     = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true);
147   /**
148    * The standard output PrintStream.  This is assigned at startup and
149    * starts its life perfectly valid. Although it is marked final, you can
150    * change it using {@link #setOut(PrintStream)} through some hefty VM magic.
151    *
152    * <p>This corresponds to the C stderr and C++ cerr variables, which
153    * typically output error messages to the screen, but may be used to pipe
154    * output to other processes or files.  That should all be transparent to
155    * you, however.
156    */
157   public static final PrintStream err
158     = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.err)), true);
159 
160   /**
161    * This class is uninstantiable.
162    */
System()163   private System()
164   {
165   }
166 
167   /**
168    * Set {@link #in} to a new InputStream. This uses some VM magic to change
169    * a "final" variable, so naturally there is a security check,
170    * <code>RuntimePermission("setIO")</code>.
171    *
172    * @param in the new InputStream
173    * @throws SecurityException if permission is denied
174    * @since 1.1
175    */
setIn(InputStream in)176   public static void setIn(InputStream in)
177   {
178     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
179     if (sm != null)
180       sm.checkPermission(new RuntimePermission("setIO"));
181     setIn0(in);
182   }
183 
184   /**
185    * Set {@link #out} to a new PrintStream. This uses some VM magic to change
186    * a "final" variable, so naturally there is a security check,
187    * <code>RuntimePermission("setIO")</code>.
188    *
189    * @param out the new PrintStream
190    * @throws SecurityException if permission is denied
191    * @since 1.1
192    */
setOut(PrintStream out)193   public static void setOut(PrintStream out)
194   {
195     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
196     if (sm != null)
197       sm.checkPermission(new RuntimePermission("setIO"));
198 
199     setOut0(out);
200   }
201 
202   /**
203    * Set {@link #err} to a new PrintStream. This uses some VM magic to change
204    * a "final" variable, so naturally there is a security check,
205    * <code>RuntimePermission("setIO")</code>.
206    *
207    * @param err the new PrintStream
208    * @throws SecurityException if permission is denied
209    * @since 1.1
210    */
setErr(PrintStream err)211   public static void setErr(PrintStream err)
212   {
213     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
214     if (sm != null)
215       sm.checkPermission(new RuntimePermission("setIO"));
216     setErr0(err);
217   }
218 
219   /**
220    * Set the current SecurityManager. If a security manager already exists,
221    * then <code>RuntimePermission("setSecurityManager")</code> is checked
222    * first. Since this permission is denied by the default security manager,
223    * setting the security manager is often an irreversible action.
224    *
225    * <STRONG>Spec Note:</STRONG> Don't ask me, I didn't write it.  It looks
226    * pretty vulnerable; whoever gets to the gate first gets to set the policy.
227    * There is probably some way to set the original security manager as a
228    * command line argument to the VM, but I don't know it.
229    *
230    * @param sm the new SecurityManager
231    * @throws SecurityException if permission is denied
232    */
setSecurityManager(SecurityManager sm)233   public synchronized static void setSecurityManager(SecurityManager sm)
234   {
235     // Implementation note: the field lives in Runtime because of bootstrap
236     // initialization issues. This method is synchronized so that no other
237     // thread changes it to null before this thread makes the change.
238     if (Runtime.securityManager != null)
239       Runtime.securityManager.checkPermission
240         (new RuntimePermission("setSecurityManager"));
241     Runtime.securityManager = sm;
242   }
243 
244   /**
245    * Get the current SecurityManager. If the SecurityManager has not been
246    * set yet, then this method returns null.
247    *
248    * @return the current SecurityManager, or null
249    */
getSecurityManager()250   public static SecurityManager getSecurityManager()
251   {
252     // Implementation note: the field lives in Runtime because of bootstrap
253     // initialization issues.
254     return Runtime.securityManager;
255   }
256 
257   /**
258    * Get the current time, measured in the number of milliseconds from the
259    * beginning of Jan. 1, 1970. This is gathered from the system clock, with
260    * any attendant incorrectness (it may be timezone dependent).
261    *
262    * @return the current time
263    * @see java.util.Date
264    */
currentTimeMillis()265   public static native long currentTimeMillis();
266 
267   /**
268    * Copy one array onto another from <code>src[srcStart]</code> ...
269    * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ...
270    * <code>dest[destStart+len-1]</code>. First, the arguments are validated:
271    * neither array may be null, they must be of compatible types, and the
272    * start and length must fit within both arrays. Then the copying starts,
273    * and proceeds through increasing slots.  If src and dest are the same
274    * array, this will appear to copy the data to a temporary location first.
275    * An ArrayStoreException in the middle of copying will leave earlier
276    * elements copied, but later elements unchanged.
277    *
278    * @param src the array to copy elements from
279    * @param srcStart the starting position in src
280    * @param dest the array to copy elements to
281    * @param destStart the starting position in dest
282    * @param len the number of elements to copy
283    * @throws NullPointerException if src or dest is null
284    * @throws ArrayStoreException if src or dest is not an array, if they are
285    *         not compatible array types, or if an incompatible runtime type
286    *         is stored in dest
287    * @throws IndexOutOfBoundsException if len is negative, or if the start or
288    *         end copy position in either array is out of bounds
289    */
arraycopy(Object src, int srcStart, Object dest, int destStart, int len)290   public static native void arraycopy(Object src, int srcStart,
291 				      Object dest, int destStart, int len);
292 
293   /**
294    * Get a hash code computed by the VM for the Object. This hash code will
295    * be the same as Object's hashCode() method.  It is usually some
296    * convolution of the pointer to the Object internal to the VM.  It
297    * follows standard hash code rules, in that it will remain the same for a
298    * given Object for the lifetime of that Object.
299    *
300    * @param o the Object to get the hash code for
301    * @return the VM-dependent hash code for this Object
302    * @since 1.1
303    */
identityHashCode(Object o)304   public static native int identityHashCode(Object o);
305 
306   /**
307    * Get all the system properties at once. A security check may be performed,
308    * <code>checkPropertiesAccess</code>. Note that a security manager may
309    * allow getting a single property, but not the entire group.
310    *
311    * <p>The required properties include:
312    * <dl>
313    * <dt>java.version         <dd>Java version number
314    * <dt>java.vendor          <dd>Java vendor specific string
315    * <dt>java.vendor.url      <dd>Java vendor URL
316    * <dt>java.home            <dd>Java installation directory
317    * <dt>java.vm.specification.version <dd>VM Spec version
318    * <dt>java.vm.specification.vendor  <dd>VM Spec vendor
319    * <dt>java.vm.specification.name    <dd>VM Spec name
320    * <dt>java.vm.version      <dd>VM implementation version
321    * <dt>java.vm.vendor       <dd>VM implementation vendor
322    * <dt>java.vm.name         <dd>VM implementation name
323    * <dt>java.specification.version    <dd>Java Runtime Environment version
324    * <dt>java.specification.vendor     <dd>Java Runtime Environment vendor
325    * <dt>java.specification.name       <dd>Java Runtime Environment name
326    * <dt>java.class.version   <dd>Java class version number
327    * <dt>java.class.path      <dd>Java classpath
328    * <dt>java.library.path    <dd>Path for finding Java libraries
329    * <dt>java.io.tmpdir       <dd>Default temp file path
330    * <dt>java.compiler        <dd>Name of JIT to use
331    * <dt>java.ext.dirs        <dd>Java extension path
332    * <dt>os.name              <dd>Operating System Name
333    * <dt>os.arch              <dd>Operating System Architecture
334    * <dt>os.version           <dd>Operating System Version
335    * <dt>file.separator       <dd>File separator ("/" on Unix)
336    * <dt>path.separator       <dd>Path separator (":" on Unix)
337    * <dt>line.separator       <dd>Line separator ("\n" on Unix)
338    * <dt>user.name            <dd>User account name
339    * <dt>user.home            <dd>User home directory
340    * <dt>user.dir             <dd>User's current working directory
341    * </dl>
342    *
343    * In addition, gnu defines several other properties, where ? stands for
344    * each character in '0' through '9':
345    * <dl>
346    * <dl> gnu.classpath.vm.shortname <dd> Succinct version of the VM name;
347    *      used for finding property files in file system
348    * <dl> gnu.classpath.home.url <dd> Base URL; used for finding
349    *      property files in file system
350    * <dt> gnu.cpu.endian      <dd>big or little
351    * <dt> gnu.java.io.encoding_scheme_alias.ISO-8859-?   <dd>8859_?
352    * <dt> gnu.java.io.encoding_scheme_alias.iso-8859-?   <dd>8859_?
353    * <dt> gnu.java.io.encoding_scheme_alias.iso8859_?    <dd>8859_?
354    * <dt> gnu.java.io.encoding_scheme_alias.iso-latin-_? <dd>8859_?
355    * <dt> gnu.java.io.encoding_scheme_alias.latin?       <dd>8859_?
356    * <dt> gnu.java.io.encoding_scheme_alias.UTF-8        <dd>UTF8
357    * <dt> gnu.java.io.encoding_scheme_alias.utf-8        <dd>UTF8
358    * </dl>
359    *
360    * @return the system properties, will never be null
361    * @throws SecurityException if permission is denied
362    */
getProperties()363   public static Properties getProperties()
364   {
365     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
366     if (sm != null)
367       sm.checkPropertiesAccess();
368     return properties;
369   }
370 
371   /**
372    * Set all the system properties at once. A security check may be performed,
373    * <code>checkPropertiesAccess</code>. Note that a security manager may
374    * allow setting a single property, but not the entire group. An argument
375    * of null resets the properties to the startup default.
376    *
377    * @param properties the new set of system properties
378    * @throws SecurityException if permission is denied
379    */
setProperties(Properties properties)380   public static void setProperties(Properties properties)
381   {
382     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
383     if (sm != null)
384       sm.checkPropertiesAccess();
385     if (properties == null)
386       {
387 	// Note that we use clone here and not new.  Some programs
388 	// assume that the system properties do not have a parent.
389 	properties = (Properties) Runtime.defaultProperties.clone();
390       }
391     System.properties = properties;
392   }
393 
394   /**
395    * Get a single system property by name. A security check may be performed,
396    * <code>checkPropertyAccess(key)</code>.
397    *
398    * @param key the name of the system property to get
399    * @return the property, or null if not found
400    * @throws SecurityException if permission is denied
401    * @throws NullPointerException if key is null
402    * @throws IllegalArgumentException if key is ""
403    */
getProperty(String key)404   public static String getProperty(String key)
405   {
406     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
407     if (sm != null)
408       sm.checkPropertyAccess(key);
409     else if (key.length() == 0)
410       throw new IllegalArgumentException("key can't be empty");
411     return properties.getProperty(key);
412   }
413 
414   /**
415    * Get a single system property by name. A security check may be performed,
416    * <code>checkPropertyAccess(key)</code>.
417    *
418    * @param key the name of the system property to get
419    * @param def the default
420    * @return the property, or def if not found
421    * @throws SecurityException if permission is denied
422    * @throws NullPointerException if key is null
423    * @throws IllegalArgumentException if key is ""
424    */
getProperty(String key, String def)425   public static String getProperty(String key, String def)
426   {
427     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
428     if (sm != null)
429       sm.checkPropertyAccess(key);
430     return properties.getProperty(key, def);
431   }
432 
433   /**
434    * Set a single system property by name. A security check may be performed,
435    * <code>checkPropertyAccess(key, "write")</code>.
436    *
437    * @param key the name of the system property to set
438    * @param value the new value
439    * @return the previous value, or null
440    * @throws SecurityException if permission is denied
441    * @throws NullPointerException if key is null
442    * @throws IllegalArgumentException if key is ""
443    * @since 1.2
444    */
setProperty(String key, String value)445   public static String setProperty(String key, String value)
446   {
447     SecurityManager sm = Runtime.securityManager; // Be thread-safe.
448     if (sm != null)
449       sm.checkPermission(new PropertyPermission(key, "write"));
450     return (String) properties.setProperty(key, value);
451   }
452 
453   /**
454    * This used to get an environment variable, but following Sun's lead,
455    * it now throws an Error. Use <code>getProperty</code> instead.
456    *
457    * @param name the name of the environment variable
458    * @return this does not return
459    * @throws Error this is not supported
460    * @deprecated use {@link #getProperty(String)}; getenv is not supported
461    */
getenv(String name)462   public static String getenv(String name)
463   {
464     throw new Error("getenv no longer supported, use properties instead: "
465                     + name);
466   }
467 
468   /**
469    * Terminate the Virtual Machine. This just calls
470    * <code>Runtime.getRuntime().exit(status)</code>, and never returns.
471    * Obviously, a security check is in order, <code>checkExit</code>.
472    *
473    * @param status the exit status; by convention non-zero is abnormal
474    * @throws SecurityException if permission is denied
475    * @see Runtime#exit(int)
476    */
exit(int status)477   public static void exit(int status)
478   {
479     Runtime.getRuntime().exit(status);
480   }
481 
482   /**
483    * Calls the garbage collector. This is only a hint, and it is up to the
484    * implementation what this hint suggests, but it usually causes a
485    * best-effort attempt to reclaim unused memory from discarded objects.
486    * This calls <code>Runtime.getRuntime().gc()</code>.
487    *
488    * @see Runtime#gc()
489    */
gc()490   public static void gc()
491   {
492     Runtime.getRuntime().gc();
493   }
494 
495   /**
496    * Runs object finalization on pending objects. This is only a hint, and
497    * it is up to the implementation what this hint suggests, but it usually
498    * causes a best-effort attempt to run finalizers on all objects ready
499    * to be reclaimed. This calls
500    * <code>Runtime.getRuntime().runFinalization()</code>.
501    *
502    * @see Runtime#runFinalization()
503    */
runFinalization()504   public static void runFinalization()
505   {
506     Runtime.getRuntime().runFinalization();
507   }
508 
509   /**
510    * Tell the Runtime whether to run finalization before exiting the
511    * JVM.  This is inherently unsafe in multi-threaded applications,
512    * since it can force initialization on objects which are still in use
513    * by live threads, leading to deadlock; therefore this is disabled by
514    * default. There may be a security check, <code>checkExit(0)</code>. This
515    * calls <code>Runtime.getRuntime().runFinalizersOnExit()</code>.
516    *
517    * @param finalizeOnExit whether to run finalizers on exit
518    * @throws SecurityException if permission is denied
519    * @see Runtime#runFinalizersOnExit()
520    * @since 1.1
521    * @deprecated never rely on finalizers to do a clean, thread-safe,
522    *             mop-up from your code
523    */
runFinalizersOnExit(boolean finalizeOnExit)524   public static void runFinalizersOnExit(boolean finalizeOnExit)
525   {
526     Runtime.getRuntime().runFinalizersOnExit(finalizeOnExit);
527   }
528 
529   /**
530    * Load a code file using its explicit system-dependent filename. A security
531    * check may be performed, <code>checkLink</code>. This just calls
532    * <code>Runtime.getRuntime().load(filename)</code>.
533    *
534    * @param filename the code file to load
535    * @throws SecurityException if permission is denied
536    * @throws UnsatisfiedLinkError if the file cannot be loaded
537    * @see Runtime#load(String)
538    */
load(String filename)539   public static void load(String filename)
540   {
541     Runtime.getRuntime().load(filename);
542   }
543 
544   /**
545    * Load a library using its explicit system-dependent filename. A security
546    * check may be performed, <code>checkLink</code>. This just calls
547    * <code>Runtime.getRuntime().load(filename)</code>.
548    *
549    * @param libname the library file to load
550    * @throws SecurityException if permission is denied
551    * @throws UnsatisfiedLinkError if the file cannot be loaded
552    * @see Runtime#load(String)
553    */
loadLibrary(String libname)554   public static void loadLibrary(String libname)
555   {
556     Runtime.getRuntime().loadLibrary(libname);
557   }
558 
559   /**
560    * Convert a library name to its platform-specific variant.
561    *
562    * @param libname the library name, as used in <code>loadLibrary</code>
563    * @return the platform-specific mangling of the name
564    * @since 1.2
565    */
mapLibraryName(String libname)566   public static String mapLibraryName(String libname)
567   {
568     // XXX Fix this!!!!
569     return Runtime.nativeGetLibname("", libname);
570   }
571 
572   /**
573    * Detect big-endian systems.
574    *
575    * @return true if the system is big-endian.
576    */
isWordsBigEndian()577   static native boolean isWordsBigEndian();
578 
579   /**
580    * Set {@link #in} to a new InputStream.
581    *
582    * @param in the new InputStream
583    * @see #setIn(InputStream)
584    */
setIn0(InputStream in)585   private static native void setIn0(InputStream in);
586 
587   /**
588    * Set {@link #out} to a new PrintStream.
589    *
590    * @param out the new PrintStream
591    * @see #setOut(PrintStream)
592    */
setOut0(PrintStream out)593   private static native void setOut0(PrintStream out);
594 
595   /**
596    * Set {@link #err} to a new PrintStream.
597    *
598    * @param err the new PrintStream
599    * @see #setErr(PrintStream)
600    */
setErr0(PrintStream err)601   private static native void setErr0(PrintStream err);
602 } // class System
603