Source for java.lang.System

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