Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.
   *
   * This code 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
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  *
  */
 
 package sun.jvm.hotspot.runtime;
 
 import java.io.*;
 import java.net.*;
 import java.util.*;
 import  sun.jvm.hotspot.runtime.*;

This class encapsulates the global state of the VM; the universe, object heap, interpreter, etc. It is a Singleton and must be initialized with a call to initialize() before calling getVM().

Many auxiliary classes (i.e., most of the VMObjects) keep needed field offsets in the form of static Field objects. In a debugging system, the VM might be shutdown and re-initialized (on a differently-configured build, i.e., 32- vs. 64-bit), and all old cached state (including fields and field offsets) must be flushed.

An Observer pattern is used to implement the initialization of such classes. Each such class, in its static initializer, registers an Observer with the VM class via VM.registerVMInitializedObserver(). This Observer is guaranteed to be notified whenever the VM is initialized (or re-initialized). To implement the first-time initialization, the observer is also notified when it registers itself with the VM. (For bootstrapping reasons, this implies that the constructor of VM can not instantiate any such objects, since VM.soleInstance will not have been set yet. This is a bootstrapping issue which may have to be revisited later.)

 
 
 public class VM {
   private static VM    soleInstance;
   private static List  vmInitializedObservers = new ArrayList();
   private List         vmResumedObservers   = new ArrayList();
   private List         vmSuspendedObservers = new ArrayList();
   private TypeDataBase db;
   private boolean      isBigEndian;
  
This is only present if in a debugging system
 
   private JVMDebugger  debugger;
   private long         stackBias;
   private long         logAddressSize;
   private Universe     universe;
   private ObjectHeap   heap;
   private SymbolTable  symbols;
   private StringTable  strings;
   private SystemDictionary dict;
   private Threads      threads;
   private JNIHandles   handles;
   private Interpreter  interpreter;
   private StubRoutines stubRoutines;
   private Bytes        bytes;
  
Flags indicating whether we are attached to a core, C1, or C2 build
 
   private boolean      usingClientCompiler;
   private boolean      usingServerCompiler;
  
Flag indicating whether UseTLAB is turned on
 
   private boolean      useTLAB;
  
alignment constants
 
   private boolean      isLP64;
   private int          bytesPerLong;
   private int          objectAlignmentInBytes;
   private int          minObjAlignmentInBytes;
   private int          logMinObjAlignmentInBytes;
   private int          heapWordSize;
  private int          heapOopSize;
  private int          oopSize;
  
This is only present in a non-core build
  private CodeCache    codeCache;
  
This is only present in a C1 build
  private Runtime1     runtime1;
  
These constants come from globalDefinitions.hpp
  private int          invocationEntryBCI;
  private int          invalidOSREntryBCI;
  private ReversePtrs  revPtrs;
  private VMRegImpl    vmregImpl;
  // System.getProperties from debuggee VM
  private Properties   sysProps;
  // VM version strings come from Abstract_VM_Version class
  private String       vmRelease;
  private String       vmInternalInfo;
  private Flag[] commandLineFlags;
  private Map flagsMap;
  private static Type intxType;
  private static Type uintxType;
  private static CIntegerType boolType;
  private Boolean sharingEnabled;
  // command line flags supplied to VM - see struct Flag in globals.hpp
  public static final class Flag {
     private String type;
     private String name;
     private Address addr;
     private String kind;
     private Flag(String typeString nameAddress addrString kind) {
        this. = type;
        this. = name;
        this. = addr;
        this. = kind;
     }
     public String getType() {
        return ;
     }
     public String getName() {
        return ;
     }
     public Address getAddress() {
        return ;
     }
     public String getKind() {
        return ;
     }
     public boolean isBool() {
        return .equals("bool");
     }
     public boolean getBool() {
        if (.) {
           Assert.that(isBool(), "not a bool flag!");
        }
        return .getCIntegerAt(0, .getSize(), .isUnsigned())
               != 0;
     }
     public boolean isIntx() {
        return .equals("intx");
     }
     public long getIntx() {
        if (.) {
           Assert.that(isIntx(), "not a intx flag!");
        }
        return .getCIntegerAt(0, .getSize(), false);
     }
     public boolean isUIntx() {
        return .equals("uintx");
     }
     public long getUIntx() {
        if (.) {
           Assert.that(isUIntx(), "not a uintx flag!");
        }
        return .getCIntegerAt(0, .getSize(), true);
     }
     public String getValue() {
        if (isBool()) {
           return new Boolean(getBool()).toString();
        } else if (isIntx()) {
           return new Long(getIntx()).toString();
        } else if (isUIntx()) {
           return new Long(getUIntx()).toString();
        } else {
           return null;
        }
     }
  };
  private static void checkVMVersion(String vmRelease) {
     if (System.getProperty("sun.jvm.hotspot.runtime.VM.disableVersionCheck") == null) {
        // read sa build version.
        String versionProp = "sun.jvm.hotspot.runtime.VM.saBuildVersion";
        String saVersion = .getProperty(versionProp);
        if (saVersion == null)
           throw new RuntimeException("Missing property " + versionProp);
        // Strip nonproduct VM version substring (note: saVersion doesn't have it).
        String vmVersion = vmRelease.replaceAll("(-fastdebug)|(-debug)|(-jvmg)|(-optimized)|(-profiled)","");
        if (saVersion.equals(vmVersion)) {
           // Exact match
           return;
        }
        if (saVersion.indexOf('-') == saVersion.lastIndexOf('-') &&
            vmVersion.indexOf('-') == vmVersion.lastIndexOf('-')) {
           // Throw exception if different release versions:
           // <major>.<minor>-b<n>
           throw new VMVersionMismatchException(saVersionvmRelease);
        } else {
           // Otherwise print warning to allow mismatch not release versions
           // during development.
           ..println("WARNING: Hotspot VM version " + vmRelease +
                              " does not match with SA version " + saVersion +
                              "." + " You may see unexpected results. ");
        }
     } else {
        ..println("WARNING: You have disabled SA and VM version check. You may be "  +
                           "using incompatible version of SA and you may see unexpected " +
                           "results.");
     }
  }
  private static final boolean disableDerivedPrinterTableCheck;
  private static final Properties saProps;
  static {
      = new Properties();
     URL url = null;
     try {
       url = VM.class.getClassLoader().getResource("sa.properties");
       .load(new BufferedInputStream(url.openStream()));
     } catch (Exception e) {
       throw new RuntimeException("Unable to load properties  " +
                                  (url == null ? "null" : url.toString()) +
                                  ": " + e.getMessage());
     }
      = System.getProperty("sun.jvm.hotspot.runtime.VM.disableDerivedPointerTableCheck") != null;
  }
  private VM(TypeDataBase dbJVMDebugger debuggerboolean isBigEndian) {
    this.          = db;
    this.    = debugger;
    this. = isBigEndian;
    // Note that we don't construct universe, heap, threads,
    // interpreter, or stubRoutines here (any more).  The current
    // initialization mechanisms require that the VM be completely set
    // up (i.e., out of its constructor, with soleInstance assigned)
    // before their static initializers are run.
    if (db.getAddressSize() == 4) {
       = 2;
    } else if (db.getAddressSize() == 8) {
       = 3;
    } else {
      throw new RuntimeException("Address size " + db.getAddressSize() + " not yet supported");
    }
    // read VM version info
    try {
       Type vmVersion = db.lookupType("Abstract_VM_Version");
       Address releaseAddr = vmVersion.getAddressField("_s_vm_release").getValue();
        = CStringUtilities.getString(releaseAddr);
       Address vmInternalInfoAddr = vmVersion.getAddressField("_s_internal_vm_info_string").getValue();
        = CStringUtilities.getString(vmInternalInfoAddr);
    } catch (Exception exp) {
       throw new RuntimeException("can't determine target's VM version : " + exp.getMessage());
    }
        = db.lookupIntConstant("STACK_BIAS").intValue();
     = db.lookupIntConstant("InvocationEntryBci").intValue();
     = db.lookupIntConstant("InvalidOSREntryBci").intValue();
    // We infer the presence of C1 or C2 from a couple of fields we
    // already have present in the type database
    {
      Type type = db.lookupType("methodOopDesc");
      if (type.getField("_from_compiled_entry"falsefalse) == null) {
        // Neither C1 nor C2 is present
         = false;
         = false;
      } else {
        // Determine whether C2 is present
        if (type.getField("_interpreter_invocation_count"falsefalse) != null) {
           = true;
        } else {
           = true;
        }
      }
    }
     = (db.lookupIntConstant("UseTLAB").intValue() != 0);
    if (debugger != null) {
       = debugger.getMachineDescription().isLP64();
    }
     = db.lookupIntConstant("BytesPerLong").intValue();
     = db.lookupIntConstant("HeapWordSize").intValue();
      = db.lookupIntConstant("oopSize").intValue();
     = db.lookupType("intx");
     = db.lookupType("uintx");
     = (CIntegerTypedb.lookupType("bool");
    if ( == 8) {
       = 3;
    } else if ( == 16) {
       = 4;
    } else {
      throw new RuntimeException("Object alignment " +  + " not yet supported");
    }
    if (isCompressedOopsEnabled()) {
      // Size info for oops within java objects is fixed
       = (int)getIntSize();
    } else {
       = (int)getOopSize();
    }
  }

  
This could be used by a reflective runtime system
  public static void initialize(TypeDataBase dbboolean isBigEndian) {
    if ( != null) {
      throw new RuntimeException("Attempt to initialize VM twice");
    }
     = new VM(dbnullisBigEndian);
    for (Iterator iter = .iterator(); iter.hasNext(); ) {
      ((Observeriter.next()).update(nullnull);
    }
  }

  
This is used by the debugging system
  public static void initialize(TypeDataBase dbJVMDebugger debugger) {
    if ( != null) {
      throw new RuntimeException("Attempt to initialize VM twice");
    }
     = new VM(dbdebuggerdebugger.getMachineDescription().isBigEndian());
    for (Iterator iter = .iterator(); iter.hasNext(); ) {
      ((Observeriter.next()).update(nullnull);
    }
                          Universe.getNarrowOopShift());
  }

  
This is used by the debugging system
  public static void shutdown() {
     = null;
  }

  
This is used by both the debugger and any runtime system. It is the basic mechanism by which classes which mimic underlying VM functionality cause themselves to be initialized. The given observer will be notified (with arguments (null, null)) when the VM is re-initialized, as well as when it registers itself with the VM.
  public static void registerVMInitializedObserver(Observer o) {
    o.update(nullnull);
  }

  
This is the primary accessor used by both the debugger and any potential runtime system
  public static VM getVM() {
    if ( == null) {
      throw new RuntimeException("VM.initialize() was not yet called");
    }
    return ;
  }

  
This is only used by the debugging system. The given observer will be notified if the underlying VM resumes execution. NOTE that the given observer is not triggered if the VM is currently running and therefore differs in behavior from registerVMInitializedObserver(java.util.Observer) (because of the possibility of race conditions if the observer is added while the VM is being suspended or resumed).
  public void registerVMResumedObserver(Observer o) {
  }

  
This is only used by the debugging system. The given observer will be notified if the underlying VM suspends execution. NOTE that the given observer is not triggered if the VM is currently suspended and therefore differs in behavior from registerVMInitializedObserver(java.util.Observer) (because of the possibility of race conditions if the observer is added while the VM is being suspended or resumed).
  public void registerVMSuspendedObserver(Observer o) {
  }

  
This is only used by the debugging system. Informs all registered resumption observers that the VM has been resumed. The application is responsible for actually having performed the resumption. No OopHandles must be used after this point, as they may move in the target address space due to garbage collection.
  public void fireVMResumed() {
    for (Iterator iter = .iterator(); iter.hasNext(); ) {
      ((Observeriter.next()).update(nullnull);
    }
  }

  
This is only used by the debugging system. Informs all registered suspension observers that the VM has been suspended. The application is responsible for actually having performed the suspension. Garbage collection must be forbidden at this point; for example, a JPDA-level suspension is not adequate since the VM thread may still be running.
  public void fireVMSuspended() {
    for (Iterator iter = .iterator(); iter.hasNext(); ) {
      ((Observeriter.next()).update(nullnull);
    }
  }

  
Returns the OS this VM is running on. Notice that by delegating to the debugger we can transparently support remote debugging.
  public String getOS() {
    if ( != null) {
      return .getOS();
    }
    return PlatformInfo.getOS();
  }

  
Returns the CPU this VM is running on. Notice that by delegating to the debugger we can transparently support remote debugging.
  public String getCPU() {
    if ( != null) {
      return .getCPU();
    }
    return PlatformInfo.getCPU();
  }
  public Type lookupType(String cTypeName) {
    return .lookupType(cTypeName);
  }
  public Integer lookupIntConstant(String name) {
    return .lookupIntConstant(name);
  }
  public long getAddressSize() {
    return .getAddressSize();
  }
  public long getOopSize() {
    return ;
  }
  public long getLogAddressSize() {
    return ;
  }
  public long getIntSize() {
    return .getJIntType().getSize();
  }

  
NOTE: this offset is in BYTES in this system!
  public long getStackBias() {
    return ;
  }

  
Indicates whether the underlying machine supports the LP64 data model. This is needed for conditionalizing code in a few places
  public boolean isLP64() {
    if (.) {
      Assert.that(isDebugging(), "Debugging system only for now");
    }
    return ;
  }

  
Get bytes-per-long == long/double natural alignment.
  public int getBytesPerLong() {
    return ;
  }

  
Get minimum object alignment in bytes.
  public int getMinObjAlignmentInBytes() {
    return ;
  }
  public int getLogMinObjAlignmentInBytes() {
  }
  public int getHeapWordSize() {
    return ;
  }
  public int getHeapOopSize() {
    return ;
  }
  
Utility routine for getting data structure alignment correct
  public long alignUp(long sizelong alignment) {
    return (size + alignment - 1) & ~(alignment - 1);
  }

  
Utility routine for getting data structure alignment correct
  public long alignDown(long sizelong alignment) {
    return size & ~(alignment - 1);
  }

  
Utility routine for building an int from two "unsigned" 16-bit shorts
  public int buildIntFromShorts(short lowshort high) {
    return (((inthigh) << 16) | (((intlow) & 0xFFFF);
  }

  
Utility routine for building a long from two "unsigned" 32-bit ints in platform-dependent order
  public long buildLongFromIntsPD(int oneHalfint otherHalf) {
    if () {
      return (((longotherHalf) << 32) | (((longoneHalf) & 0x00000000FFFFFFFFL);
    } else{
      return (((longoneHalf) << 32) | (((longotherHalf) & 0x00000000FFFFFFFFL);
    }
  }

  
Indicates whether Thread-Local Allocation Buffers are used
  public boolean getUseTLAB() {
    return ;
  }
    return ;
  }
  public Universe    getUniverse() {
    if ( == null) {
       = new Universe();
    }
    return ;
  }
  public ObjectHeap  getObjectHeap() {
    if ( == null) {
       = new ObjectHeap();
    }
    return ;
  }
  public SymbolTable getSymbolTable() {
    if ( == null) {
       = SymbolTable.getTheTable();
    }
    return ;
  }
  public StringTable getStringTable() {
    if ( == null) {
       = StringTable.getTheTable();
    }
    return ;
  }
    if ( == null) {
       = new SystemDictionary();
    }
    return ;
  }
  public Threads     getThreads() {
    if ( == null) {
       = new Threads();
    }
    return ;
  }
    if ( == null) {
       = new ObjectSynchronizer();
    }
    return ;
  }
  public JNIHandles getJNIHandles() {
    if ( == null) {
       = new JNIHandles();
    }
    return ;
  }
  public Interpreter getInterpreter() {
    if ( == null) {
       = new Interpreter();
    }
    return ;
  }
    if ( == null) {
       = new StubRoutines();
    }
    return ;
  }
  public VMRegImpl getVMRegImplInfo() {
    if ( == null) {
       = new VMRegImpl();
    }
    return ;
  }
  public Bytes getBytes() {
    if ( == null) {
       = new Bytes(.getMachineDescription());
    }
    return ;
  }

  
Returns true if this is a isBigEndian, false otherwise
  public boolean isBigEndian() {
    return ;
  }

  
Returns true if this is a "core" build, false if either C1 or C2 is present
  public boolean isCore() {
    return (!( || ));
  }

  
Returns true if this is a C1 build, false otherwise
  public boolean isClientCompiler() {
    return ;
  }

  
Returns true if this is a C2 build, false otherwise
  public boolean isServerCompiler() {
    return ;
  }

  
Returns true if C2 derived pointer table should be used, false otherwise
  public boolean useDerivedPointerTable() {
  }

  
Returns the code cache; should not be used if is core build
  public CodeCache getCodeCache() {
    if (.) {
      Assert.that(!isCore(), "noncore builds only");
    }
    if ( == null) {
       = new CodeCache();
    }
    return ;
  }

  
Should only be called for C1 builds
  public Runtime1 getRuntime1() {
    if (.) {
      Assert.that(isClientCompiler(), "C1 builds only");
    }
    if ( == null) {
       = new Runtime1();
    }
    return ;
  }

  
Test to see whether we're in debugging mode (NOTE: this really should not be tested by this code; currently only used in StackFrameStream)
  public boolean isDebugging() {
    return ( != null);
  }

  
This is only used by the debugging (i.e., non-runtime) system
  public JVMDebugger getDebugger() {
    if ( == null) {
      throw new RuntimeException("Attempt to use debugger in runtime system");
    }
    return ;
  }

  
Indicates whether a given program counter is in Java code. This includes but is not spanned by the interpreter and code cache. Only used in the debugging system, for implementing JavaThread.currentFrameGuess() on x86.
  public boolean isJavaPCDbg(Address addr) {
    // FIXME: this is not a complete enough set: must include areas
    // like vtable stubs
    return (getInterpreter().contains(addr) ||
            getCodeCache().contains(addr));
  }

  
FIXME: figure out where to stick this
  public int getInvocationEntryBCI() {
    return ;
  }

  
FIXME: figure out where to stick this
  public int getInvalidOSREntryBCI() {
    return ;
  }
  // FIXME: figure out where to stick this
  public boolean wizardMode() {
    return true;
  }
  public ReversePtrs getRevPtrs() {
    return ;
  }
  public void setRevPtrs(ReversePtrs rp) {
     = rp;
  }
  // returns null, if not available.
  public String getVMRelease() {
    return ;
  }
  // returns null, if not available.
  public String getVMInternalInfo() {
    return ;
  }
  public boolean isSharingEnabled() {
    if ( == null) {
      Flag flag = getCommandLineFlag("UseSharedSpaces");
       = (flag == null)? . :
          (flag.getBool()? ..);
    }
    return .booleanValue();
  }
  public boolean isCompressedOopsEnabled() {
    if ( == null) {
        Flag flag = getCommandLineFlag("UseCompressedOops");
         = (flag == null) ? .:
             (flag.getBool()? ..);
    }
  }
  public int getObjectAlignmentInBytes() {
    if ( == 0) {
        Flag flag = getCommandLineFlag("ObjectAlignmentInBytes");
         = (flag == null) ? 8 : (int)flag.getIntx();
    }
    return ;
  }
  // returns null, if not available.
  public Flag[] getCommandLineFlags() {
    if ( == null) {
       readCommandLineFlags();
    }
    return ;
  }
  public Flag getCommandLineFlag(String name) {
    if ( == null) {
       = new HashMap();
      Flag[] flags = getCommandLineFlags();
      for (int i = 0; i < flags.lengthi++) {
        .put(flags[i].getName(), flags[i]);
      }
    }
    return (Flag.get(name);
  }
  private void readCommandLineFlags() {
    // get command line flags
    TypeDataBase db = getTypeDataBase();
    try {
       Type flagType = db.lookupType("Flag");
       int numFlags = (intflagType.getCIntegerField("numFlags").getValue();
       // NOTE: last flag contains null values.
        = new Flag[numFlags - 1];
       Address flagAddr = flagType.getAddressField("flags").getValue();
       AddressField typeFld = flagType.getAddressField("type");
       AddressField nameFld = flagType.getAddressField("name");
       AddressField addrFld = flagType.getAddressField("addr");
       AddressField kindFld = flagType.getAddressField("kind");
       long flagSize = flagType.getSize(); // sizeof(Flag)
       // NOTE: last flag contains null values.
       for (int f = 0; f < numFlags - 1; f++) {
          String type = CStringUtilities.getString(typeFld.getValue(flagAddr));
          String name = CStringUtilities.getString(nameFld.getValue(flagAddr));
          Address addr = addrFld.getValue(flagAddr);
          String kind = CStringUtilities.getString(kindFld.getValue(flagAddr));
          [f] = new Flag(typenameaddrkind);
          flagAddr = flagAddr.addOffsetTo(flagSize);
       }
       // sort flags by name
       Arrays.sort(new Comparator() {
                                        public int compare(Object o1Object o2) {
                                           Flag f1 = (Flago1;
                                           Flag f2 = (Flago2;
                                           return f1.getName().compareTo(f2.getName());
                                        }
                                     });
    } catch (Exception exp) {
       // ignore. may be older version. command line flags not available.
    }
  }
  public String getSystemProperty(String key) {
    Properties props = getSystemProperties();
    return (props != null)? props.getProperty(key) : null;
  }
    if ( == null) {
       readSystemProperties();
    }
    return ;
  }
  private void readSystemProperties() {
    final InstanceKlass systemKls = getSystemDictionary().getSystemKlass();
    systemKls.iterateStaticFields(new DefaultOopVisitor() {
        ObjectReader objReader = new ObjectReader();
        public void doOop(sun.jvm.hotspot.oops.OopField fieldboolean isVMField) {
          if (field.getID().getName().equals("props")) {
            try {
               = (Properties.readObject(field.getValue(getObj()));
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      });
  }
New to GrepCode? Check out our FAQ X