diff options
author | Tom Tromey <tromey@redhat.com> | 2002-05-13 20:10:37 +0000 |
---|---|---|
committer | Tom Tromey <tromey@gcc.gnu.org> | 2002-05-13 20:10:37 +0000 |
commit | 86397868159ba8c7ba20d56fdf49f551a512a1f1 (patch) | |
tree | 8d55a2017b3cd999dc25fd24a3e201558e07756e /libjava | |
parent | 16133d00586de86b5d77c3b5f5833c6485ca697c (diff) | |
download | gcc-86397868159ba8c7ba20d56fdf49f551a512a1f1.tar.gz |
re PR libgcj/6389 (System.getProperty("") should always throw an IllegalArgumentException)
Fixes PR libgcj/6389:
* Makefile.in: Rebuilt.
* Makefile.am (nat_source_files): Added natTimeZone.cc.
* java/util/natTimeZone.cc: New file.
* java/util/TimeZone.java (getDefaultTimeZoneId): New method.
* java/lang/System.java: Merged with Classpath.
* java/lang/Runtime.java: Merged with Classpath.
* java/lang/natSystem.cc (setErr0): Renamed from setErr; don't run
security check.
(setIn0): Renamed from setIn; don't run security check.
(setOut0): Renamed from setOut; don't run security check.
(file_encoding, getpwuid_adaptor, getSystemTimeZone,
init_properties): Moved to natRuntime.cc.
Moved many includes to natRuntime.cc.
(isWordsBigEndian): New method.
* java/lang/natRuntime.cc: Include Long.h, also other includes
previously in natSystem.cc.
(maxMemory): New function.
(exitInternal): Renamed from `_exit'.
(exit): Removed.
(init): Don't set finalize_on_exit.
(exitInternal): Use `finalizeOnExit'.
(file_encoding, getpwuid_adaptor): New functions from
natSystem.cc.
(insertSystemProperties): New method, renamed from
System::init_properties. Don't set user.timezone.
(_load): Don't call checkLink.
(execInternal): New method.
(availableProcessors): Likewise.
(nativeGetLibname): Likewise.
From-SVN: r53429
Diffstat (limited to 'libjava')
-rw-r--r-- | libjava/ChangeLog | 33 | ||||
-rw-r--r-- | libjava/Makefile.am | 1 | ||||
-rw-r--r-- | libjava/Makefile.in | 60 | ||||
-rw-r--r-- | libjava/java/lang/Runtime.java | 812 | ||||
-rw-r--r-- | libjava/java/lang/System.java | 691 | ||||
-rw-r--r-- | libjava/java/lang/natRuntime.cc | 375 | ||||
-rw-r--r-- | libjava/java/lang/natSystem.cc | 399 | ||||
-rw-r--r-- | libjava/java/util/TimeZone.java | 23 | ||||
-rw-r--r-- | libjava/java/util/natTimeZone.cc | 154 |
9 files changed, 1852 insertions, 696 deletions
diff --git a/libjava/ChangeLog b/libjava/ChangeLog index 688debb9c8b..25233a17b54 100644 --- a/libjava/ChangeLog +++ b/libjava/ChangeLog @@ -1,3 +1,36 @@ +2002-05-13 Tom Tromey <tromey@redhat.com> + + Fixes PR libgcj/6389: + * Makefile.in: Rebuilt. + * Makefile.am (nat_source_files): Added natTimeZone.cc. + * java/util/natTimeZone.cc: New file. + * java/util/TimeZone.java (getDefaultTimeZoneId): New method. + * java/lang/System.java: Merged with Classpath. + * java/lang/Runtime.java: Merged with Classpath. + * java/lang/natSystem.cc (setErr0): Renamed from setErr; don't run + security check. + (setIn0): Renamed from setIn; don't run security check. + (setOut0): Renamed from setOut; don't run security check. + (file_encoding, getpwuid_adaptor, getSystemTimeZone, + init_properties): Moved to natRuntime.cc. + Moved many includes to natRuntime.cc. + (isWordsBigEndian): New method. + * java/lang/natRuntime.cc: Include Long.h, also other includes + previously in natSystem.cc. + (maxMemory): New function. + (exitInternal): Renamed from `_exit'. + (exit): Removed. + (init): Don't set finalize_on_exit. + (exitInternal): Use `finalizeOnExit'. + (file_encoding, getpwuid_adaptor): New functions from + natSystem.cc. + (insertSystemProperties): New method, renamed from + System::init_properties. Don't set user.timezone. + (_load): Don't call checkLink. + (execInternal): New method. + (availableProcessors): Likewise. + (nativeGetLibname): Likewise. + 2002-05-11 Mark Wielaard <mark@klomp.org> * gnu/java/text/SentenceBreakIterator.java (next): Skip all java white diff --git a/libjava/Makefile.am b/libjava/Makefile.am index c98b0d1b242..53ff7519ce5 100644 --- a/libjava/Makefile.am +++ b/libjava/Makefile.am @@ -1783,6 +1783,7 @@ java/net/natInetAddress.cc \ java/net/natPlainDatagramSocketImpl.cc \ java/net/natPlainSocketImpl.cc \ java/text/natCollator.cc \ +java/util/natTimeZone.cc \ java/util/zip/natDeflater.cc \ java/util/zip/natInflater.cc diff --git a/libjava/Makefile.in b/libjava/Makefile.in index b269ee71ff6..71fab9917c7 100644 --- a/libjava/Makefile.in +++ b/libjava/Makefile.in @@ -129,13 +129,19 @@ mkinstalldirs = @mkinstalldirs@ tool_include_dir = @tool_include_dir@ AUTOMAKE_OPTIONS = foreign -@TESTSUBDIR_TRUE@SUBDIRS = @TESTSUBDIR_TRUE@$(DIRLTDL) testsuite gcj include -@TESTSUBDIR_FALSE@SUBDIRS = @TESTSUBDIR_FALSE@$(DIRLTDL) gcj include -@USE_LIBDIR_TRUE@toolexeclibdir = @USE_LIBDIR_TRUE@$(libdir)$(MULTISUBDIR) -@USE_LIBDIR_FALSE@toolexeclibdir = @USE_LIBDIR_FALSE@$(toolexecdir)/lib$(MULTISUBDIR) -@USE_LIBDIR_FALSE@toolexecdir = @USE_LIBDIR_FALSE@$(exec_prefix)/$(target_alias) -@XLIB_AWT_TRUE@cond_x_ltlibrary = @XLIB_AWT_TRUE@libgcjx.la -@XLIB_AWT_FALSE@cond_x_ltlibrary = +@TESTSUBDIR_TRUE@SUBDIRS = \ +@TESTSUBDIR_TRUE@$(DIRLTDL) testsuite gcj include +@TESTSUBDIR_FALSE@SUBDIRS = \ +@TESTSUBDIR_FALSE@$(DIRLTDL) gcj include +@USE_LIBDIR_TRUE@toolexeclibdir = \ +@USE_LIBDIR_TRUE@$(libdir)$(MULTISUBDIR) +@USE_LIBDIR_FALSE@toolexeclibdir = \ +@USE_LIBDIR_FALSE@$(toolexecdir)/lib$(MULTISUBDIR) +@USE_LIBDIR_FALSE@toolexecdir = \ +@USE_LIBDIR_FALSE@$(exec_prefix)/$(target_alias) +@XLIB_AWT_TRUE@cond_x_ltlibrary = \ +@XLIB_AWT_TRUE@libgcjx.la +@XLIB_AWT_FALSE@cond_x_ltlibrary = \ toolexeclib_LTLIBRARIES = libgcj.la $(cond_x_ltlibrary) toolexeclib_DATA = libgcj.spec @@ -145,14 +151,20 @@ jar_DATA = libgcj-@gcc_version@.jar secdir = $(libdir)/security -@NATIVE_TRUE@bin_PROGRAMS = @NATIVE_TRUE@jv-convert gij rmic rmiregistry +@NATIVE_TRUE@bin_PROGRAMS = \ +@NATIVE_TRUE@jv-convert gij rmic rmiregistry bin_SCRIPTS = addr2name.awk -@CANADIAN_TRUE@@NULL_TARGET_TRUE@ZIP = @CANADIAN_TRUE@@NULL_TARGET_TRUE@$(MULTIBUILDTOP)../$(COMPPATH)/fastjar/jar$(EXEEXT) -@CANADIAN_TRUE@@NULL_TARGET_FALSE@ZIP = @CANADIAN_TRUE@@NULL_TARGET_FALSE@jar -@CANADIAN_FALSE@ZIP = @CANADIAN_FALSE@$(MULTIBUILDTOP)../$(COMPPATH)/fastjar/jar$(EXEEXT) -@CANADIAN_TRUE@GCJH = @CANADIAN_TRUE@gcjh -@CANADIAN_FALSE@GCJH = @CANADIAN_FALSE@$(MULTIBUILDTOP)../$(COMPPATH)/gcc/gcjh$(EXEEXT) +@CANADIAN_TRUE@@NULL_TARGET_TRUE@ZIP = \ +@CANADIAN_TRUE@@NULL_TARGET_TRUE@$(MULTIBUILDTOP)../$(COMPPATH)/fastjar/jar$(EXEEXT) +@CANADIAN_TRUE@@NULL_TARGET_FALSE@ZIP = \ +@CANADIAN_TRUE@@NULL_TARGET_FALSE@jar +@CANADIAN_FALSE@ZIP = \ +@CANADIAN_FALSE@$(MULTIBUILDTOP)../$(COMPPATH)/fastjar/jar$(EXEEXT) +@CANADIAN_TRUE@GCJH = \ +@CANADIAN_TRUE@gcjh +@CANADIAN_FALSE@GCJH = \ +@CANADIAN_FALSE@$(MULTIBUILDTOP)../$(COMPPATH)/gcc/gcjh$(EXEEXT) GCJ_WITH_FLAGS = $(GCJ) --encoding=UTF-8 @@ -173,8 +185,10 @@ AM_CXXFLAGS = -fno-rtti -fnon-call-exceptions \ @LIBGCJ_CXXFLAGS@ @X_CFLAGS@ $(WARNINGS) -D_GNU_SOURCE \ -DPREFIX="\"$(prefix)\"" -@USING_GCC_TRUE@AM_CFLAGS = @USING_GCC_TRUE@@LIBGCJ_CFLAGS@ $(WARNINGS) -@USING_GCC_FALSE@AM_CFLAGS = @USING_GCC_FALSE@@LIBGCJ_CFLAGS@ +@USING_GCC_TRUE@AM_CFLAGS = \ +@USING_GCC_TRUE@@LIBGCJ_CFLAGS@ $(WARNINGS) +@USING_GCC_FALSE@AM_CFLAGS = \ +@USING_GCC_FALSE@@LIBGCJ_CFLAGS@ JCFLAGS = -g JC1FLAGS = @LIBGCJ_JAVAFLAGS@ $(GCJFLAGS) @@ -257,7 +271,8 @@ extra_headers = java/lang/Object.h java/lang/Class.h NM = nm -@NATIVE_TRUE@@MAINTAINER_MODE_TRUE@noinst_PROGRAMS = @NATIVE_TRUE@@MAINTAINER_MODE_TRUE@gen-from-JIS +@NATIVE_TRUE@@MAINTAINER_MODE_TRUE@noinst_PROGRAMS = \ +@NATIVE_TRUE@@MAINTAINER_MODE_TRUE@gen-from-JIS CONVERT_DIR = gnu/gcj/convert @@ -1544,6 +1559,7 @@ java/net/natInetAddress.cc \ java/net/natPlainDatagramSocketImpl.cc \ java/net/natPlainSocketImpl.cc \ java/text/natCollator.cc \ +java/util/natTimeZone.cc \ java/util/zip/natDeflater.cc \ java/util/zip/natInflater.cc @@ -1694,8 +1710,8 @@ java/lang/ref/natReference.lo java/lang/reflect/natArray.lo \ java/lang/reflect/natConstructor.lo java/lang/reflect/natField.lo \ java/lang/reflect/natMethod.lo java/net/natInetAddress.lo \ java/net/natPlainDatagramSocketImpl.lo java/net/natPlainSocketImpl.lo \ -java/text/natCollator.lo java/util/zip/natDeflater.lo \ -java/util/zip/natInflater.lo +java/text/natCollator.lo java/util/natTimeZone.lo \ +java/util/zip/natDeflater.lo java/util/zip/natInflater.lo libgcjx_la_OBJECTS = gnu/gcj/xlib/natClip.lo \ gnu/gcj/xlib/natColormap.lo gnu/gcj/xlib/natDisplay.lo \ gnu/gcj/xlib/natDrawable.lo gnu/gcj/xlib/natFont.lo \ @@ -1739,7 +1755,7 @@ libgcj-test.spec.in libgcj.spec.in DISTFILES = $(DIST_COMMON) $(SOURCES) $(HEADERS) $(TEXINFOS) $(EXTRA_DIST) -TAR = gtar +TAR = tar GZIP_ENV = --best DIST_SUBDIRS = @DIRLTDL@ testsuite gcj include @DIRLTDL@ gcj include DEP_FILES = .deps/$(srcdir)/$(CONVERT_DIR)/gen-from-JIS.P \ @@ -2548,8 +2564,8 @@ DEP_FILES = .deps/$(srcdir)/$(CONVERT_DIR)/gen-from-JIS.P \ .deps/java/util/jar/JarException.P .deps/java/util/jar/JarFile.P \ .deps/java/util/jar/JarInputStream.P \ .deps/java/util/jar/JarOutputStream.P .deps/java/util/jar/Manifest.P \ -.deps/java/util/zip/Adler32.P .deps/java/util/zip/CRC32.P \ -.deps/java/util/zip/CheckedInputStream.P \ +.deps/java/util/natTimeZone.P .deps/java/util/zip/Adler32.P \ +.deps/java/util/zip/CRC32.P .deps/java/util/zip/CheckedInputStream.P \ .deps/java/util/zip/CheckedOutputStream.P \ .deps/java/util/zip/Checksum.P \ .deps/java/util/zip/DataFormatException.P \ @@ -3040,7 +3056,7 @@ distdir: $(DISTFILES) @for file in $(DISTFILES); do \ d=$(srcdir); \ if test -d $$d/$$file; then \ - cp -pr $$d/$$file $(distdir)/$$file; \ + cp -pr $$/$$file $(distdir)/$$file; \ else \ test -f $(distdir)/$$file \ || ln $$d/$$file $(distdir)/$$file 2> /dev/null \ diff --git a/libjava/java/lang/Runtime.java b/libjava/java/lang/Runtime.java index 28befc26d19..65f73a337be 100644 --- a/libjava/java/lang/Runtime.java +++ b/libjava/java/lang/Runtime.java @@ -1,147 +1,785 @@ -// Runtime.java - Runtime class. +/* Runtime.java -- access to the VM process + Copyright (C) 1998, 2002 Free Software Foundation -/* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation +This file is part of GNU Classpath. - This file is part of libgcj. +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. -This software is copyrighted work licensed under the terms of the -Libgcj License. Please consult the file "LIBGCJ_LICENSE" for -details. */ +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ package java.lang; -import java.io.IOException; +import java.io.File; import java.io.InputStream; +import java.io.IOException; import java.io.OutputStream; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; import java.util.StringTokenizer; /** - * @author Tom Tromey <tromey@cygnus.com> - * @date August 27, 1998 + * Runtime represents the Virtual Machine. + * + * @author John Keiser + * @author Eric Blake <ebb9@email.byu.edu> + * @status still missing 1.4 functionality */ - -/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 - * "The Java Language Specification", ISBN 0-201-63451-1 - * plus online API docs for JDK 1.2 beta from http://www.javasoft.com. - * Status: All 1.1 methods exist. exec() is not fully implemented. - */ - +// No idea why this class isn't final, since you can't build a subclass! public class Runtime { - public Process exec (String prog) throws IOException + /** + * The library path, to search when loading libraries. We can also safely use + * this as a lock for synchronization. + */ + private final String[] libpath; + + /** + * The current security manager. This is located here instead of in + * Runtime, to avoid security problems, as well as bootstrap issues. + * Make sure to access it in a thread-safe manner; it is package visible + * to avoid overhead in java.lang. + */ + static SecurityManager securityManager; + + /** + * The default properties defined by the system. This is likewise located + * here instead of in Runtime, to avoid bootstrap issues; it is package + * visible to avoid overhead in java.lang. Note that System will add a + * few more properties to this collection, but that after that, it is + * treated as read-only. + * + * No matter what class you start initialization with, it defers to the + * superclass, therefore Object.<clinit> will be the first Java code + * executed. From there, the bootstrap sequence, up to the point that + * native libraries are loaded (as of March 24, when I traced this + * manually) is as follows: + * + * Object.<clinit> uses a String literal, possibly triggering initialization + * String.<clinit> calls WeakHashMap.<init>, triggering initialization + * AbstractMap, WeakHashMap, WeakHashMap$1 have no dependencies + * String.<clinit> calls CaseInsensitiveComparator.<init>, triggering + * initialization + * CaseInsensitiveComparator has no dependencies + * Object.<clinit> calls System.loadLibrary, triggering initialization + * System.<clinit> calls System.loadLibrary + * System.loadLibrary calls Runtime.getRuntime, triggering initialization + * Runtime.<clinit> calls Properties.<init>, triggering initialization + * Dictionary, Hashtable, and Properties have no dependencies + * Runtime.<clinit> calls insertSystemProperties; the VM must make sure + * that there are not any harmful dependencies + * Runtime.<clinit> calls Runtime.<init> + * Runtime.<init> calls StringTokenizer.<init>, triggering initialization + * StringTokenizer has no dependencies + * System.loadLibrary calls Runtime.loadLibrary + * Runtime.loadLibrary should be able to load the library, although it + * will probably set off another string of initializations from + * ClassLoader first + */ + static Properties defaultProperties = new Properties(); + static { - return exec (prog, null); + insertSystemProperties(defaultProperties); } - public Process exec (String prog, String[] envp) throws IOException + /** + * The thread that started the exit sequence. Access to this field must + * be thread-safe; lock on libpath to avoid deadlock with user code. + * <code>runFinalization()</code> may want to look at this to see if ALL + * finalizers should be run, because the virtual machine is about to halt. + */ + private Thread exitSequence; + + /** + * All shutdown hooks. This is initialized lazily, and set to null once all + * shutdown hooks have run. Access to this field must be thread-safe; lock + * on libpath to avoid deadlock with user code. + */ + private Set shutdownHooks; + + /** True if we should finalize on exit. */ + private boolean finalizeOnExit; + + /** + * The one and only runtime instance. This must appear after the default + * properties have been initialized by the VM. + */ + private static final Runtime current = new Runtime(); + + /** + * Not instantiable by a user, this should only create one instance. + */ + private Runtime() { - StringTokenizer st = new StringTokenizer(prog); - String[] a = new String[st.countTokens ()]; - for (int i = 0; i < a.length; i++) - a[i] = st.nextToken (); - return exec (a, envp); + if (current != null) + throw new InternalError("Attempt to recreate Runtime"); + + // We don't use libpath in the libgcj implementation. We still + // set it to something to allow the various synchronizations to + // work. + libpath = new String[0]; + + init (); } - public Process exec (String[] progarray) throws IOException + /** + * Get the current Runtime object for this JVM. This is necessary to access + * the many instance methods of this class. + * + * @return the current Runtime object + */ + public static Runtime getRuntime() { - return exec (progarray, null); + return current; } - public Process exec (String[] progarray, String[] envp) throws IOException + /** + * Exit the Java runtime. This method will either throw a SecurityException + * or it will never return. The status code is returned to the system; often + * a non-zero status code indicates an abnormal exit. Of course, there is a + * security check, <code>checkExit(status)</code>. + * + * <p>First, all shutdown hooks are run, in unspecified order, and + * concurrently. Next, if finalization on exit has been enabled, all pending + * finalizers are run. Finally, the system calls <code>halt</code>. + * + * <p>If this is run a second time after shutdown has already started, there + * are two actions. If shutdown hooks are still executing, it blocks + * indefinitely. Otherwise, if the status is nonzero it halts immediately; + * if it is zero, it blocks indefinitely. This is typically called by + * <code>System.exit</code>. + * + * @param status the status to exit with + * @throws SecurityException if permission is denied + * @see #addShutdownHook(Thread) + * @see #runFinalizersOnExit(boolean) + * @see #runFinalization() + * @see #halt(int) + */ + public void exit(int status) { - SecurityManager s = System.getSecurityManager(); - if (s != null) - s.checkExec(progarray[0]); - return new ConcreteProcess (progarray, envp); + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkExit(status); + boolean first = false; + synchronized (libpath) // Synch on libpath, not this, to avoid deadlock. + { + if (exitSequence == null) + { + first = true; + exitSequence = Thread.currentThread(); + if (shutdownHooks != null) + { + Iterator i = shutdownHooks.iterator(); + while (i.hasNext()) // Start all shutdown hooks. + try + { + ((Thread) i.next()).start(); + } + catch (IllegalThreadStateException e) + { + i.remove(); + } + } + } + } + if (first) + { + if (shutdownHooks != null) + { + // Check progress of all shutdown hooks. As a hook completes, + // remove it from the set. If a hook calls exit, it removes + // itself from the set, then waits indefinitely on the + // exitSequence thread. Once the set is empty, set it to null to + // signal all finalizer threads that halt may be called. + while (! shutdownHooks.isEmpty()) + { + Thread[] hooks; + synchronized (libpath) + { + hooks = new Thread[shutdownHooks.size()]; + shutdownHooks.toArray(hooks); + } + for (int i = hooks.length; --i >= 0; ) + if (! hooks[i].isAlive()) + synchronized (libpath) + { + shutdownHooks.remove(hooks[i]); + } + try + { + exitSequence.sleep(1); // Give other threads a chance. + } + catch (InterruptedException e) + { + // Ignore, the next loop just starts sooner. + } + } + synchronized (libpath) + { + shutdownHooks = null; + } + } + // XXX Right now, it is the VM that knows whether runFinalizersOnExit + // is true; so the VM must look at exitSequence to decide whether + // this should be run on every object. + runFinalization(); + } + else + synchronized (libpath) + { + if (shutdownHooks != null) + { + shutdownHooks.remove(Thread.currentThread()); + status = 0; // Change status to enter indefinite wait. + } + } + + if (first || status > 0) + halt(status); + while (true) + try + { + exitSequence.join(); + } + catch (InterruptedException e) + { + // Ignore, we've suspended indefinitely to let all shutdown + // hooks complete, and to let any non-zero exits through, because + // this is a duplicate call to exit(0). + } } - private final static void checkExit (int status) + /** + * Register a new shutdown hook. This is invoked when the program exits + * normally (because all non-daemon threads ended, or because + * <code>System.exit</code> was invoked), or when the user terminates + * the virtual machine (such as by typing ^C, or logging off). There is + * a security check to add hooks, + * <code>RuntimePermission("shutdownHooks")<code>. + * + * <p>The hook must be an initialized, but unstarted Thread. The threads + * are run concurrently, and started in an arbitrary order; and user + * threads or daemons may still be running. Once shutdown hooks have + * started, they must all complete, or else you must use <code>halt</code>, + * to actually finish the shutdown sequence. Attempts to modify hooks + * after shutdown has started result in IllegalStateExceptions. + * + * <p>It is imperative that you code shutdown hooks defensively, as you + * do not want to deadlock, and have no idea what other hooks will be + * running concurrently. It is also a good idea to finish quickly, as the + * virtual machine really wants to shut down! + * + * <p>There are no guarantees that such hooks will run, as there are ways + * to forcibly kill a process. But in such a drastic case, shutdown hooks + * would do little for you in the first place. + * + * @param hook an initialized, unstarted Thread + * @throws IllegalArgumentException if the hook is already registered or run + * @throws IllegalStateException if the virtual machine is already in + * the shutdown sequence + * @throws SecurityException if permission is denied + * @since 1.3 + * @see #removeShutdownHook(Thread) + * @see #exit(int) + * @see #halt(int) + */ + public void addShutdownHook(Thread hook) { - SecurityManager s = System.getSecurityManager(); - if (s != null) - s.checkExit(status); + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkPermission(new RuntimePermission("shutdownHooks")); + if (hook.isAlive() || hook.getThreadGroup() == null) + throw new IllegalArgumentException(); + synchronized (libpath) + { + if (exitSequence != null) + throw new IllegalStateException(); + if (shutdownHooks == null) + shutdownHooks = new HashSet(); // Lazy initialization. + if (! shutdownHooks.add(hook)) + throw new IllegalArgumentException(); + } } - public native void exit (int status); - - // Shutdown the runtime without a SecurityManager check. libgcj uses this - // exit function internally. - final native void _exit (int status); + /** + * De-register a shutdown hook. As when you registered it, there is a + * security check to remove hooks, + * <code>RuntimePermission("shutdownHooks")<code>. + * + * @param hook the hook to remove + * @return true if the hook was successfully removed, false if it was not + * registered in the first place + * @throws IllegalStateException if the virtual machine is already in + * the shutdown sequence + * @throws SecurityException if permission is denied + * @since 1.3 + * @see #addShutdownHook(Thread) + * @see #exit(int) + * @see #halt(int) + */ + public boolean removeShutdownHook(Thread hook) + { + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkPermission(new RuntimePermission("shutdownHooks")); + synchronized (libpath) + { + if (exitSequence != null) + throw new IllegalStateException(); + if (shutdownHooks != null) + return shutdownHooks.remove(hook); + } + return false; + } - public native long freeMemory (); - public native void gc (); + /** + * Forcibly terminate the virtual machine. This call never returns. It is + * much more severe than <code>exit</code>, as it bypasses all shutdown + * hooks and initializers. Use caution in calling this! Of course, there is + * a security check, <code>checkExit(status)</code>. + * + * @param status the status to exit with + * @throws SecurityException if permission is denied + * @since 1.3 + * @see #exit(int) + * @see #addShutdownHook(Thread) + */ + public void halt(int status) + { + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkExit(status); + exitInternal(status); + } - // Deprecated in 1.1. We implement what the JCL book says. - public InputStream getLocalizedInputStream (InputStream in) + /** + * Tell the VM to run the finalize() method on every single Object before + * it exits. Note that the JVM may still exit abnormally and not perform + * this, so you still don't have a guarantee. And besides that, this is + * inherently unsafe in multi-threaded code, as it may result in deadlock + * as multiple threads compete to manipulate objects. This value defaults to + * <code>false</code>. There is a security check, <code>checkExit(0)</code>. + * + * @param finalizeOnExit whether to finalize all Objects on exit + * @throws SecurityException if permission is denied + * @see #exit(int) + * @see #gc() + * @since 1.1 + * @deprecated never rely on finalizers to do a clean, thread-safe, + * mop-up from your code + */ + public static void runFinalizersOnExit(boolean finalizeOnExit) { - return in; + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkExit(0); + current.finalizeOnExit = finalizeOnExit; } - // Deprecated in 1.1. We implement what the JCL book says. - public OutputStream getLocalizedOutputStream (OutputStream out) + /** + * Create a new subprocess with the specified command line. Calls + * <code>exec(cmdline, null, null)<code>. A security check is performed, + * <code>checkExec</code>. + * + * @param cmdline the command to call + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmdline is null + * @throws IndexOutOfBoundsException if cmdline is "" + */ + public Process exec(String cmdline) throws IOException { - return out; + return exec(cmdline, null, null); } - public static Runtime getRuntime () + /** + * Create a new subprocess with the specified command line and environment. + * If the environment is null, the process inherits the environment of + * this process. Calls <code>exec(cmdline, env, null)</code>. A security + * check is performed, <code>checkExec</code>. + * + * @param cmdline the command to call + * @param env the environment to use, in the format name=value + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmdline is null, or env has null entries + * @throws IndexOutOfBoundsException if cmdline is "" + */ + public Process exec(String cmdline, String[] env) throws IOException { - return self; + return exec(cmdline, env, null); } - private final void checkLink (String lib) + /** + * Create a new subprocess with the specified command line, environment, and + * working directory. If the environment is null, the process inherits the + * environment of this process. If the directory is null, the process uses + * the current working directory. This splits cmdline into an array, using + * the default StringTokenizer, then calls + * <code>exec(cmdArray, env, dir)</code>. A security check is performed, + * <code>checkExec</code>. + * + * @param cmdline the command to call + * @param env the environment to use, in the format name=value + * @param dir the working directory to use + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmdline is null, or env has null entries + * @throws IndexOutOfBoundsException if cmdline is "" + * @since 1.3 + */ + public Process exec(String cmdline, String[] env, File dir) + throws IOException { - if (lib == null) - throw new NullPointerException (); - SecurityManager s = System.getSecurityManager(); - if (s != null) - s.checkLink(lib); + StringTokenizer t = new StringTokenizer(cmdline); + String[] cmd = new String[t.countTokens()]; + for (int i = 0; i < cmd.length; i++) + cmd[i] = t.nextToken(); + return exec(cmd, env, dir); } - private native void _load (String pathname, boolean do_search); + /** + * Create a new subprocess with the specified command line, already + * tokenized. Calls <code>exec(cmd, null, null)</code>. A security check + * is performed, <code>checkExec</code>. + * + * @param cmd the command to call + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmd is null, or has null entries + * @throws IndexOutOfBoundsException if cmd is length 0 + */ + public Process exec(String[] cmd) throws IOException + { + return exec(cmd, null, null); + } - public void load (String pathname) + /** + * Create a new subprocess with the specified command line, already + * tokenized, and specified environment. If the environment is null, the + * process inherits the environment of this process. Calls + * <code>exec(cmd, env, null)</code>. A security check is performed, + * <code>checkExec</code>. + * + * @param cmd the command to call + * @param env the environment to use, in the format name=value + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmd is null, or cmd or env has null + * entries + * @throws IndexOutOfBoundsException if cmd is length 0 + */ + public Process exec(String[] cmd, String[] env) throws IOException { - _load (pathname, false); + return exec(cmd, env, null); } - public void loadLibrary (String libname) + /** + * Create a new subprocess with the specified command line, already + * tokenized, and the specified environment and working directory. If the + * environment is null, the process inherits the environment of this + * process. If the directory is null, the process uses the current working + * directory. A security check is performed, <code>checkExec</code>. + * + * @param cmd the command to call + * @param env the environment to use, in the format name=value + * @param dir the working directory to use + * @return the Process object + * @throws SecurityException if permission is denied + * @throws IOException if an I/O error occurs + * @throws NullPointerException if cmd is null, or cmd or env has null + * entries + * @throws IndexOutOfBoundsException if cmd is length 0 + * @since 1.3 + * @XXX Ignores dir, for now + */ + public Process exec(String[] cmd, String[] env, File dir) + throws IOException { - _load (libname, true); + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkExec(cmd[0]); + if (env == null) + env = new String[0]; + //XXX Should be: return execInternal(cmd, env, dir); + return execInternal(cmd, env); } - // This is a helper function for the ClassLoader which can load - // compiled libraries. Returns true if library (which is just the - // base name -- path searching is done by this function) was loaded, - // false otherwise. - native boolean loadLibraryInternal (String libname); + /** + * Returns the number of available processors currently available to the + * virtual machine. This number may change over time; so a multi-processor + * program want to poll this to determine maximal resource usage. + * + * @return the number of processors available, at least 1 + */ + public native int availableProcessors(); + + /** + * Find out how much memory is still free for allocating Objects on the heap. + * + * @return the number of bytes of free memory for more Objects + */ + public native long freeMemory(); + + /** + * Find out how much memory total is available on the heap for allocating + * Objects. + * + * @return the total number of bytes of memory for Objects + */ + public native long totalMemory(); + + /** + * Returns the maximum amount of memory the virtual machine can attempt to + * use. This may be <code>Long.MAX_VALUE</code> if there is no inherent + * limit (or if you really do have a 8 exabyte memory!). + * + * @return the maximum number of bytes the virtual machine will attempt + * to allocate + */ + public native long maxMemory(); - public native void runFinalization (); + /** + * Run the garbage collector. This method is more of a suggestion than + * anything. All this method guarantees is that the garbage collector will + * have "done its best" by the time it returns. Notice that garbage + * collection takes place even without calling this method. + */ + public native void gc(); - // This method is static in JDK 1.1, but isn't listed as static in - // the books. It is marked as static in the 1.2 docs. - public static void runFinalizersOnExit (boolean run) + /** + * Run finalization on all Objects that are waiting to be finalized. Again, + * a suggestion, though a stronger one than {@link #gc()}. This calls the + * <code>finalize</code> method of all objects waiting to be collected. + * + * @see #finalize() + */ + public native void runFinalization(); + + /** + * Tell the VM to trace every bytecode instruction that executes (print out + * a trace of it). No guarantees are made as to where it will be printed, + * and the VM is allowed to ignore this request. + * + * @param on whether to turn instruction tracing on + */ + public native void traceInstructions(boolean on); + + /** + * Tell the VM to trace every method call that executes (print out a trace + * of it). No guarantees are made as to where it will be printed, and the + * VM is allowed to ignore this request. + * + * @param on whether to turn method tracing on + */ + public native void traceMethodCalls(boolean on); + + /** + * Load a native library using the system-dependent filename. This is similar + * to loadLibrary, except the only name mangling done is inserting "_g" + * before the final ".so" if the VM was invoked by the name "java_g". There + * may be a security check, of <code>checkLink</code>. + * + * @param filename the file to load + * @throws SecurityException if permission is denied + * @throws UnsatisfiedLinkError if the library is not found + */ + public void load(String filename) { - // The status we pass to the security check is unspecified. - checkExit (0); - self.finalize_on_exit = run; + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkLink(filename); + _load(filename, false); } - public native long totalMemory (); - public native void traceInstructions (boolean on); - public native void traceMethodCalls (boolean on); + /** + * Load a native library using a system-independent "short name" for the + * library. It will be transformed to a correct filename in a + * system-dependent manner (for example, in Windows, "mylib" will be turned + * into "mylib.dll"). This is done as follows: if the context that called + * load has a ClassLoader cl, then <code>cl.findLibrary(libpath)</code> is + * used to convert the name. If that result was null, or there was no class + * loader, this searches each directory of the system property + * <code>java.library.path</code> for a file named + * <code>System.mapLibraryName(libname)</code>. There may be a security + * check, of <code>checkLink</code>. + * + * @param filename the file to load + * @throws SecurityException if permission is denied + * @throws UnsatisfiedLinkError if the library is not found + * @see System#mapLibraryName(String) + * @see ClassLoader#findLibrary(String) + */ + public void loadLibrary(String libname) + { + // This is different from the Classpath implementation, but I + // believe it is more correct. + SecurityManager sm = securityManager; // Be thread-safe! + if (sm != null) + sm.checkLink(libname); + _load(libname, false); + } - // A helper for the constructor. - private final native void init (); + /** + * Return a localized version of this InputStream, meaning all characters + * are localized before they come out the other end. + * + * @param in the stream to localize + * @return the localized stream + * @deprecated <code>InputStreamReader</code> is the preferred way to read + * local encodings + */ + public InputStream getLocalizedInputStream(InputStream in) + { + return in; + } - // The sole constructor. - private Runtime () + /** + * Return a localized version of this OutputStream, meaning all characters + * are localized before they are sent to the other end. + * + * @param out the stream to localize + * @return the localized stream + * @deprecated <code>OutputStreamWriter</code> is the preferred way to write + * local encodings + */ + public OutputStream getLocalizedOutputStream(OutputStream out) { - init (); + return out; } - // Private data. - private static Runtime self = new Runtime (); - // FIXME: for now this can't be static. If it is, our compiler will - // mark it as local, and it will be inaccessible to natRuntime.cc. - private boolean finalize_on_exit; -} + /** + * Native method that actually shuts down the virtual machine. + * + * @param status the status to end the process with + */ + native void exitInternal(int status); + + /** + * Load a file. If it has already been loaded, do nothing. The name has + * already been mapped to a true filename. + * + * @param filename the file to load + * @param do_search True if we should search the load path for the file + */ + native void _load(String filename, boolean do_search); + + /** + *This is a helper function for the ClassLoader which can load + * compiled libraries. Returns true if library (which is just the + * base name -- path searching is done by this function) was loaded, + * false otherwise. + */ + native boolean loadLibraryInternal(String libname); + + /** + * A helper for the constructor which does some internal native + * initialization. + */ + private native void init (); + + /** + * Map a system-independent "short name" to the full file name, and append + * it to the path. + * XXX This method is being replaced by System.mapLibraryName. + * + * @param pathname the path + * @param libname the short version of the library name + * @return the full filename + */ + static native String nativeGetLibname(String pathname, String libname); + + /** + * Execute a process. The command line has already been tokenized, and + * the environment should contain name=value mappings. If directory is null, + * use the current working directory; otherwise start the process in that + * directory. + * XXX Add directory support. + * + * @param cmd the non-null command tokens + * @param env the non-null environment setup + * @param dir the directory to use, may be null + * @return the newly created process + * @throws NullPointerException if cmd or env have null elements + */ + // native Process execInternal(String[] cmd, String[] env, File dir); + native Process execInternal(String[] cmd, String[] env); + + /** + * Get the system properties. This is done here, instead of in System, + * because of the bootstrap sequence. Note that the native code should + * not try to use the Java I/O classes yet, as they rely on the properties + * already existing. The only safe method to use to insert these default + * system properties is {@link Properties#setProperty(String, String)}. + * + * <p>These properties MUST include: + * <dl> + * <dt>java.version <dd>Java version number + * <dt>java.vendor <dd>Java vendor specific string + * <dt>java.vendor.url <dd>Java vendor URL + * <dt>java.home <dd>Java installation directory + * <dt>java.vm.specification.version <dd>VM Spec version + * <dt>java.vm.specification.vendor <dd>VM Spec vendor + * <dt>java.vm.specification.name <dd>VM Spec name + * <dt>java.vm.version <dd>VM implementation version + * <dt>java.vm.vendor <dd>VM implementation vendor + * <dt>java.vm.name <dd>VM implementation name + * <dt>java.specification.version <dd>Java Runtime Environment version + * <dt>java.specification.vendor <dd>Java Runtime Environment vendor + * <dt>java.specification.name <dd>Java Runtime Environment name + * <dt>java.class.version <dd>Java class version number + * <dt>java.class.path <dd>Java classpath + * <dt>java.library.path <dd>Path for finding Java libraries + * <dt>java.io.tmpdir <dd>Default temp file path + * <dt>java.compiler <dd>Name of JIT to use + * <dt>java.ext.dirs <dd>Java extension path + * <dt>os.name <dd>Operating System Name + * <dt>os.arch <dd>Operating System Architecture + * <dt>os.version <dd>Operating System Version + * <dt>file.separator <dd>File separator ("/" on Unix) + * <dt>path.separator <dd>Path separator (":" on Unix) + * <dt>line.separator <dd>Line separator ("\n" on Unix) + * <dt>user.name <dd>User account name + * <dt>user.home <dd>User home directory + * <dt>user.dir <dd>User's current working directory + * </dl> + * + * @param p the Properties object to insert the system properties into + */ + static native void insertSystemProperties(Properties p); +} // class Runtime diff --git a/libjava/java/lang/System.java b/libjava/java/lang/System.java index 9ac160a56f3..edc818fb181 100644 --- a/libjava/java/lang/System.java +++ b/libjava/java/lang/System.java @@ -1,252 +1,563 @@ -// System.java - System-specific info. +/* System.java -- useful methods to interface with the system + Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2, or (at your option) +any later version. + +GNU Classpath is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +02111-1307 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ -/* Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation - - This file is part of libgcj. - -This software is copyrighted work licensed under the terms of the -Libgcj License. Please consult the file "LIBGCJ_LICENSE" for -details. */ package java.lang; -import java.io.FileDescriptor; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilterInputStream; -import java.io.InputStream; -import java.io.PrintStream; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; +import java.io.*; import java.util.Properties; import java.util.PropertyPermission; -import java.util.TimeZone; +import gnu.classpath.Configuration; /** - * @author Tom Tromey <tromey@cygnus.com> - * @date August 27, 1998 - */ - -/* Written using "Java Class Libraries", 2nd edition, ISBN 0-201-31002-3 - * "The Java Language Specification", ISBN 0-201-63451-1 - * plus online API docs for JDK 1.2 beta from http://www.javasoft.com. - * Status: 1.1. Some 1.2 methods missing. Properties code not fully - * implemented. + * System represents system-wide resources; things that represent the + * general environment. As such, all methods are static. + * + * @author John Keiser + * @author Eric Blake <ebb9@email.byu.edu> + * @since 1.0 + * @status still missing 1.4 functionality */ - public final class System { - public static native void arraycopy (Object src, int srcOffset, - Object dst, int dstOffset, - int count); - - public static native long currentTimeMillis (); - - // FIXME: When merging with Classpath, remember to remove the call to - // getDefaultTimeZoneId from java.util.Timezone. - private static native String getSystemTimeZone (); - - // Get the System Timezone as reported by the OS. It should be in - // the form PST8PDT so we'll need to parse it and check that it's valid. - // The result is used to set the user.timezone property in init_properties. - // FIXME: Using the code from Classpath for generating the System - // Timezone IMO is suboptimal because it ignores whether the rules for - // DST match up. - private static String getDefaultTimeZoneId () - { - String sysTimeZoneId = getSystemTimeZone (); - - // Check if this is a valid timezone. Make sure the IDs match - // since getTimeZone returns GMT if no match is found. - TimeZone tz = TimeZone.getTimeZone (sysTimeZoneId); - if (tz.getID ().equals (sysTimeZoneId)) - return sysTimeZoneId; - - // Check if the base part of sysTimeZoneId is a valid timezone that - // matches with daylight usage and rawOffset. Make sure the IDs match - // since getTimeZone returns GMT if no match is found. - // First find start of GMT offset info and any Daylight zone name. - int startGMToffset = 0; - int sysTimeZoneIdLength = sysTimeZoneId.length(); - for (int i = 0; i < sysTimeZoneIdLength && startGMToffset == 0; i++) - { - if (Character.isDigit (sysTimeZoneId.charAt (i))) - startGMToffset = i; - } - - int startDaylightZoneName = 0; - boolean usesDaylight = false; - for (int i = sysTimeZoneIdLength - 1; - i >= 0 && !Character.isDigit (sysTimeZoneId.charAt (i)); --i) - { - startDaylightZoneName = i; - } - if (startDaylightZoneName > 0) - usesDaylight = true; - - int GMToffset = Integer.parseInt (startDaylightZoneName == 0 ? - sysTimeZoneId.substring (startGMToffset) : - sysTimeZoneId.substring (startGMToffset, startDaylightZoneName)); - - // Offset could be in hours or seconds. Convert to millis. - if (GMToffset < 24) - GMToffset *= 60 * 60; - GMToffset *= -1000; - - String tzBasename = sysTimeZoneId.substring (0, startGMToffset); - tz = TimeZone.getTimeZone (tzBasename); - if (tz.getID ().equals (tzBasename) && tz.getRawOffset () == GMToffset) - { - boolean tzUsesDaylight = tz.useDaylightTime (); - if (usesDaylight && tzUsesDaylight || !usesDaylight && !tzUsesDaylight) - return tzBasename; - } - - // If no match, see if a valid timezone has the same attributes as this - // and then use it instead. - String[] IDs = TimeZone.getAvailableIDs (GMToffset); - for (int i = 0; i < IDs.length; ++i) - { - // FIXME: The daylight savings rules may not match the rules - // for the desired zone. - boolean IDusesDaylight = - TimeZone.getTimeZone (IDs[i]).useDaylightTime (); - if (usesDaylight && IDusesDaylight || !usesDaylight && !IDusesDaylight) - return IDs[i]; - } - - // If all else fails, return null. - return null; - } - - public static void exit (int status) + // WARNING: System is a CORE class in the bootstrap cycle. See the comments + // in vm/reference/java/lang/Runtime for implications of this fact. + + /** + * Add to the default properties. The field is stored in Runtime, because + * of the bootstrap sequence; but this adds several useful properties to + * the defaults. Once the default is stabilized, it should not be modified; + * instead it is passed as a parent properties for fast setup of the + * defaults when calling <code>setProperties(null)</code>. + */ + static { - Runtime.getRuntime().exit(status); + // Note that this loadLibrary() takes precedence over the one in Object, + // since Object.<clinit> is waiting for System.<clinit> to complete + // first; but loading a library twice is harmless. + if (Configuration.INIT_LOAD_LIBRARY) + loadLibrary("javalang"); + + Properties defaultProperties = Runtime.defaultProperties; + defaultProperties.put("gnu.cpu.endian", + isWordsBigEndian() ? "big" : "little"); + + // XXX FIXME - Temp hack for old systems that set the wrong property + if (defaultProperties.get("java.io.tmpdir") == null) + defaultProperties.put("java.io.tmpdir", + defaultProperties.get("java.tmpdir")); } - - public static void gc () + + /** + * Stores the current system properties. This can be modified by + * {@link #setProperties(Properties)}, but will never be null, because + * setProperties(null) sucks in the default properties. + */ + private static Properties properties + = new Properties(Runtime.defaultProperties); + + /** + * The standard InputStream. This is assigned at startup and starts its + * life perfectly valid. Although it is marked final, you can change it + * using {@link #setIn(InputStream)} through some hefty VM magic. + * + * <p>This corresponds to the C stdin and C++ cin variables, which + * typically input from the keyboard, but may be used to pipe input from + * other processes or files. That should all be transparent to you, + * however. + */ + public static final InputStream in + = new BufferedInputStream (new FileInputStream(FileDescriptor.in)); + /** + * The standard output PrintStream. This is assigned at startup and + * starts its life perfectly valid. Although it is marked final, you can + * change it using {@link #setOut(PrintStream)} through some hefty VM magic. + * + * <p>This corresponds to the C stdout and C++ cout variables, which + * typically output normal messages to the screen, but may be used to pipe + * output to other processes or files. That should all be transparent to + * you, however. + */ + public static final PrintStream out + = new PrintStream(new BufferedOutputStream (new FileOutputStream(FileDescriptor.out)), true); + /** + * The standard output PrintStream. This is assigned at startup and + * starts its life perfectly valid. Although it is marked final, you can + * change it using {@link #setOut(PrintStream)} through some hefty VM magic. + * + * <p>This corresponds to the C stderr and C++ cerr variables, which + * typically output error messages to the screen, but may be used to pipe + * output to other processes or files. That should all be transparent to + * you, however. + */ + public static final PrintStream err + = new PrintStream(new BufferedOutputStream (new FileOutputStream(FileDescriptor.err)), true); + + /** + * This class is uninstantiable. + */ + private System() { - Runtime.getRuntime().gc(); } - // Marked deprecated in 1.1. We implement what the JCL book says. - public static String getenv (String name) + /** + * Set {@link #in} to a new InputStream. This uses some VM magic to change + * a "final" variable, so naturally there is a security check, + * <code>RuntimePermission("setIO")</code>. + * + * @param in the new InputStream + * @throws SecurityException if permission is denied + * @since 1.1 + */ + public static void setIn(InputStream in) { - throw new Error (); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPermission(new RuntimePermission("setIO")); + setIn0(in); } - private static native void init_properties (); - - public static Properties getProperties () + /** + * Set {@link #out} to a new PrintStream. This uses some VM magic to change + * a "final" variable, so naturally there is a security check, + * <code>RuntimePermission("setIO")</code>. + * + * @param out the new PrintStream + * @throws SecurityException if permission is denied + * @since 1.1 + */ + public static void setOut(PrintStream out) { - if (secman != null) - secman.checkPropertiesAccess(); - if (properties == null) - init_properties (); - return properties; + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPermission(new RuntimePermission("setIO")); + setOut0(out); } - public static String getProperty (String property) + /** + * Set {@link #err} to a new PrintStream. This uses some VM magic to change + * a "final" variable, so naturally there is a security check, + * <code>RuntimePermission("setIO")</code>. + * + * @param err the new PrintStream + * @throws SecurityException if permission is denied + * @since 1.1 + */ + public static void setErr(PrintStream err) { - if (secman != null) - secman.checkPropertyAccess(property); - if (properties == null) - init_properties (); - return properties.getProperty(property); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPermission(new RuntimePermission("setIO")); + setErr0(err); } - public static String getProperty (String property, String defval) + /** + * Set the current SecurityManager. If a security manager already exists, + * then <code>RuntimePermission("setSecurityManager")</code> is checked + * first. Since this permission is denied by the default security manager, + * setting the security manager is often an irreversible action. + * + * <STRONG>Spec Note:</STRONG> Don't ask me, I didn't write it. It looks + * pretty vulnerable; whoever gets to the gate first gets to set the policy. + * There is probably some way to set the original security manager as a + * command line argument to the VM, but I don't know it. + * + * @param sm the new SecurityManager + * @throws SecurityException if permission is denied + */ + public synchronized static void setSecurityManager(SecurityManager sm) { - if (secman != null) - secman.checkPropertyAccess(property); - if (properties == null) - init_properties (); - return properties.getProperty(property, defval); + // Implementation note: the field lives in Runtime because of bootstrap + // initialization issues. This method is synchronized so that no other + // thread changes it to null before this thread makes the change. + if (Runtime.securityManager != null) + Runtime.securityManager.checkPermission + (new RuntimePermission("setSecurityManager")); + Runtime.securityManager = sm; } - public static SecurityManager getSecurityManager () + /** + * Get the current SecurityManager. If the SecurityManager has not been + * set yet, then this method returns null. + * + * @return the current SecurityManager, or null + */ + public static SecurityManager getSecurityManager() { - return secman; + // Implementation note: the field lives in Runtime because of bootstrap + // initialization issues. + return Runtime.securityManager; } - public static native int identityHashCode (Object obj); - - public static void load (String pathname) + /** + * Get the current time, measured in the number of milliseconds from the + * beginning of Jan. 1, 1970. This is gathered from the system clock, with + * any attendant incorrectness (it may be timezone dependent). + * + * @return the current time + * @see java.util.Date + */ + public static native long currentTimeMillis(); + + /** + * Copy one array onto another from <code>src[srcStart]</code> ... + * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ... + * <code>dest[destStart+len-1]</code>. First, the arguments are validated: + * neither array may be null, they must be of compatible types, and the + * start and length must fit within both arrays. Then the copying starts, + * and proceeds through increasing slots. If src and dest are the same + * array, this will appear to copy the data to a temporary location first. + * An ArrayStoreException in the middle of copying will leave earlier + * elements copied, but later elements unchanged. + * + * @param src the array to copy elements from + * @param srcStart the starting position in src + * @param dest the array to copy elements to + * @param destStart the starting position in dest + * @param len the number of elements to copy + * @throws NullPointerException if src or dest is null + * @throws ArrayStoreException if src or dest is not an array, if they are + * not compatible array types, or if an incompatible runtime type + * is stored in dest + * @throws IndexOutOfBoundsException if len is negative, or if the start or + * end copy position in either array is out of bounds + */ + public static native void arraycopy(Object src, int srcStart, + Object dest, int destStart, int len); + + /** + * Get a hash code computed by the VM for the Object. This hash code will + * be the same as Object's hashCode() method. It is usually some + * convolution of the pointer to the Object internal to the VM. It + * follows standard hash code rules, in that it will remain the same for a + * given Object for the lifetime of that Object. + * + * @param o the Object to get the hash code for + * @return the VM-dependent hash code for this Object + * @since 1.1 + */ + public static native int identityHashCode(Object o); + + /** + * Get all the system properties at once. A security check may be performed, + * <code>checkPropertiesAccess</code>. Note that a security manager may + * allow getting a single property, but not the entire group. + * + * <p>The required properties include: + * <dl> + * <dt>java.version <dd>Java version number + * <dt>java.vendor <dd>Java vendor specific string + * <dt>java.vendor.url <dd>Java vendor URL + * <dt>java.home <dd>Java installation directory + * <dt>java.vm.specification.version <dd>VM Spec version + * <dt>java.vm.specification.vendor <dd>VM Spec vendor + * <dt>java.vm.specification.name <dd>VM Spec name + * <dt>java.vm.version <dd>VM implementation version + * <dt>java.vm.vendor <dd>VM implementation vendor + * <dt>java.vm.name <dd>VM implementation name + * <dt>java.specification.version <dd>Java Runtime Environment version + * <dt>java.specification.vendor <dd>Java Runtime Environment vendor + * <dt>java.specification.name <dd>Java Runtime Environment name + * <dt>java.class.version <dd>Java class version number + * <dt>java.class.path <dd>Java classpath + * <dt>java.library.path <dd>Path for finding Java libraries + * <dt>java.io.tmpdir <dd>Default temp file path + * <dt>java.compiler <dd>Name of JIT to use + * <dt>java.ext.dirs <dd>Java extension path + * <dt>os.name <dd>Operating System Name + * <dt>os.arch <dd>Operating System Architecture + * <dt>os.version <dd>Operating System Version + * <dt>file.separator <dd>File separator ("/" on Unix) + * <dt>path.separator <dd>Path separator (":" on Unix) + * <dt>line.separator <dd>Line separator ("\n" on Unix) + * <dt>user.name <dd>User account name + * <dt>user.home <dd>User home directory + * <dt>user.dir <dd>User's current working directory + * </dl> + * + * In addition, gnu defines several other properties, where ? stands for + * each character in '0' through '9': + * <dl> + * <dt> gnu.cpu.endian <dd>big or little + * <dt> gnu.java.io.encoding_scheme_alias.ISO-8859-? <dd>8859_? + * <dt> gnu.java.io.encoding_scheme_alias.iso-8859-? <dd>8859_? + * <dt> gnu.java.io.encoding_scheme_alias.iso8859_? <dd>8859_? + * <dt> gnu.java.io.encoding_scheme_alias.iso-latin-_? <dd>8859_? + * <dt> gnu.java.io.encoding_scheme_alias.latin? <dd>8859_? + * <dt> gnu.java.io.encoding_scheme_alias.UTF-8 <dd>UTF8 + * <dt> gnu.java.io.encoding_scheme_alias.utf-8 <dd>UTF8 + * </dl> + * + * @return the system properties, will never be null + * @throws SecurityException if permission is denied + */ + public static Properties getProperties() { - Runtime.getRuntime().load(pathname); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPropertiesAccess(); + return properties; } - public static void loadLibrary (String libname) + /** + * Set all the system properties at once. A security check may be performed, + * <code>checkPropertiesAccess</code>. Note that a security manager may + * allow setting a single property, but not the entire group. An argument + * of null resets the properties to the startup default. + * + * @param properties the new set of system properties + * @throws SecurityException if permission is denied + */ + public static void setProperties(Properties properties) { - Runtime.getRuntime().loadLibrary(libname); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPropertiesAccess(); + if (properties == null) + properties = new Properties(Runtime.defaultProperties); + System.properties = properties; } - public static void runFinalization () + /** + * Get a single system property by name. A security check may be performed, + * <code>checkPropertyAccess(key)</code>. + * + * @param key the name of the system property to get + * @return the property, or null if not found + * @throws SecurityException if permission is denied + * @throws NullPointerException if key is null + * @throws IllegalArgumentException if key is "" + */ + public static String getProperty(String key) { - Runtime.getRuntime().runFinalization(); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPropertyAccess(key); + else if (key.length() == 0) + throw new IllegalArgumentException("key can't be empty"); + return properties.getProperty(key); } - // Marked as deprecated in 1.2. - public static void runFinalizersOnExit (boolean run) + /** + * Get a single system property by name. A security check may be performed, + * <code>checkPropertyAccess(key)</code>. + * + * @param key the name of the system property to get + * @param def the default + * @return the property, or def if not found + * @throws SecurityException if permission is denied + * @throws NullPointerException if key is null + * @throws IllegalArgumentException if key is "" + */ + public static String getProperty(String key, String def) { - Runtime.getRuntime().runFinalizersOnExit(run); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPropertyAccess(key); + return properties.getProperty(key, def); } - private static void checkSetIO () + /** + * Set a single system property by name. A security check may be performed, + * <code>checkPropertyAccess(key, "write")</code>. + * + * @param key the name of the system property to set + * @param value the new value + * @return the previous value, or null + * @throws SecurityException if permission is denied + * @throws NullPointerException if key is null + * @throws IllegalArgumentException if key is "" + * @since 1.2 + */ + public static String setProperty(String key, String value) { - // In 1.1, we are supposed to call checkExec, but the argument is - // not specified. In 1.2, we are supposed to use checkPermission, - // which doesn't exist in 1.1. - if (secman != null) - secman.checkExec(""); + SecurityManager sm = Runtime.securityManager; // Be thread-safe. + if (sm != null) + sm.checkPermission(new PropertyPermission(key, "write")); + return (String) properties.setProperty(key, value); } - public static native void setErr (PrintStream newErr); - public static native void setIn (InputStream newIn); - public static native void setOut (PrintStream newOut); - - public static void setProperties (Properties props) + /** + * This used to get an environment variable, but following Sun's lead, + * it now throws an Error. Use <code>getProperty</code> instead. + * + * @param name the name of the environment variable + * @return this does not return + * @throws Error this is not supported + * @deprecated use {@link #getProperty(String)}; getenv is not supported + */ + public static String getenv(String name) { - if (secman != null) - secman.checkPropertiesAccess(); - synchronized (System.class) - { - properties = props; - } + throw new Error("getenv no longer supported, use properties instead: " + + name); } - public static String setProperty (String key, String value) + /** + * Terminate the Virtual Machine. This just calls + * <code>Runtime.getRuntime().exit(status)</code>, and never returns. + * Obviously, a security check is in order, <code>checkExit</code>. + * + * @param status the exit status; by convention non-zero is abnormal + * @throws SecurityException if permission is denied + * @see Runtime#exit(int) + */ + public static void exit(int status) { - if (secman != null) - secman.checkPermission (new PropertyPermission (key, "write")); - if (properties == null) - init_properties (); - return (String) properties.setProperty (key, value); + Runtime.getRuntime().exit(status); } - // TODO 1.2. - // public static String mapLibraryName (String libname); + /** + * Calls the garbage collector. This is only a hint, and it is up to the + * implementation what this hint suggests, but it usually causes a + * best-effort attempt to reclaim unused memory from discarded objects. + * This calls <code>Runtime.getRuntime().gc()</code>. + * + * @see Runtime#gc() + */ + public static void gc() + { + Runtime.getRuntime().gc(); + } - public static void setSecurityManager (SecurityManager s) + /** + * Runs object finalization on pending objects. This is only a hint, and + * it is up to the implementation what this hint suggests, but it usually + * causes a best-effort attempt to run finalizers on all objects ready + * to be reclaimed. This calls + * <code>Runtime.getRuntime().runFinalization()</code>. + * + * @see Runtime#runFinalization() + */ + public static void runFinalization() { - if (secman != null) - secman.checkPermission(new RuntimePermission("setSecurityManager")); - secman = s; + Runtime.getRuntime().runFinalization(); } - // Public data. - public static final InputStream in = new BufferedInputStream (new FileInputStream (FileDescriptor.in)); + /** + * Tell the Runtime whether to run finalization before exiting the + * JVM. This is inherently unsafe in multi-threaded applications, + * since it can force initialization on objects which are still in use + * by live threads, leading to deadlock; therefore this is disabled by + * default. There may be a security check, <code>checkExit(0)</code>. This + * calls <code>Runtime.getRuntime().runFinalizersOnExit()</code>. + * + * @param finalizeOnExit whether to run finalizers on exit + * @throws SecurityException if permission is denied + * @see Runtime#runFinalizersOnExit() + * @since 1.1 + * @deprecated never rely on finalizers to do a clean, thread-safe, + * mop-up from your code + */ + public static void runFinalizersOnExit(boolean finalizeOnExit) + { + Runtime.getRuntime().runFinalizersOnExit(finalizeOnExit); + } - public static final PrintStream out = new PrintStream (new BufferedOutputStream (new FileOutputStream (FileDescriptor.out)), true); + /** + * Load a code file using its explicit system-dependent filename. A security + * check may be performed, <code>checkLink</code>. This just calls + * <code>Runtime.getRuntime().load(filename)</code>. + * + * @param filename the code file to load + * @throws SecurityException if permission is denied + * @throws UnsatisfiedLinkError if the file cannot be loaded + * @see Runtime#load(String) + */ + public static void load(String filename) + { + Runtime.getRuntime().load(filename); + } - public static final PrintStream err = new PrintStream (new BufferedOutputStream (new FileOutputStream (FileDescriptor.err)), true); + /** + * Load a library using its explicit system-dependent filename. A security + * check may be performed, <code>checkLink</code>. This just calls + * <code>Runtime.getRuntime().load(filename)</code>. + * + * @param libname the library file to load + * @throws SecurityException if permission is denied + * @throws UnsatisfiedLinkError if the file cannot be loaded + * @see Runtime#load(String) + */ + public static void loadLibrary(String libname) + { + Runtime.getRuntime().loadLibrary(libname); + } - // Don't allow System objects to be made. - private System () + /** + * Convert a library name to its platform-specific variant. + * + * @param libname the library name, as used in <code>loadLibrary</code> + * @return the platform-specific mangling of the name + * @since 1.2 + */ + public static String mapLibraryName(String libname) { + // XXX Fix this!!!! + return Runtime.nativeGetLibname("", libname); } - // Private data. - private static SecurityManager secman = null; - private static Properties properties = null; -} + /** + * Detect big-endian systems. + * + * @return true if the system is big-endian. + */ + static native boolean isWordsBigEndian(); + + /** + * Set {@link #in} to a new InputStream. + * + * @param in the new InputStream + * @see #setIn(InputStream) + */ + private static native void setIn0(InputStream in); + + /** + * Set {@link #out} to a new PrintStream. + * + * @param out the new PrintStream + * @see #setOut(PrintStream) + */ + private static native void setOut0(PrintStream out); + + /** + * Set {@link #err} to a new PrintStream. + * + * @param err the new PrintStream + * @see #setErr(PrintStream) + */ + private static native void setErr0(PrintStream err); +} // class System diff --git a/libjava/java/lang/natRuntime.cc b/libjava/java/lang/natRuntime.cc index a566bf4d999..0783d5b7419 100644 --- a/libjava/java/lang/natRuntime.cc +++ b/libjava/java/lang/natRuntime.cc @@ -14,14 +14,53 @@ details. */ #include <gcj/cni.h> #include <jvm.h> +#include <java-props.h> +#include <java/lang/Long.h> #include <java/lang/Runtime.h> #include <java/lang/UnknownError.h> #include <java/lang/UnsatisfiedLinkError.h> #include <gnu/gcj/runtime/FileDeleter.h> #include <gnu/gcj/runtime/FinalizerThread.h> +#include <java/util/Properties.h> +#include <java/util/TimeZone.h> +#include <java/lang/StringBuffer.h> +#include <java/lang/Process.h> +#include <java/lang/ConcreteProcess.h> #include <jni.h> +#include "platform.h" + +#ifdef HAVE_PWD_H +#include <pwd.h> +#endif +#include <errno.h> + +#ifdef HAVE_UNAME +#include <sys/utsname.h> +#endif + +#ifdef HAVE_LOCALE_H +#include <locale.h> +#endif + +#ifdef HAVE_LANGINFO_H +#include <langinfo.h> +#endif + +#if TIME_WITH_SYS_TIME +# include <sys/time.h> +# include <time.h> +#else +# if HAVE_SYS_TIME_H +# include <sys/time.h> +# else +# include <time.h> +# endif +#endif + + + #ifdef USE_LTDL #include <ltdl.h> @@ -83,21 +122,16 @@ _Jv_FindSymbolInExecutable (const char *symname) #endif /* USE_LTDL */ -void -java::lang::Runtime::exit (jint status) -{ - checkExit (status); - _exit (status); -} + void -java::lang::Runtime::_exit (jint status) +java::lang::Runtime::exitInternal (jint status) { // Make status right for Unix. This is perhaps strange. if (status < 0 || status > 255) status = 255; - if (finalize_on_exit) + if (finalizeOnExit) _Jv_RunAllFinalizers (); // Delete all files registered with File.deleteOnExit() @@ -122,7 +156,6 @@ void java::lang::Runtime::_load (jstring path, jboolean do_search) { JvSynchronize sync (this); - checkLink (path); using namespace java::lang; #ifdef USE_LTDL jint len = _Jv_GetStringUTFLength (path); @@ -205,7 +238,6 @@ java::lang::Runtime::loadLibraryInternal (jstring lib) void java::lang::Runtime::init (void) { - finalize_on_exit = false; #ifdef USE_LTDL lt_dlinit (); lt_dlhandle self = lt_dlopen (NULL); @@ -226,6 +258,14 @@ java::lang::Runtime::totalMemory (void) return _Jv_GCTotalMemory (); } +jlong +java::lang::Runtime::maxMemory (void) +{ + // We don't have a maximum. FIXME: we might if we ask the GC for + // one. + return Long::MAX_VALUE; +} + void java::lang::Runtime::traceInstructions (jboolean) { @@ -237,3 +277,318 @@ java::lang::Runtime::traceMethodCalls (jboolean) { // Do nothing. } + +#if ! defined (DEFAULT_FILE_ENCODING) && defined (HAVE_ICONV) \ + && defined (HAVE_NL_LANGINFO) + +static char * +file_encoding () +{ + setlocale (LC_CTYPE, ""); + char *e = nl_langinfo (CODESET); + if (e == NULL || *e == '\0') + e = "8859_1"; + return e; +} + +#define DEFAULT_FILE_ENCODING file_encoding () + +#endif + +#ifndef DEFAULT_FILE_ENCODING +#define DEFAULT_FILE_ENCODING "8859_1" +#endif + +static char *default_file_encoding = DEFAULT_FILE_ENCODING; + +#if HAVE_GETPWUID_R +/* Use overload resolution to find out the signature of getpwuid_r. */ + + /* This is Posix getpwuid_r. */ +template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> +static inline int +getpwuid_adaptor(int (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, + T_buf *buf_r, T_len len_r, + T_passwd **pwd_entry_ptr), + uid_t user_id, struct passwd *pwd_r, + char *buf_r, size_t len_r, struct passwd **pwd_entry) +{ + return getpwuid_r (user_id, pwd_r, buf_r, len_r, pwd_entry); +} + +/* This is used on HPUX 10.20 */ +template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> +static inline int +getpwuid_adaptor(int (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, + T_buf *buf_r, T_len len_r), + uid_t user_id, struct passwd *pwd_r, + char *buf_r, size_t len_r, struct passwd **pwd_entry) +{ + return getpwuid_r (user_id, pwd_r, buf_r, len_r); +} + +/* This is used on IRIX 5.2. */ +template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> +static inline int +getpwuid_adaptor(T_passwd * (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, + T_buf *buf_r, T_len len_r), + uid_t user_id, struct passwd *pwd_r, + char *buf_r, size_t len_r, struct passwd **pwd_entry) +{ + *pwd_entry = getpwuid_r (user_id, pwd_r, buf_r, len_r); + return (*pwd_entry == NULL) ? errno : 0; +} +#endif + +void +java::lang::Runtime::insertSystemProperties (java::util::Properties *newprops) +{ + // A convenience define. +#define SET(Prop,Val) \ + newprops->put(JvNewStringLatin1 (Prop), JvNewStringLatin1 (Val)) + + // A mixture of the Java Product Versioning Specification + // (introduced in 1.2), and earlier versioning properties. + SET ("java.version", GCJVERSION); + SET ("java.vendor", "Free Software Foundation, Inc."); + SET ("java.vendor.url", "http://gcc.gnu.org/java/"); + SET ("java.class.version", "46.0"); + SET ("java.vm.specification.version", "1.0"); + SET ("java.vm.specification.name", "Java(tm) Virtual Machine Specification"); + SET ("java.vm.specification.vendor", "Sun Microsystems Inc."); + SET ("java.vm.version", __VERSION__); + SET ("java.vm.vendor", "Free Software Foundation, Inc."); + SET ("java.vm.name", "GNU libgcj"); + SET ("java.specification.version", "1.3"); + SET ("java.specification.name", "Java(tm) Platform API Specification"); + SET ("java.specification.vendor", "Sun Microsystems Inc."); + + char value[100]; +#define NAME "GNU libgcj " + strcpy (value, NAME); + strncpy (value + sizeof (NAME) - 1, __VERSION__, + sizeof(value) - sizeof(NAME)); + value[sizeof (value) - 1] = '\0'; + jstring version = JvNewStringLatin1 (value); + newprops->put (JvNewStringLatin1 ("java.fullversion"), version); + newprops->put (JvNewStringLatin1 ("java.vm.info"), version); + + // This definition is rather arbitrary: we choose $(prefix). In + // part we do this because most people specify only --prefix and + // nothing else when installing gcj. Plus, people are free to + // redefine `java.home' with `-D' if necessary. + SET ("java.home", PREFIX); + + SET ("file.encoding", default_file_encoding); + +#ifdef HAVE_UNAME + struct utsname u; + if (! uname (&u)) + { + SET ("os.name", u.sysname); + SET ("os.arch", u.machine); + SET ("os.version", u.release); + } + else + { + SET ("os.name", "unknown"); + SET ("os.arch", "unknown"); + SET ("os.version", "unknown"); + } +#endif /* HAVE_UNAME */ + +#ifndef NO_GETUID +#ifdef HAVE_PWD_H + uid_t user_id = getuid (); + struct passwd *pwd_entry; + +#ifdef HAVE_GETPWUID_R + struct passwd pwd_r; + size_t len_r = 200; + char *buf_r = (char *) _Jv_AllocBytes (len_r); + + while (buf_r != NULL) + { + int r = getpwuid_adaptor (getpwuid_r, user_id, &pwd_r, + buf_r, len_r, &pwd_entry); + if (r == 0) + break; + else if (r != ERANGE) + { + pwd_entry = NULL; + break; + } + len_r *= 2; + buf_r = (char *) _Jv_AllocBytes (len_r); + } +#else + pwd_entry = getpwuid (user_id); +#endif /* HAVE_GETPWUID_R */ + + if (pwd_entry != NULL) + { + SET ("user.name", pwd_entry->pw_name); + SET ("user.home", pwd_entry->pw_dir); + } +#endif /* HAVE_PWD_H */ +#endif /* NO_GETUID */ + +#ifdef HAVE_GETCWD +#ifdef HAVE_UNISTD_H + /* Use getcwd to set "user.dir". */ + int buflen = 250; + char *buffer = (char *) malloc (buflen); + while (buffer != NULL) + { + if (getcwd (buffer, buflen) != NULL) + { + SET ("user.dir", buffer); + break; + } + if (errno != ERANGE) + break; + buflen = 2 * buflen; + buffer = (char *) realloc (buffer, buflen); + } + if (buffer != NULL) + free (buffer); +#endif /* HAVE_UNISTD_H */ +#endif /* HAVE_GETCWD */ + + // Set user locale properties based on setlocale() +#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES) + // We let the user choose the locale. However, since Java differs + // from POSIX, we arbitrarily pick LC_MESSAGES as determining the + // Java locale. We can't use LC_ALL because it might return a full + // list of all the settings. If we don't have LC_MESSAGES then we + // just default to `en_US'. + setlocale (LC_ALL, ""); + char *locale = setlocale (LC_MESSAGES, ""); + if (locale && strlen (locale) >= 2) + { + char buf[3]; + buf[2] = '\0'; + // copy the first two chars to user.language + strncpy (buf, locale, 2); + SET ("user.language", buf); + // if the next char is a '_', copy the two after that to user.region + locale += 2; + if (locale[0] == '_') + { + locale++; + strncpy (buf, locale, 2); + SET ("user.region", buf); + } + } + else +#endif /* HAVE_SETLOCALE and HAVE_LC_MESSAGES */ + { + SET ("user.language", "en"); + SET ("user.region", "US"); + } + + // Set some properties according to whatever was compiled in with + // `-D'. + for (int i = 0; _Jv_Compiler_Properties[i]; ++i) + { + const char *s, *p; + // Find the `='. + for (s = p = _Jv_Compiler_Properties[i]; *s && *s != '='; ++s) + ; + jstring name = JvNewStringLatin1 (p, s - p); + jstring val = JvNewStringLatin1 (*s == '=' ? s + 1 : s); + newprops->put (name, val); + } + + // Set the system properties from the user's environment. +#ifndef DISABLE_GETENV_PROPERTIES + if (_Jv_Environment_Properties) + { + size_t i = 0; + + while (_Jv_Environment_Properties[i].key) + { + SET (_Jv_Environment_Properties[i].key, + _Jv_Environment_Properties[i].value); + i++; + } + } +#endif + + if (_Jv_Jar_Class_Path) + newprops->put(JvNewStringLatin1 ("java.class.path"), + JvNewStringLatin1 (_Jv_Jar_Class_Path)); + else + { + // FIXME: find libgcj.zip and append its path? + char *classpath = ::getenv("CLASSPATH"); + jstring cp = newprops->getProperty (JvNewStringLatin1("java.class.path")); + java::lang::StringBuffer *sb = new java::lang::StringBuffer (); + + if (classpath) + { + sb->append (JvNewStringLatin1 (classpath)); +#ifdef WIN32 + sb->append ((jchar) ';'); +#else + sb->append ((jchar) ':'); +#endif + } + if (cp != NULL) + sb->append (cp); + else + sb->append ((jchar) '.'); + + newprops->put(JvNewStringLatin1 ("java.class.path"), + sb->toString ()); + } + + // Allow platform specific settings and overrides. + _Jv_platform_initProperties (newprops); +} + +java::lang::Process * +java::lang::Runtime::execInternal (jstringArray cmd, + jstringArray env) +{ + return new java::lang::ConcreteProcess (cmd, env); +} + +jint +java::lang::Runtime::availableProcessors (void) +{ + // FIXME: find the real value. + return 1; +} + +jstring +java::lang::Runtime::nativeGetLibname (jstring pathname, jstring libname) +{ + java::lang::StringBuffer *sb = new java::lang::StringBuffer (); + sb->append(pathname); + if (pathname->length() > 0) + { + // FIXME: use platform function here. +#ifdef WIN32 + sb->append ((jchar) '\\'); +#else + sb->append ((jchar) '/'); +#endif + } + + // FIXME: use platform function here. +#ifndef WIN32 + sb->append (JvNewStringLatin1 ("lib")); +#endif + + sb->append(libname); + + // FIXME: use platform function here. +#ifdef WIN32 + sb->append (JvNewStringLatin1 ("dll")); +else + sb->append (JvNewStringLatin1 ("so")); +#endif + + return sb->toString(); +} diff --git a/libjava/java/lang/natSystem.cc b/libjava/java/lang/natSystem.cc index 386d8b0b8f4..ffa3f1a5053 100644 --- a/libjava/java/lang/natSystem.cc +++ b/libjava/java/lang/natSystem.cc @@ -14,73 +14,35 @@ details. */ #include <string.h> #include <stdlib.h> -#include "platform.h" - -#ifdef HAVE_PWD_H -#include <pwd.h> -#endif -#include <errno.h> - -#ifdef HAVE_UNAME -#include <sys/utsname.h> -#endif - -#ifdef HAVE_LOCALE_H -#include <locale.h> -#endif - -#ifdef HAVE_LANGINFO_H -#include <langinfo.h> -#endif - -#if TIME_WITH_SYS_TIME -# include <sys/time.h> -# include <time.h> -#else -# if HAVE_SYS_TIME_H -# include <sys/time.h> -# else -# include <time.h> -# endif -#endif - #include <gcj/cni.h> #include <jvm.h> -#include <java-props.h> #include <java/lang/System.h> #include <java/lang/Class.h> #include <java/lang/ArrayStoreException.h> #include <java/lang/ArrayIndexOutOfBoundsException.h> #include <java/lang/NullPointerException.h> -#include <java/lang/StringBuffer.h> -#include <java/util/Properties.h> -#include <java/util/TimeZone.h> #include <java/io/PrintStream.h> #include <java/io/InputStream.h> +#include "platform.h" + void -java::lang::System::setErr (java::io::PrintStream *newErr) +java::lang::System::setErr0 (java::io::PrintStream *newErr) { - checkSetIO (); - // This violates `final' semantics. Oh well. err = newErr; } void -java::lang::System::setIn (java::io::InputStream *newIn) +java::lang::System::setIn0 (java::io::InputStream *newIn) { - checkSetIO (); - // This violates `final' semantics. Oh well. in = newIn; } void -java::lang::System::setOut (java::io::PrintStream *newOut) +java::lang::System::setOut0 (java::io::PrintStream *newOut) { - checkSetIO (); - // This violates `final' semantics. Oh well. out = newOut; } @@ -167,346 +129,15 @@ java::lang::System::identityHashCode (jobject obj) return _Jv_HashCode (obj); } -#if ! defined (DEFAULT_FILE_ENCODING) && defined (HAVE_ICONV) \ - && defined (HAVE_NL_LANGINFO) - -static char * -file_encoding () -{ - setlocale (LC_CTYPE, ""); - char *e = nl_langinfo (CODESET); - if (e == NULL || *e == '\0') - e = "8859_1"; - return e; -} - -#define DEFAULT_FILE_ENCODING file_encoding () - -#endif - -#ifndef DEFAULT_FILE_ENCODING -#define DEFAULT_FILE_ENCODING "8859_1" -#endif - -static char *default_file_encoding = DEFAULT_FILE_ENCODING; - -#if HAVE_GETPWUID_R -/* Use overload resolution to find out the signature of getpwuid_r. */ - - /* This is Posix getpwuid_r. */ -template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> -static inline int -getpwuid_adaptor(int (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, - T_buf *buf_r, T_len len_r, - T_passwd **pwd_entry_ptr), - uid_t user_id, struct passwd *pwd_r, - char *buf_r, size_t len_r, struct passwd **pwd_entry) -{ - return getpwuid_r (user_id, pwd_r, buf_r, len_r, pwd_entry); -} - -/* This is used on HPUX 10.20 */ -template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> -static inline int -getpwuid_adaptor(int (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, - T_buf *buf_r, T_len len_r), - uid_t user_id, struct passwd *pwd_r, - char *buf_r, size_t len_r, struct passwd **pwd_entry) -{ - return getpwuid_r (user_id, pwd_r, buf_r, len_r); -} - -/* This is used on IRIX 5.2. */ -template <typename T_uid, typename T_passwd, typename T_buf, typename T_len> -static inline int -getpwuid_adaptor(T_passwd * (*getpwuid_r)(T_uid user_id, T_passwd *pwd_r, - T_buf *buf_r, T_len len_r), - uid_t user_id, struct passwd *pwd_r, - char *buf_r, size_t len_r, struct passwd **pwd_entry) -{ - *pwd_entry = getpwuid_r (user_id, pwd_r, buf_r, len_r); - return (*pwd_entry == NULL) ? errno : 0; -} -#endif - -/* - * This method returns a time zone string that is used by init_properties - * to set the default timezone property 'user.timezone'. That value is - * used by default as a key into the timezone table used by the - * java::util::TimeZone class. - */ -jstring -java::lang::System::getSystemTimeZone (void) -{ - struct tm *tim; - time_t current_time; - long tzoffset; - const char *tz1, *tz2; - char *tzid; - - current_time = time(0); - - mktime(tim = localtime(¤t_time)); -#ifdef STRUCT_TM_HAS_GMTOFF - // tm_gmtoff is secs EAST of UTC. - tzoffset = -(tim->tm_gmtoff) + tim->tm_isdst * 3600L; -#elif HAVE_UNDERSCORE_TIMEZONE - tzoffset = _timezone; -#elif HAVE_TIMEZONE - // timezone is secs WEST of UTC. - tzoffset = timezone; -#else - // FIXME: there must be another global if neither tm_gmtoff nor timezone - // is available, esp. if tzname is valid. - // Richard Earnshaw <rearnsha@arm.com> has suggested using difftime to - // calculate between gmtime and localtime (and accounting for possible - // daylight savings time) as an alternative. - tzoffset = 0L; -#endif - -#ifdef HAVE_TM_ZONE - tz1 = tim->tm_zone; - tz2 = ""; -#elif defined (HAVE_TZNAME) - tz1 = tzname[0]; - tz2 = strcmp (tzname[0], tzname[1]) ? tzname[1] : ""; -#else - // Some targets have no concept of timezones. - tz1 = "???"; - tz2 = tz1; -#endif - - if ((tzoffset % 3600) == 0) - tzoffset = tzoffset / 3600; - - tzid = (char*) _Jv_Malloc (strlen(tz1) + strlen(tz2) + 6); - sprintf(tzid, "%s%ld%s", tz1, tzoffset, tz2); - jstring retval = JvNewStringUTF (tzid); - _Jv_Free (tzid); - - return retval; -} - -void -java::lang::System::init_properties (void) +jboolean +java::lang::System::isWordsBigEndian (void) { - JvSynchronize sync (&java::lang::System::class$); - - if (properties != NULL) - return; - - java::util::Properties* newprops = new java::util::Properties (); - - // A convenience define. -#define SET(Prop,Val) \ - newprops->put(JvNewStringLatin1 (Prop), JvNewStringLatin1 (Val)) - - // A mixture of the Java Product Versioning Specification - // (introduced in 1.2), and earlier versioning properties. - SET ("java.version", GCJVERSION); - SET ("java.vendor", "Free Software Foundation, Inc."); - SET ("java.vendor.url", "http://gcc.gnu.org/java/"); - SET ("java.class.version", "46.0"); - SET ("java.vm.specification.version", "1.0"); - SET ("java.vm.specification.name", "Java(tm) Virtual Machine Specification"); - SET ("java.vm.specification.vendor", "Sun Microsystems Inc."); - SET ("java.vm.version", __VERSION__); - SET ("java.vm.vendor", "Free Software Foundation, Inc."); - SET ("java.vm.name", "GNU libgcj"); - SET ("java.specification.version", "1.3"); - SET ("java.specification.name", "Java(tm) Platform API Specification"); - SET ("java.specification.vendor", "Sun Microsystems Inc."); - - char value[100]; -#define NAME "GNU libgcj " - strcpy (value, NAME); - strncpy (value + sizeof (NAME) - 1, __VERSION__, - sizeof(value) - sizeof(NAME)); - value[sizeof (value) - 1] = '\0'; - jstring version = JvNewStringLatin1 (value); - newprops->put (JvNewStringLatin1 ("java.fullversion"), version); - newprops->put (JvNewStringLatin1 ("java.vm.info"), version); - - // This definition is rather arbitrary: we choose $(prefix). In - // part we do this because most people specify only --prefix and - // nothing else when installing gcj. Plus, people are free to - // redefine `java.home' with `-D' if necessary. - SET ("java.home", PREFIX); - - SET ("file.encoding", default_file_encoding); - -#ifdef HAVE_UNAME - struct utsname u; - if (! uname (&u)) - { - SET ("os.name", u.sysname); - SET ("os.arch", u.machine); - SET ("os.version", u.release); - } - else - { - SET ("os.name", "unknown"); - SET ("os.arch", "unknown"); - SET ("os.version", "unknown"); - } -#endif /* HAVE_UNAME */ - -#ifndef NO_GETUID -#ifdef HAVE_PWD_H - uid_t user_id = getuid (); - struct passwd *pwd_entry; - -#ifdef HAVE_GETPWUID_R - struct passwd pwd_r; - size_t len_r = 200; - char *buf_r = (char *) _Jv_AllocBytes (len_r); - - while (buf_r != NULL) - { - int r = getpwuid_adaptor (getpwuid_r, user_id, &pwd_r, - buf_r, len_r, &pwd_entry); - if (r == 0) - break; - else if (r != ERANGE) - { - pwd_entry = NULL; - break; - } - len_r *= 2; - buf_r = (char *) _Jv_AllocBytes (len_r); - } -#else - pwd_entry = getpwuid (user_id); -#endif /* HAVE_GETPWUID_R */ - - if (pwd_entry != NULL) - { - SET ("user.name", pwd_entry->pw_name); - SET ("user.home", pwd_entry->pw_dir); - } -#endif /* HAVE_PWD_H */ -#endif /* NO_GETUID */ - -#ifdef HAVE_GETCWD -#ifdef HAVE_UNISTD_H - /* Use getcwd to set "user.dir". */ - int buflen = 250; - char *buffer = (char *) malloc (buflen); - while (buffer != NULL) - { - if (getcwd (buffer, buflen) != NULL) - { - SET ("user.dir", buffer); - break; - } - if (errno != ERANGE) - break; - buflen = 2 * buflen; - buffer = (char *) realloc (buffer, buflen); - } - if (buffer != NULL) - free (buffer); -#endif /* HAVE_UNISTD_H */ -#endif /* HAVE_GETCWD */ - - // Set user locale properties based on setlocale() -#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES) - // We let the user choose the locale. However, since Java differs - // from POSIX, we arbitrarily pick LC_MESSAGES as determining the - // Java locale. We can't use LC_ALL because it might return a full - // list of all the settings. If we don't have LC_MESSAGES then we - // just default to `en_US'. - setlocale (LC_ALL, ""); - char *locale = setlocale (LC_MESSAGES, ""); - if (locale && strlen (locale) >= 2) - { - char buf[3]; - buf[2] = '\0'; - // copy the first two chars to user.language - strncpy (buf, locale, 2); - SET ("user.language", buf); - // if the next char is a '_', copy the two after that to user.region - locale += 2; - if (locale[0] == '_') - { - locale++; - strncpy (buf, locale, 2); - SET ("user.region", buf); - } - } - else -#endif /* HAVE_SETLOCALE and HAVE_LC_MESSAGES */ - { - SET ("user.language", "en"); - SET ("user.region", "US"); - } - - // Set the "user.timezone" property. - jstring timezone = getDefaultTimeZoneId (); - if (timezone != NULL) - newprops->put (JvNewStringLatin1 ("user.timezone"), timezone); - - // Set some properties according to whatever was compiled in with - // `-D'. - for (int i = 0; _Jv_Compiler_Properties[i]; ++i) - { - const char *s, *p; - // Find the `='. - for (s = p = _Jv_Compiler_Properties[i]; *s && *s != '='; ++s) - ; - jstring name = JvNewStringLatin1 (p, s - p); - jstring val = JvNewStringLatin1 (*s == '=' ? s + 1 : s); - newprops->put (name, val); - } - - // Set the system properties from the user's environment. -#ifndef DISABLE_GETENV_PROPERTIES - if (_Jv_Environment_Properties) - { - size_t i = 0; - - while (_Jv_Environment_Properties[i].key) - { - SET (_Jv_Environment_Properties[i].key, - _Jv_Environment_Properties[i].value); - i++; - } - } -#endif - - if (_Jv_Jar_Class_Path) - newprops->put(JvNewStringLatin1 ("java.class.path"), - JvNewStringLatin1 (_Jv_Jar_Class_Path)); - else - { - // FIXME: find libgcj.zip and append its path? - char *classpath = ::getenv("CLASSPATH"); - jstring cp = newprops->getProperty (JvNewStringLatin1("java.class.path")); - java::lang::StringBuffer *sb = new java::lang::StringBuffer (); - - if (classpath) - { - sb->append (JvNewStringLatin1 (classpath)); -#ifdef WIN32 - sb->append ((jchar) ';'); -#else - sb->append ((jchar) ':'); -#endif - } - if (cp != NULL) - sb->append (cp); - else - sb->append ((jchar) '.'); - - newprops->put(JvNewStringLatin1 ("java.class.path"), - sb->toString ()); - } - - // Allow platform specific settings and overrides. - _Jv_platform_initProperties (newprops); - - // Finally, set the field. This ensures that concurrent getProperty() - // calls will return initialized values without requiring them to be - // synchronized in the common case. - properties = newprops; + union + { + long lval; + char cval; + } u; + + u.lval = 1; + return u.cval == 0; } diff --git a/libjava/java/util/TimeZone.java b/libjava/java/util/TimeZone.java index 974065a6e65..eba22363d18 100644 --- a/libjava/java/util/TimeZone.java +++ b/libjava/java/util/TimeZone.java @@ -1,5 +1,5 @@ /* java.util.TimeZone - Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc. + Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. @@ -38,6 +38,7 @@ exception statement from your version. */ package java.util; import java.text.DateFormatSymbols; +import gnu.classpath.Configuration; /** * This class represents a time zone offset and handles daylight savings. @@ -753,16 +754,32 @@ public abstract class TimeZone implements java.io.Serializable, Cloneable /* Look up default timezone */ static { - // System.loadLibrary("javautil"); - + if (Configuration.INIT_LOAD_LIBRARY) + { + System.loadLibrary("javautil"); + } String tzid = System.getProperty("user.timezone"); if (tzid == null) + tzid = getDefaultTimeZoneId(); + + if (tzid == null) tzid = "GMT"; defaultZone = getTimeZone(tzid); } + /* This method returns us a time zone id string which is in the + form <standard zone name><GMT offset><daylight time zone name>. + The GMT offset is in seconds, except where it is evenly divisible + by 3600, then it is in hours. If the zone does not observe + daylight time, then the daylight zone name is omitted. Examples: + in Chicago, the timezone would be CST6CDT. In Indianapolis + (which does not have Daylight Savings Time) the string would + be EST5 + */ + private static native String getDefaultTimeZoneId(); + /** * Gets the time zone offset, for current date, modified in case of * daylight savings. This is the offset to add to UTC to get the local diff --git a/libjava/java/util/natTimeZone.cc b/libjava/java/util/natTimeZone.cc new file mode 100644 index 00000000000..007f689209f --- /dev/null +++ b/libjava/java/util/natTimeZone.cc @@ -0,0 +1,154 @@ +// natTimeZone.cc -- Native side of TimeZone class. + +/* Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation + + This file is part of libgcj. + +This software is copyrighted work licensed under the terms of the +Libgcj License. Please consult the file "LIBGCJ_LICENSE" for +details. */ + +#include <config.h> + +#include <gcj/cni.h> +#include <jvm.h> + +#include <java/util/TimeZone.h> +#include <java/lang/Character.h> +#include <java/lang/Integer.h> + +/* + * This method returns a time zone string that is used by init_properties + * to set the default timezone property 'user.timezone'. That value is + * used by default as a key into the timezone table used by the + * java::util::TimeZone class. + */ +static jstring +getSystemTimeZone (void) +{ + struct tm *tim; + time_t current_time; + long tzoffset; + const char *tz1, *tz2; + char *tzid; + + current_time = time(0); + + mktime(tim = localtime(¤t_time)); +#ifdef STRUCT_TM_HAS_GMTOFF + // tm_gmtoff is secs EAST of UTC. + tzoffset = -(tim->tm_gmtoff) + tim->tm_isdst * 3600L; +#elif HAVE_UNDERSCORE_TIMEZONE + tzoffset = _timezone; +#elif HAVE_TIMEZONE + // timezone is secs WEST of UTC. + tzoffset = timezone; +#else + // FIXME: there must be another global if neither tm_gmtoff nor timezone + // is available, esp. if tzname is valid. + // Richard Earnshaw <rearnsha@arm.com> has suggested using difftime to + // calculate between gmtime and localtime (and accounting for possible + // daylight savings time) as an alternative. + tzoffset = 0L; +#endif + +#ifdef HAVE_TM_ZONE + tz1 = tim->tm_zone; + tz2 = ""; +#elif defined (HAVE_TZNAME) + tz1 = tzname[0]; + tz2 = strcmp (tzname[0], tzname[1]) ? tzname[1] : ""; +#else + // Some targets have no concept of timezones. + tz1 = "???"; + tz2 = tz1; +#endif + + if ((tzoffset % 3600) == 0) + tzoffset = tzoffset / 3600; + + tzid = (char*) _Jv_Malloc (strlen(tz1) + strlen(tz2) + 6); + sprintf(tzid, "%s%ld%s", tz1, tzoffset, tz2); + jstring retval = JvNewStringUTF (tzid); + _Jv_Free (tzid); + + return retval; +} + +// Get the System Timezone as reported by the OS. It should be in +// the form PST8PDT so we'll need to parse it and check that it's valid. +// FIXME: Using the code from Classpath for generating the System +// Timezone IMO is suboptimal because it ignores whether the rules for +// DST match up. +jstring +java::util::TimeZone::getDefaultTimeZoneId () +{ + jstring sysTimeZoneId = getSystemTimeZone (); + + using namespace java::lang; + + // Check if this is a valid timezone. Make sure the IDs match + // since getTimeZone returns GMT if no match is found. + TimeZone *tz = TimeZone::getTimeZone (sysTimeZoneId); + if (tz->getID ()->equals (sysTimeZoneId)) + return sysTimeZoneId; + + // Check if the base part of sysTimeZoneId is a valid timezone that + // matches with daylight usage and rawOffset. Make sure the IDs match + // since getTimeZone returns GMT if no match is found. + // First find start of GMT offset info and any Daylight zone name. + int startGMToffset = 0; + int sysTimeZoneIdLength = sysTimeZoneId->length(); + for (int i = 0; i < sysTimeZoneIdLength && startGMToffset == 0; i++) + { + if (Character::isDigit (sysTimeZoneId->charAt (i))) + startGMToffset = i; + } + + int startDaylightZoneName = 0; + jboolean usesDaylight = false; + for (int i = sysTimeZoneIdLength - 1; + i >= 0 && !Character::isDigit (sysTimeZoneId->charAt (i)); --i) + { + startDaylightZoneName = i; + } + if (startDaylightZoneName > 0) + usesDaylight = true; + + int GMToffset + = Integer::parseInt (startDaylightZoneName == 0 ? + sysTimeZoneId->substring (startGMToffset) : + sysTimeZoneId->substring (startGMToffset, + startDaylightZoneName)); + + // Offset could be in hours or seconds. Convert to millis. + if (GMToffset < 24) + GMToffset *= 60 * 60; + GMToffset *= -1000; + + jstring tzBasename = sysTimeZoneId->substring (0, startGMToffset); + tz = TimeZone::getTimeZone (tzBasename); + if (tz->getID ()->equals (tzBasename) && tz->getRawOffset () == GMToffset) + { + jboolean tzUsesDaylight = tz->useDaylightTime (); + if (usesDaylight && tzUsesDaylight || !usesDaylight && !tzUsesDaylight) + return tzBasename; + } + + // If no match, see if a valid timezone has the same attributes as this + // and then use it instead. + jstringArray IDs = TimeZone::getAvailableIDs (GMToffset); + jstring *elts = elements (IDs); + for (int i = 0; i < IDs->length; ++i) + { + // FIXME: The daylight savings rules may not match the rules + // for the desired zone. + jboolean IDusesDaylight = + TimeZone::getTimeZone (elts[i])->useDaylightTime (); + if (usesDaylight && IDusesDaylight || !usesDaylight && !IDusesDaylight) + return elts[i]; + } + + // If all else fails, return null. + return NULL; +} |