提交 5a8f487c 编写于 作者: M mlapshin

Merge

37a05a11f281b4d238e2f9e7ebb67c63f64d0e77 jdk7-b24 37a05a11f281b4d238e2f9e7ebb67c63f64d0e77 jdk7-b24
75fca0b0ab83ab1392e615910cea020f66535390 jdk7-b25 75fca0b0ab83ab1392e615910cea020f66535390 jdk7-b25
fb57027902e04ecafceae31a605e69b436c23d57 jdk7-b26
...@@ -41,7 +41,7 @@ endif ...@@ -41,7 +41,7 @@ endif
# Omit mirror since it's built with the apt tool. # Omit mirror since it's built with the apt tool.
SUBDIRS = $(SCRIPT_SUBDIR) image security crypto/provider jndi jmx \ SUBDIRS = $(SCRIPT_SUBDIR) image security crypto/provider jndi jmx \
java inputmethods org xml rowset net/httpserver net/ssl demo \ java inputmethods org xml rowset net/httpserver net/ssl demo \
tools jarsigner tools jarsigner tracing
all build clean clobber:: all build clean clobber::
$(SUBDIRS-loop) $(SUBDIRS-loop)
......
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
#
#
# Makefile for building tracing classes
#
BUILDDIR = ../../..
PACKAGE = com.sun.tracing
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = dtrace
all build:
$(SUBDIRS-loop)
clean clobber::
$(SUBDIRS-loop)
AUTO_FILES_JAVA_DIRS = com/sun/tracing
#
# Rules.
#
include $(BUILDDIR)/common/Classes.gmk
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
#
#
# Makefile for building dtrace extension
#
BUILDDIR = ../../../..
PACKAGE = com.sun.tracing.dtrace
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
AUTO_FILES_JAVA_DIRS = com/sun/tracing/dtrace
#
# Rules.
#
include $(BUILDDIR)/common/Classes.gmk
...@@ -272,6 +272,28 @@ SMARTCARDIO_DOCTITLE = "Java$(TRADEMARK) Smart Card I/O" ...@@ -272,6 +272,28 @@ SMARTCARDIO_DOCTITLE = "Java$(TRADEMARK) Smart Card I/O"
SMARTCARDIO_JAVADOCHEADER = "Java Smart Card I/O" SMARTCARDIO_JAVADOCHEADER = "Java Smart Card I/O"
# SMARTCARDIO_PKGS is located in NON_CORE_PKGS.gmk # SMARTCARDIO_PKGS is located in NON_CORE_PKGS.gmk
#
# Variables used by TRACING target
#
TRACING_SOURCEPATH = $(TOPDIR)/src/share/classes
TRACING_DOCDIR = $(DOCSDIR)/jre/api/tracing
TRACING_JAVADOCFLAGS = $(COMMON_JAVADOCFLAGS) \
-encoding ascii \
-nodeprecatedlist \
-d $(TRACING_DOCDIR) \
-sourcepath $(TRACING_SOURCEPATH) \
-windowtitle $(TRACING_WINDOWTITLE) \
-doctitle $(TRACING_DOCTITLE) \
-header $(TRACING_JAVADOCHEADER) \
-linkoffline ../../../../../api $(DOCSDIR)/api/
TRACING_WINDOWTITLE = "Tracing"
TRACING_DOCTITLE = "Java$(TRADEMARK) Platform Tracing"
TRACING_JAVADOCHEADER = "Platform Tracing"
# TRACING_PKGS is located in NON_CORE_PKGS.gmk
# #
# Variables used by HTTPSERVER target # Variables used by HTTPSERVER target
# #
...@@ -420,6 +442,7 @@ ALL_OTHER_TARGETS = \ ...@@ -420,6 +442,7 @@ ALL_OTHER_TARGETS = \
jaasdocs \ jaasdocs \
jgssdocs \ jgssdocs \
smartcardiodocs \ smartcardiodocs \
tracingdocs \
httpserverdocs \ httpserverdocs \
mgmtdocs \ mgmtdocs \
attachdocs \ attachdocs \
...@@ -585,6 +608,14 @@ smartcardiodocs: ...@@ -585,6 +608,14 @@ smartcardiodocs:
$(JAVADOC_CMD) $(SMARTCARDIO_JAVADOCFLAGS) \ $(JAVADOC_CMD) $(SMARTCARDIO_JAVADOCFLAGS) \
$(SMARTCARDIO_PKGS) $(SMARTCARDIO_PKGS)
.PHONY: tracingdocs
tracingdocs:
@# ######## api-tracing ############################
$(RM) -r $(TRACING_DOCDIR)
$(MKDIR) -p $(TRACING_DOCDIR)
$(JAVADOC) $(TRACING_JAVADOCFLAGS) \
$(TRACING_PKGS)
.PHONY: httpserverdocs .PHONY: httpserverdocs
httpserverdocs: httpserverdocs:
@# ######## api-httpserver ####################### @# ######## api-httpserver #######################
......
...@@ -84,6 +84,9 @@ TREEAPI_PKGS = com.sun.source.tree \ ...@@ -84,6 +84,9 @@ TREEAPI_PKGS = com.sun.source.tree \
SMARTCARDIO_PKGS = javax.smartcardio SMARTCARDIO_PKGS = javax.smartcardio
TRACING_PKGS = com.sun.tracing \
com.sun.tracing.dtrace
# non-core packages in rt.jar # non-core packages in rt.jar
NON_CORE_PKGS = $(DOMAPI_PKGS) \ NON_CORE_PKGS = $(DOMAPI_PKGS) \
$(MGMT_PKGS) \ $(MGMT_PKGS) \
...@@ -91,4 +94,5 @@ NON_CORE_PKGS = $(DOMAPI_PKGS) \ ...@@ -91,4 +94,5 @@ NON_CORE_PKGS = $(DOMAPI_PKGS) \
$(JGSS_PKGS) \ $(JGSS_PKGS) \
$(OLD_JSSE_PKGS) \ $(OLD_JSSE_PKGS) \
$(HTTPSERVER_PKGS) \ $(HTTPSERVER_PKGS) \
$(SMARTCARDIO_PKGS) $(SMARTCARDIO_PKGS) \
$(TRACING_PKGS)
...@@ -33,6 +33,7 @@ FILES_java = \ ...@@ -33,6 +33,7 @@ FILES_java = \
sun/nio/cs/AbstractCharsetProvider.java \ sun/nio/cs/AbstractCharsetProvider.java \
sun/nio/cs/HistoricallyNamedCharset.java \ sun/nio/cs/HistoricallyNamedCharset.java \
sun/nio/cs/Surrogate.java \ sun/nio/cs/Surrogate.java \
sun/nio/cs/CharsetMapping.java \
sun/nio/cs/SingleByteEncoder.java \ sun/nio/cs/SingleByteEncoder.java \
sun/nio/cs/SingleByteDecoder.java \ sun/nio/cs/SingleByteDecoder.java \
sun/nio/cs/UnicodeEncoder.java \ sun/nio/cs/UnicodeEncoder.java \
......
...@@ -63,7 +63,7 @@ SUBDIRS = jar security javazic misc net audio $(RENDER_SUBDIR) image \ ...@@ -63,7 +63,7 @@ SUBDIRS = jar security javazic misc net audio $(RENDER_SUBDIR) image \
$(HEADLESS_SUBDIR) $(DGA_SUBDIR) \ $(HEADLESS_SUBDIR) $(DGA_SUBDIR) \
font jpeg cmm applet rmi beans $(JDBC_SUBDIR) \ font jpeg cmm applet rmi beans $(JDBC_SUBDIR) \
jawt text nio launcher management $(ORG_SUBDIR) \ jawt text nio launcher management $(ORG_SUBDIR) \
native2ascii serialver tools jconsole native2ascii serialver tools jconsole tracing
all build clean clobber:: all build clean clobber::
$(SUBDIRS-loop) $(SUBDIRS-loop)
......
# #
# Copyright 1996-2006 Sun Microsystems, Inc. All Rights Reserved. # Copyright 1996-2008 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -73,11 +73,21 @@ build: $(CHARSETS_JAR) ...@@ -73,11 +73,21 @@ build: $(CHARSETS_JAR)
SERVICE_DESCRIPTION = java.nio.charset.spi.CharsetProvider SERVICE_DESCRIPTION = java.nio.charset.spi.CharsetProvider
SERVICE_DESCRIPTION_PATH = META-INF/services/$(SERVICE_DESCRIPTION) SERVICE_DESCRIPTION_PATH = META-INF/services/$(SERVICE_DESCRIPTION)
GENCSDATASRC = $(BUILDDIR)/tools/CharsetMapping
FILES_MAP = $(GENCSDATASRC)/sjis0213.map
FILES_DAT = $(CLASSDESTDIR)/sun/nio/cs/ext/sjis0213.dat
CHARSETMAPPING_JARFILE = $(BUILDTOOLJARDIR)/charsetmapping.jar
$(FILES_DAT): $(FILES_MAP)
@$(prep-target)
$(BOOT_JAVA_CMD) -jar $(CHARSETMAPPING_JARFILE) \
$(FILES_MAP) $(FILES_DAT)
$(CLASSDESTDIR)/$(SERVICE_DESCRIPTION_PATH): \ $(CLASSDESTDIR)/$(SERVICE_DESCRIPTION_PATH): \
$(SHARE_SRC)/classes/sun/nio/cs/ext/$(SERVICE_DESCRIPTION_PATH) $(SHARE_SRC)/classes/sun/nio/cs/ext/$(SERVICE_DESCRIPTION_PATH)
$(install-file) $(install-file)
$(CHARSETS_JAR): $(FILES_class) $(CLASSDESTDIR)/$(SERVICE_DESCRIPTION_PATH) $(CHARSETS_JAR): $(FILES_class) $(CLASSDESTDIR)/$(SERVICE_DESCRIPTION_PATH) $(FILES_DAT)
$(BOOT_JAR_CMD) cf $(CHARSETS_JAR) \ $(BOOT_JAR_CMD) cf $(CHARSETS_JAR) \
-C $(CLASSDESTDIR) sun \ -C $(CLASSDESTDIR) sun \
-C $(CLASSDESTDIR) $(SERVICE_DESCRIPTION_PATH) \ -C $(CLASSDESTDIR) $(SERVICE_DESCRIPTION_PATH) \
......
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
#
#
# Makefile for building tracing package implementation classes
#
BUILDDIR = ../..
PACKAGE = sun.tracing
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
SUBDIRS = dtrace
all build:
$(SUBDIRS-loop)
clean clobber::
$(SUBDIRS-loop)
AUTO_FILES_JAVA_DIRS = sun/tracing
#
# Rules.
#
include $(BUILDDIR)/common/Classes.gmk
#
# Copyright 2007 Sun Microsystems, Inc. All rights reserved.
# SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
#
#
# Makefile for building dtrace extension
#
BUILDDIR = ../../..
PACKAGE = sun.tracing.dtrace
LIBRARY = jsdt
PRODUCT = sun
include $(BUILDDIR)/common/Defs.gmk
#
# Use mapfile
#
FILES_m = mapfile-vers
include $(BUILDDIR)/common/Mapfile-vers.gmk
NATIVE_DTRACE_DIR=native/sun/tracing/dtrace
SRCDIR=$(SHARE_SRC)/$(NATIVE_DTRACE_DIR)
PSRCDIR=$(PLATFORM_SRC)/$(NATIVE_DTRACE_DIR)
FILES_c = JVM.c jvm_symbols_md.c
FILES_java = \
sun/tracing/dtrace/Activation.java \
sun/tracing/dtrace/DTraceProvider.java \
sun/tracing/dtrace/DTraceProbe.java \
sun/tracing/dtrace/DTraceProviderFactory.java \
sun/tracing/dtrace/JVM.java
FILES_export = $(FILES_java)
ifeq ($(PLATFORM), linux)
OTHER_LDLIBS += -ldl
endif
#
# Use JNI for generating header files
#
JAVAHFLAGS += -jni
#
# Don't need to link against -ljava
#
JAVALIB=
#
# Rules.
#
include $(BUILDDIR)/common/Library.gmk
#
# Add to ambient vpath so we pick up the library files
#
vpath %.c $(SRCDIR):$(PSRCDIR)
#
#ident "@(#)mapfile-vers 1.1 07/08/14"
#
# Copyright 2006 Sun Microsystems, Inc. All rights reserved.
# SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
#
# Define library interface.
SUNWprivate_1.1 {
global:
Java_sun_tracing_dtrace_JVM_isSupported0;
Java_sun_tracing_dtrace_JVM_activate0;
Java_sun_tracing_dtrace_JVM_dispose0;
Java_sun_tracing_dtrace_JVM_isEnabled0;
Java_sun_tracing_dtrace_JVM_defineClass0;
local:
*;
};
#
# Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
# particular file as subject to the "Classpath" exception as provided
# by Sun in the LICENSE file that accompanied this code.
#
# 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# CA 95054 USA or visit www.sun.com if you need additional information or
# have any questions.
#
#
# Makefile for building the charsetmapping tool
#
BUILDDIR = ../..
PACKAGE = build.tools.charsetmapping
PRODUCT = tools
PROGRAM = charsetmapping
include $(BUILDDIR)/common/Defs.gmk
BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src
BUILDTOOL_MAIN = $(PKGDIR)/GenerateMapping.java
#
# Build tool jar rules.
#
include $(BUILDDIR)/common/BuildToolJar.gmk
因为 它太大了无法显示 source diff 。你可以改为 查看blob
...@@ -51,7 +51,8 @@ SUBDIRS = \ ...@@ -51,7 +51,8 @@ SUBDIRS = \
jdwpgen \ jdwpgen \
makeclasslist \ makeclasslist \
strip_properties \ strip_properties \
winver winver \
CharsetMapping
all build clean clobber:: all build clean clobber::
$(SUBDIRS-loop) $(SUBDIRS-loop)
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package build.tools.charsetmapping;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
public class CharsetMapping {
public final static char UNMAPPABLE_DECODING = '\uFFFD';
public final static int UNMAPPABLE_ENCODING = -1;
public static class Entry {
public int bs; //byte sequence reps
public int cp; //Unicode codepoint
public int cp2; //CC of composite
public Entry () {}
public Entry (int bytes, int cp, int cp2) {
this.bs = bytes;
this.cp = cp;
this.cp2 = cp2;
}
}
static Comparator<Entry> comparatorCP =
new Comparator<Entry>() {
public int compare(Entry m1, Entry m2) {
return m1.cp - m2.cp;
}
public boolean equals(Object obj) {
return this == obj;
}
};
public static class Parser {
static final Pattern basic = Pattern.compile("(?:0x)?(\\p{XDigit}++)\\s++(?:0x)?(\\p{XDigit}++)?\\s*+.*");
static final int gBS = 1;
static final int gCP = 2;
static final int gCP2 = 3;
BufferedReader reader;
boolean closed;
Matcher matcher;
int gbs, gcp, gcp2;
public Parser (InputStream in, Pattern p, int gbs, int gcp, int gcp2)
throws IOException
{
this.reader = new BufferedReader(new InputStreamReader(in));
this.closed = false;
this.matcher = p.matcher("");
this.gbs = gbs;
this.gcp = gcp;
this.gcp2 = gcp2;
}
public Parser (InputStream in, Pattern p) throws IOException {
this(in, p, gBS, gCP, gCP2);
}
public Parser (InputStream in) throws IOException {
this(in, basic, gBS, gCP, gCP2);
}
protected boolean isDirective(String line) {
return line.startsWith("#");
}
protected Entry parse(Matcher matcher, Entry mapping) {
mapping.bs = Integer.parseInt(matcher.group(gbs), 16);
mapping.cp = Integer.parseInt(matcher.group(gcp), 16);
if (gcp2 <= matcher.groupCount() &&
matcher.group(gcp2) != null)
mapping.cp2 = Integer.parseInt(matcher.group(gcp2), 16);
else
mapping.cp2 = 0;
return mapping;
}
public Entry next() throws Exception {
return next(new Entry());
}
// returns null and closes the input stream if the eof has beenreached.
public Entry next(Entry mapping) throws Exception {
if (closed)
return null;
String line;
while ((line = reader.readLine()) != null) {
if (isDirective(line))
continue;
matcher.reset(line);
if (!matcher.lookingAt()) {
//System.out.println("Missed: " + line);
continue;
}
return parse(matcher, mapping);
}
reader.close();
closed = true;
return null;
}
}
// tags of different charset mapping tables
private final static int MAP_SINGLEBYTE = 0x1; // 0..256 : c
private final static int MAP_DOUBLEBYTE1 = 0x2; // min..max: c
private final static int MAP_DOUBLEBYTE2 = 0x3; // min..max: c [DB2]
private final static int MAP_SUPPLEMENT = 0x5; // db,c
private final static int MAP_SUPPLEMENT_C2B = 0x6; // c,db
private final static int MAP_COMPOSITE = 0x7; // db,base,cc
private final static int MAP_INDEXC2B = 0x8; // index table of c->bb
private static final void writeShort(OutputStream out, int data)
throws IOException
{
out.write((data >>> 8) & 0xFF);
out.write((data ) & 0xFF);
}
private static final void writeShortArray(OutputStream out,
int type,
int[] array,
int off,
int size) // exclusive
throws IOException
{
writeShort(out, type);
writeShort(out, size);
for (int i = off; i < size; i++) {
writeShort(out, array[off+i]);
}
}
public static final void writeSIZE(OutputStream out, int data)
throws IOException
{
out.write((data >>> 24) & 0xFF);
out.write((data >>> 16) & 0xFF);
out.write((data >>> 8) & 0xFF);
out.write((data ) & 0xFF);
}
public static void writeINDEXC2B(OutputStream out, int[] indexC2B)
throws IOException
{
writeShort(out, MAP_INDEXC2B);
writeShort(out, indexC2B.length);
int off = 0;
for (int i = 0; i < indexC2B.length; i++) {
if (indexC2B[i] != 0) {
writeShort(out, off);
off += 256;
} else {
writeShort(out, -1);
}
}
}
public static void writeSINGLEBYTE(OutputStream out, int[] sb)
throws IOException
{
writeShortArray(out, MAP_SINGLEBYTE, sb, 0, 256);
}
private static void writeDOUBLEBYTE(OutputStream out,
int type,
int[] db,
int b1Min, int b1Max,
int b2Min, int b2Max)
throws IOException
{
writeShort(out, type);
writeShort(out, b1Min);
writeShort(out, b1Max);
writeShort(out, b2Min);
writeShort(out, b2Max);
writeShort(out, (b1Max - b1Min + 1) * (b2Max - b2Min + 1));
for (int b1 = b1Min; b1 <= b1Max; b1++) {
for (int b2 = b2Min; b2 <= b2Max; b2++) {
writeShort(out, db[b1 * 256 + b2]);
}
}
}
public static void writeDOUBLEBYTE1(OutputStream out,
int[] db,
int b1Min, int b1Max,
int b2Min, int b2Max)
throws IOException
{
writeDOUBLEBYTE(out, MAP_DOUBLEBYTE1, db, b1Min, b1Max, b2Min, b2Max);
}
public static void writeDOUBLEBYTE2(OutputStream out,
int[] db,
int b1Min, int b1Max,
int b2Min, int b2Max)
throws IOException
{
writeDOUBLEBYTE(out, MAP_DOUBLEBYTE2, db, b1Min, b1Max, b2Min, b2Max);
}
// the c2b table is output as well
public static void writeSUPPLEMENT(OutputStream out, Entry[] supp, int size)
throws IOException
{
writeShort(out, MAP_SUPPLEMENT);
writeShort(out, size * 2);
// db at first half, cc at the low half
for (int i = 0; i < size; i++) {
writeShort(out, supp[i].bs);
}
for (int i = 0; i < size; i++) {
writeShort(out, supp[i].cp);
}
//c2b
writeShort(out, MAP_SUPPLEMENT_C2B);
writeShort(out, size*2);
Arrays.sort(supp, 0, size, comparatorCP);
for (int i = 0; i < size; i++) {
writeShort(out, supp[i].cp);
}
for (int i = 0; i < size; i++) {
writeShort(out, supp[i].bs);
}
}
public static void writeCOMPOSITE(OutputStream out, Entry[] comp, int size)
throws IOException
{
writeShort(out, MAP_COMPOSITE);
writeShort(out, size*3);
// comp is sorted already
for (int i = 0; i < size; i++) {
writeShort(out, (char)comp[i].bs);
writeShort(out, (char)comp[i].cp);
writeShort(out, (char)comp[i].cp2);
}
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package build.tools.charsetmapping;
import java.io.*;
import java.util.regex.*;
import static build.tools.charsetmapping.CharsetMapping.*;
public class GenerateMapping {
public static void main(String argv[]) throws IOException {
if (argv.length < 2) {
System.out.println("Usage: java GenCSData fMap fDat");
System.exit(1);
}
genDataJIS0213(new FileInputStream(argv[0]),
new FileOutputStream(argv[1]));
}
// regex pattern to parse the "jis0213.map" file
static Pattern sjis0213 = Pattern.compile("0x(\\p{XDigit}++)\\s++U\\+(\\p{XDigit}++)(?:\\+(\\p{XDigit}++))?\\s++#.*");
private static void genDataJIS0213(InputStream in, OutputStream out)
{
int[] sb = new int[0x100]; // singlebyte
int[] db = new int[0x10000]; // doublebyte
int[] indexC2B = new int[256];
Entry[] supp = new Entry[0x10000];
Entry[] comp = new Entry[0x100];
int suppTotal = 0;
int compTotal = 0;
int b1Min1 = 0x81;
int b1Max1 = 0x9f;
int b1Min2 = 0xe0;
int b1Max2 = 0xfc;
int b2Min = 0x40;
int b2Max = 0xfe;
//init
for (int i = 0; i < 0x80; i++) sb[i] = i;
for (int i = 0x80; i < 0x100; i++) sb[i] = UNMAPPABLE_DECODING;
for (int i = 0; i < 0x10000; i++) db[i] = UNMAPPABLE_DECODING;
try {
Parser p = new Parser(in, sjis0213);
Entry e = null;
while ((e = p.next()) != null) {
if (e.cp2 != 0) {
comp[compTotal++] = e;
} else {
if (e.cp <= 0xffff) {
if (e.bs <= 0xff)
sb[e.bs] = e.cp;
else
db[e.bs] = e.cp;
indexC2B[e.cp>>8] = 1;
} else {
supp[suppTotal++] = e;
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// c2b Index Table, always the first one
writeINDEXC2B(baos, indexC2B);
writeSINGLEBYTE(baos, sb);
writeDOUBLEBYTE1(baos, db, b1Min1, b1Max1, b2Min, b2Max);
writeDOUBLEBYTE2(baos, db, b1Min2, b1Max2, b2Min, b2Max);
writeSUPPLEMENT(baos, supp, suppTotal);
writeCOMPOSITE(baos, comp, compTotal);
writeSIZE(out, baos.size());
baos.writeTo(out);
out.close();
} catch (Exception x) {
x.printStackTrace();
}
}
}
/* /*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -50,7 +50,7 @@ ...@@ -50,7 +50,7 @@
#define JAR_ERROR2 "Error: Unable to access jarfile %s" #define JAR_ERROR2 "Error: Unable to access jarfile %s"
#define JAR_ERROR3 "Error: Invalid or corrupt jarfile %s" #define JAR_ERROR3 "Error: Invalid or corrupt jarfile %s"
#define CLS_ERROR1 "Error: Could not find the main class.\n" JNI_ERROR #define CLS_ERROR1 "Error: Could not find the main class %s.\n" JNI_ERROR
#define CLS_ERROR2 "Error: Failed to load Main Class: %s\n%s" #define CLS_ERROR2 "Error: Failed to load Main Class: %s\n%s"
#define CLS_ERROR3 "Error: No main method found in specified class.\n" GEN_ERROR #define CLS_ERROR3 "Error: No main method found in specified class.\n" GEN_ERROR
#define CLS_ERROR4 "Error: Main method not public\n" GEN_ERROR #define CLS_ERROR4 "Error: Main method not public\n" GEN_ERROR
......
/* /*
* Copyright 1995-2007 Sun Microsystems, Inc. All Rights Reserved. * Copyright 1995-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -414,7 +414,7 @@ JavaMain(void * _args) ...@@ -414,7 +414,7 @@ JavaMain(void * _args)
mainClass = LoadClass(env, classname); mainClass = LoadClass(env, classname);
if(mainClass == NULL) { /* exception occured */ if(mainClass == NULL) { /* exception occured */
ReportExceptionDescription(env); ReportExceptionDescription(env);
ReportErrorMessage(CLS_ERROR1); ReportErrorMessage(CLS_ERROR1, classname);
goto leave; goto leave;
} }
(*env)->ReleaseStringUTFChars(env, mainClassName, classname); (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
...@@ -433,7 +433,7 @@ JavaMain(void * _args) ...@@ -433,7 +433,7 @@ JavaMain(void * _args)
mainClass = LoadClass(env, classname); mainClass = LoadClass(env, classname);
if(mainClass == NULL) { /* exception occured */ if(mainClass == NULL) { /* exception occured */
ReportExceptionDescription(env); ReportExceptionDescription(env);
ReportErrorMessage(CLS_ERROR1); ReportErrorMessage(CLS_ERROR1, classname);
goto leave; goto leave;
} }
(*env)->ReleaseStringUTFChars(env, mainClassName, classname); (*env)->ReleaseStringUTFChars(env, mainClassName, classname);
......
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
package com.sun.management; package com.sun.management;
import java.lang.management.PlatformManagedObject;
/** /**
* Diagnostic management interface for the HotSpot Virtual Machine. * Diagnostic management interface for the HotSpot Virtual Machine.
* The diagnostic MBean is registered to the platform MBeanServer * The diagnostic MBean is registered to the platform MBeanServer
...@@ -35,8 +37,13 @@ package com.sun.management; ...@@ -35,8 +37,13 @@ package com.sun.management;
* <blockquote> * <blockquote>
* <tt>com.sun.management:type=HotSpotDiagnostic</tt> * <tt>com.sun.management:type=HotSpotDiagnostic</tt>
* </blockquote> * </blockquote>
.*
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
*/ */
public interface HotSpotDiagnosticMXBean { public interface HotSpotDiagnosticMXBean extends PlatformManagedObject {
/** /**
* Dumps the heap to the <tt>outputFile</tt> file in the same * Dumps the heap to the <tt>outputFile</tt> file in the same
* format as the hprof heap dump. * format as the hprof heap dump.
......
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing;
/**
* The {@code Probe} interface represents a tracepoint.
*
* A {@code Probe} instance is obtained by calling the
* {@code Provider.getProbe()} method of a provider instance created by
* {@code ProviderFactory.createProvider()}. A {@code Probe} can be used to
* trigger a probe manually (provided the correct arguments are passed to
* it), or to check a probe to see if anything is currently tracing it.
* <p>
* A tracing check can be used to avoid lengthy work that might be
* needed to set up the probe's arguments. However, checking
* whether the probe is enabled generally takes the same amount of time
* as actually triggering the probe. So, you should only check a probe's status
* without triggering it if setting up the arguments is very expensive.
* <p>
* Users do not need to implement this interface: instances are
* created automatically by the system when a {@code Provider)} instance is
* created.
* <p>
* @since 1.7
*/
public interface Probe {
/**
* Checks whether there is an active trace of this probe.
*
* @return true if an active trace is detected.
*/
boolean isEnabled();
/**
* Determines whether a tracepoint is enabled.
*
* Typically, users do not need to use this method. It is called
* automatically when a Provider's instance method is called. Calls to
* this method expect the arguments to match the declared parameters for
* the method associated with the probe.
*
* @param args the parameters to pass to the method.
* @throws IllegalArgumentException if the provided parameters do not
* match the method declaration for this probe.
*/
void trigger(Object ... args);
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* An annotation used to override the name of a probe.
* <p>
* This annotation can be added to a method in a user-defined {@code Provider}
* interface, to set the name that will be used for the generated probe
* associated with that method. Without this annotation, the name will be the
* name of the method.
* <p>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProbeName {
String value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing;
/**
* {@code Provider} is a superinterface for user-defined tracing providers.
* <p>
* To define tracepoints, users must extend this interface
* and then use a {@code ProviderFactory} to create an instance of the
* newly-defined interface. Each method in the defined interface represents a
* tracepoint (or probe), which can be triggered by calling the associated
* method on the returned instance.
* <p>
* This interface also contains a {@code getProbe()} method, which can be
* used to get direct handles to the {@code Probe} objects themselves.
* {@code Probe} objects can be triggered manually, or they can be queried to
* check their state.
* <p>
* When an application has finished triggering probes, it should call
* {@code dispose()} to free up any system resources associated with the
* Provider.
* <p>
* All methods declared in a subclass of this interface should have a
* {@code void} return type. Methods can have parameters, and when called the
* values of the arguments will be passed to the tracing implementation.
* If any methods do not have a {@code void} return type, an
* {@code java.lang.IllegalArgumentException} will be thrown when the
* provider is registered.
* @since 1.7
*/
public interface Provider {
/**
* Retrieves a reference to a Probe object, which is used to check status
* or to trigger the probe manually.
*
* If the provided method parameter is not a method of the provider
* interface, or if the provider interface has been disposed, then
* this returns null
*
* @param method a method declared in the provider.
* @return the specified probe represented by that method, or null.
*/
Probe getProbe(java.lang.reflect.Method method);
/**
* Disposes system resources associated with this provider.
*
* After calling this method, triggering the probes will have no effect.
* Additional calls to this method after the first call are ignored.
*/
void dispose();
}
package com.sun.tracing;
import java.util.HashSet;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.logging.Logger;
import sun.tracing.NullProviderFactory;
import sun.tracing.PrintStreamProviderFactory;
import sun.tracing.MultiplexProviderFactory;
import sun.tracing.dtrace.DTraceProviderFactory;
/**
* {@code ProviderFactory} is a factory class used to create instances of
* providers.
*
* To enable tracing in an application, this class must be used to create
* instances of the provider interfaces defined by users.
* The system-defined factory is obtained by using the
* {@code getDefaultFactory()} static method. The resulting instance can be
* used to create any number of providers.
*
* @since 1.7
*/
public abstract class ProviderFactory {
protected ProviderFactory() {}
/**
* Creates an implementation of a Provider interface.
*
* @param cls the provider interface to be defined.
* @return an implementation of {@code cls}, whose methods, when called,
* will trigger tracepoints in the application.
* @throws NullPointerException if cls is null
* @throws IllegalArgumentException if the class definition contains
* non-void methods
*/
public abstract <T extends Provider> T createProvider(Class<T> cls);
/**
* Returns an implementation of a {@code ProviderFactory} which
* creates instances of Providers.
*
* The created Provider instances will be linked to all appropriate
* and enabled system-defined tracing mechanisms in the JDK.
*
* @return a {@code ProviderFactory} that is used to create Providers.
*/
public static ProviderFactory getDefaultFactory() {
HashSet<ProviderFactory> factories = new HashSet<ProviderFactory>();
// Try to instantiate a DTraceProviderFactory
String prop = null;
try { prop = System.getProperty("com.sun.tracing.dtrace"); }
catch (java.security.AccessControlException e) {
Logger.getAnonymousLogger().fine(
"Cannot access property com.sun.tracing.dtrace");
}
if ( (prop == null || !prop.equals("disable")) &&
DTraceProviderFactory.isSupported() ) {
factories.add(new DTraceProviderFactory());
}
// Try to instantiate an output stream factory
try { prop = System.getProperty("sun.tracing.stream"); }
catch (java.security.AccessControlException e) {
Logger.getAnonymousLogger().fine(
"Cannot access property sun.tracing.stream");
}
if (prop != null) {
for (String spec : prop.split(",")) {
PrintStream ps = getPrintStreamFromSpec(spec);
if (ps != null) {
factories.add(new PrintStreamProviderFactory(ps));
}
}
}
// See how many factories we instantiated, and return an appropriate
// factory that encapsulates that.
if (factories.size() == 0) {
return new NullProviderFactory();
} else if (factories.size() == 1) {
return factories.toArray(new ProviderFactory[1])[0];
} else {
return new MultiplexProviderFactory(factories);
}
}
private static PrintStream getPrintStreamFromSpec(String spec) {
try {
// spec is in the form of <class>.<field>, where <class> is
// a fully specified class name, and <field> is a static member
// in that class. The <field> must be a 'PrintStream' or subtype
// in order to be used.
int fieldpos = spec.lastIndexOf('.');
Class<?> cls = Class.forName(spec.substring(0, fieldpos));
Field f = cls.getField(spec.substring(fieldpos + 1));
Class<?> fieldType = f.getType();
return (PrintStream)f.get(null);
} catch (Exception e) {
Logger.getAnonymousLogger().warning(
"Could not parse sun.tracing.stream property: " + e);
}
return null;
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* An annotation used to specify the name of a provider.
* <p>
* This annotation can be added to a user-defined {@code Provider}
* interface, to set the name that will be used
* for the provider in the generated probes. Without this annotation,
* the simple class name of the provider interface is used.
* <p>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ProviderName {
String value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation describes the interface attributes of the probe arguments in
* a single provider.
*
* This annotation can be added to a user-defined {@code Provider} specification
* interface to set the stability attributes of the probe arguments, for
* all the probes specified in that provider.
* <p>
* If this annotation is not present, the interface attributes for the
* arguments are Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface ArgsAttributes {
Attributes value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation describes the interface's field attributes
* for the probes in a provider.
*
* This annotation provides the contents of field-specific annotations
* that specify the stability attributes and dependency class of a
* particular field, for the probes in a provider.
* <p>
* The default interface attributes for unspecified fields is
* Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Attributes {
/**
* The stability level of the name.
*/
StabilityLevel name() default StabilityLevel.PRIVATE;
/**
* The stability level of the data.
*/
StabilityLevel data() default StabilityLevel.PRIVATE;
/**
* The interface attribute's dependency class.
*/
DependencyClass dependency() default DependencyClass.UNKNOWN;
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
/**
* Enumeration for the DTrace dependency classes.
*
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide for details, Chapter 39: Stability</a>
* @since 1.7
*/
public enum DependencyClass {
/**
* The interface has an unknown set of architectural dependencies.
*/
UNKNOWN (0),
/**
* The interface is specific to the CPU model of the current system.
*/
CPU (1),
/**
* The interface is specific to the hardware platform of the current
* system.
*/
PLATFORM (2),
/**
* The interface is specific to the hardware platform group of the
* current system.
*/
GROUP (3),
/**
* The interface is specific to the instruction set architecture (ISA)
* supported by the microprocessors on this system.
*/
ISA (4),
/**
* The interface is common to all Solaris systems regardless of the
* underlying hardware.
*/
COMMON (5);
public String toDisplayString() {
return toString().substring(0,1) +
toString().substring(1).toLowerCase();
}
public int getEncoding() { return encoding; }
private int encoding;
private DependencyClass(int encoding) {
this.encoding = encoding;
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation describes the interface attributes of the
* {@code function} field for a single provider.
*
* This annotation can be added to a user-defined {@code Provider} specification
* interface to set the stability attributes of the {@code function} field for
* all probes specified in that provider.
* <p>
* If this annotation is not present, the interface attributes for the
* {@code function} field are Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface FunctionAttributes {
Attributes value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* An annotation used to specify the {@code function} field for a DTrace probe.
*
* This annotation can be added to a method in a user-defined Provider
* specification interface to set the {@code function} field that is used
* for the generated DTrace probe associated with that method.
* <p>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FunctionName {
String value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation is used to describe the interface attributes of the
* {@code module} field for a single provider.
*
* This annotation can be added to a user-defined Provider specification
* interface to set the stability attributes of the {@code module} field for
* all probes specified in that provider.
* <p>
* If this annotation is not present, the interface attributes for the
* {@code module} field is Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface ModuleAttributes {
Attributes value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* An annotation used to specify the {@code module} field for a DTrace probe.
*
* This annotation can be added to a method in a user-defined Provider
* specification interface to set the {@code module} field that will be used
* for the generated DTrace probe associated with that method.
* <p>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ModuleName {
String value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation describes the interface attributes of the
* {@code name} field for a single provider.
*
* This annotation can be added to a user-defined Provider specification
* interface to set the stability attributes of the {@code name} field for
* all probes specified in that provider.
* <p>
* If this annotation is not present, the interface attributes for the
* {@code name} field will be Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface NameAttributes {
Attributes value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* This annotation is used to describe the interface attributes of the
* {@code provider} field for a single provider.
*
* This annotation can be added to a user-defined Provider specification
* interface to set the stability attributes of the {@code provider} field for
* all probes specified in that provider.
* <p>
* If this annotation is not present, the interface attributes for the
* {@code provider} field will be Private/Private/Unknown.
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE })
public @interface ProviderAttributes {
Attributes value();
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.tracing.dtrace;
/**
* Enumeration for the DTrace stability levels.
*
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
* @since 1.7
*/
public enum StabilityLevel {
/**
* The interface is private to DTrace and represents an implementation
* detail of DTrace.
*/
INTERNAL (0),
/**
* The interface is private to Sun for use by other Sun products. It is
* not yet publicly documented for use by customers and ISVs.
*/
PRIVATE (1),
/**
* The interface is supported in the current release but is scheduled
* to be removed, most likely in a future minor release.
*/
OBSOLETE (2),
/**
* The interface is controlled by an entity other than Sun.
*/
EXTERNAL (3),
/**
* The interface gives developers early access to new or
* rapidly changing technology or to an implementation artifact that is
* essential for observing or debugging system behavior. A more
* stable solution is anticipated in the future.
*/
UNSTABLE (4),
/**
* The interface might eventually become Standard or Stable but is
* still in transition.
*/
EVOLVING (5),
/**
* The interface is a mature interface under Sun's control.
*/
STABLE (6),
/**
* The interface complies with an industry standard.
*/
STANDARD (7);
String toDisplayString() {
return toString().substring(0,1) +
toString().substring(1).toLowerCase();
}
public int getEncoding() { return encoding; }
private int encoding;
private StabilityLevel(int encoding) {
this.encoding = encoding;
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* This package contains annotations and enumerations that are used to
* add DTrace-specific information to a tracing provider.
* <p>
* The DTrace-specific annotations modify the attributes of a DTrace provider
* implementation when it is used by the tracing subsystem. The annotations are
* added to a {@code com.sun.tracing} provider specification to control
* specific attributes of the provider as it relates to DTrace.
* <p>
* Any other tracing subsystems supported by the system will ignore these
* annotations.
* <p>
* DTrace probes have additional fields and stability attributes that are
* not accounted for in the generic tracing package. If unspecified, the
* default values are used for the stability and dependency attributes of
* probes, as well as for the module and field names of the generated probes.
* The values can be specified by adding the appropriate annotations to the
* provider specification.
* <p>
* The {@code FunctionName} annotation is used to annotate the tracepoint
* methods defined in the provider specification. The value of this annotation
* is used as the {@code function} field in the generated DTrace probes. It
* is typically set to the name of the enclosing function where the
* tracepoint is triggered.
* <p>
* The {@code ModuleName} annotation is used to annotate the provider
* specification itself and applies to all the probes in the provider. It
* sets the value of the {@code module} field in the generated DTrace probes.
* <p>
* The remaining annotations, are also applied to the provider itself, and
* are used to set the stability and dependency attributes of all probes in
* that provider. Each probe field and the probe arguments can be
* independently assigned interface attributes to control the stability
* ratings of the probes.
* <p>
* Here is an example of how to declare a provider, specifying additional DTrace
* data:
<PRE>
&#064;ProviderName("my_app_provider")
&#064;ModuleName("app.jar")
&#064;ProviderAttributes(&#064;Attributes={
name=StabilityLevel.STABLE,data=StabilityLevel.STABLE,
dependency=DependencyClass.COMMON})
&#064;ProbeAttributes(&#064;Attributes={
name=StabilityLevel.STABLE,data=StabilityLevel.STABLE,
dependency=DependencyClass.COMMON})
&#064;ModuleAttributes(&#064;Attributes={name=StabilityLevel.UNSTABLE})
public class MyProvider {
&#064;FunctionName("main") void startProbe();
}
</PRE>
* <p>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlms?a=view">Solaris Dynamic Tracing Guide, Chapter 34: Statically Defined Tracing for User Applications</a>
* @see <a href="http://docs.sun.com/app/docs/doc/817-6223/6mlkidlnp?a=view">Solaris Dynamic Tracing Guide, Chapter 39: Stability</a>
*/
package com.sun.tracing.dtrace;
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* This package provides a mechanism for defining and
* inserting tracepoints into Java-technology based applications, which
* can then be monitored by the tracing tools available on the system.
* <p>
* To add tracepoints to a program, you must first decide where to place the
* tracepoints, what the logical names are for these points, what information
* will be available to the tracing mechanisms at each point, and decide upon
* any logical grouping.
* <p>
* You add instrumentation to a program in three steps:
* <ul>
* <li>First, declare tracepoints by creating interfaces to define
* them, and include these interfaces in the program definition.
* The declared interfaces are standard Java technology-based
* interfaces and are compiled with the program.</li>
* <li>Second, add code in the application to create an instance of the
* interface at some point during the initialization of the application,
* using a factory class provided by the system. The reference to the
* instance can be stored as a global static, or passed as context to all
* the places where it is needed.</li>
* <li>Finally, add the actual tracepoints to the desired locations in the
* application by inserting a call to one of the methods defined in the
* interface, via the factory-created reference.</li>
* </ul>
* <p>
* The method calls representing the tracepoints have no logical
* impact on the program. The side effect of the call is that any
* activated tracing mechanisms will be notified that the tracepoint has
* been hit, and will take whatever actions are appropriate (for example,
* logging the tracepoint, or triggering a DTrace probe, etc.). In most
* cases, the impact on performance of adding tracepoints to the application
* will be minimal.
* <p>
* Each logical grouping of tracepoints should be defined in a common
* interface, called a <i>provider</i>. An application can have one or many
* providers. Each provider is independent and can be created whenever
* it is appropriate for that provider, for example, when a subsytem is
* initialized. Providers should be disposed of when they are no longer
* needed, to free up any associated system resources. Each tracepoint
* in a provider is represented by a method in that interface. These methods
* are referred to as <i>probes</i>. The method signature determines the probe
* parameters. A call to the method with the specified parameters triggers
* the probe and makes its parameter values visible to any associated tracing
* mechanism.
* <p>
* User-defined interfaces which represent providers must extend the
* {@code Provider} interface. To activate the system-defined
* tracing mechanisms, you must obtain an instance of the
* {@code ProviderFactory} class, and pass the class of the provider to
* the {@code createProvider()} method. The returned instance is then used to
* trigger the probes later in the application.
* <p>
* In addition to triggering the probes, the provider instance can be used
* to obtain direct references to the {@code Probe} objects, which can be used
* directly for triggering, or can be queried to determine whether the probe is
* currently being traced. The {@code Provider} interface also defines a
* {@code Provider.dispose()} method which is used to free up any resources
* that might be associated with that provider.
* <p>
* When a probe is triggered, any activated tracing system will be given
* the provider name, the probe name, and the values of the probe arguments.
* The tracing system is free to consume this data is whatever way is
* appropriate.
* By default, the provider name is the same as the class name of the interface
* that defines the provider. Similarly, the probe name is
* the name of the method that defines the probe. These default values
* can be over-ridden by annotations. The provider definition can be
* annotated with the {@code @ProviderName} annotation, whose value will
* indicate the provider name that the tracing system will use. Similarly,
* the {@code @ProbeName} annotation annotates a declared method and
* indicates the probe name that should be used in the place of the
* method name. These annotations can be used to define providers and
* probes with the same name, in cases where the semantics of the Java language
* may prevent this.
* <p>
* Here is a very small and simple usage example:
* <p>
*
<PRE>
import com.sun.tracing.Provider;
import com.sun.tracing.ProviderFactory;
interface MyProvider extends Provider {
void startProbe();
void finishProbe(int value);
}
public class MyApplication {
public static void main(String argv[]) {
ProviderFactory factory = ProviderFactory.getDefaultFactory();
MyProvider trace = factory.createProvider(MyProvider.class);
trace.startProbe();
int result = foo();
trace.finishProbe(result);
trace.dispose();
}
}
</PRE>
* <p>
* The Java Development Kit (JDK) currently only includes one system-defined
* tracing framework: DTrace. DTrace is enabled automatically whenever an
* application is run on a system and a JDK release that supports it. When
* DTrace is enabled, probes are made available for listing and matching by
* DTrace scripts as soon as the provider is created. At the tracepoint, an
* associated DTrace script is informed of the creation of the provider, and
* it takes whatever action it is designed to take. Tracepoints in the
* program have the following DTrace probe names:<br>
* {@code <provider><pid>:<module>:<function>:<probe>}
* Where:
* <ul>
* <li>{@code <provider>} the provider name as specified by the application</li>
* <li>{@code <pid>} the operating system process ID</li>
* <li>{@code <module>} undefined, unless specified by the application</li>
* <li>{@code <function>} undefined, unless specified by the application</li>
* <li>{@code <probe>} the probe name as specified by the application</li>
* </ul>
* <p>
* The {@code com.sun.tracing.dtrace} package contains additional
* annotations that can be used to control the names used for the
* <code>module</code> and <code>function</code> fields, as well as annotations
* that can be added to the provider to control probe stability and dependency
* attributes.
* <p>
* Integer, float and string probe parameters are made available to DTrace
* using
* the built-in argument variables, {@code arg0 ... arg_n}. Integer-types
* are passed by value (boxed values are unboxed), floating-point types are
* passed as encoded integer
* arguments, and {@code java.lang.String} objects are converted
* to UTF8 strings, so they can be read into the DTrace script using the
* {@code copyinstr()} intrinsic. Non-string and non-boxed primitive
* reference arguments are only
* placeholders and have no value.
* <p>
* Using the example above, with a theoretical process ID of 123, these are
* the probes that can be traced from DTrace:
<PRE>
MyProvider123:::startProbe
MyProvider123:::finishProbe
</PRE>
* When {@code finishProbe} executes, {@code arg0} will contain the
* value of {@code result}.
* <p>
* The DTrace tracing mechanism is enabled for all providers, apart from in the
* following circumstances:
* <ul>
* <li>DTrace is not supported on the underlying system.</li>
* <li>The property {@code com.sun.tracing.dtrace} is set to "disable".</li>
* <li>The RuntimePermission {@code com.sun.tracing.dtrace.createProvider}
* is denied to the process.</li>
* </ul>
* <p>
*/
package com.sun.tracing;
...@@ -35,7 +35,7 @@ package java.lang.management; ...@@ -35,7 +35,7 @@ package java.lang.management;
* that can be obtained by calling * that can be obtained by calling
* the {@link ManagementFactory#getClassLoadingMXBean} method or * the {@link ManagementFactory#getClassLoadingMXBean} method or
* from the {@link ManagementFactory#getPlatformMBeanServer * from the {@link ManagementFactory#getPlatformMBeanServer
* platform <tt>MBeanServer</tt>} method. * platform <tt>MBeanServer</tt>}.
* *
* <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for * <p>The <tt>ObjectName</tt> for uniquely identifying the MXBean for
* the class loading system within an <tt>MBeanServer</tt> is: * the class loading system within an <tt>MBeanServer</tt> is:
...@@ -44,6 +44,10 @@ package java.lang.management; ...@@ -44,6 +44,10 @@ package java.lang.management;
* <tt>java.lang:type=ClassLoading</tt>} * <tt>java.lang:type=ClassLoading</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -52,7 +56,7 @@ package java.lang.management; ...@@ -52,7 +56,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface ClassLoadingMXBean { public interface ClassLoadingMXBean extends PlatformManagedObject {
/** /**
* Returns the total number of classes that have been loaded since * Returns the total number of classes that have been loaded since
......
...@@ -44,6 +44,10 @@ package java.lang.management; ...@@ -44,6 +44,10 @@ package java.lang.management;
* <tt>java.lang:type=Compilation</tt>} * <tt>java.lang:type=Compilation</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -52,7 +56,7 @@ package java.lang.management; ...@@ -52,7 +56,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface CompilationMXBean { public interface CompilationMXBean extends PlatformManagedObject {
/** /**
* Returns the name of the Just-in-time (JIT) compiler. * Returns the name of the Just-in-time (JIT) compiler.
* *
......
...@@ -48,9 +48,13 @@ package java.lang.management; ...@@ -48,9 +48,13 @@ package java.lang.management;
* <tt>java.lang:type=GarbageCollector</tt>}<tt>,name=</tt><i>collector's name</i> * <tt>java.lang:type=GarbageCollector</tt>}<tt>,name=</tt><i>collector's name</i>
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* A platform usually includes additional platform-dependent information * A platform usually includes additional platform-dependent information
* specific to a garbage collection algorithm for monitoring. * specific to a garbage collection algorithm for monitoring.
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see MemoryMXBean * @see MemoryMXBean
* *
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
......
...@@ -24,17 +24,31 @@ ...@@ -24,17 +24,31 @@
*/ */
package java.lang.management; package java.lang.management;
import javax.management.DynamicMBean;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import javax.management.MBeanServerConnection; import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.MBeanServerPermission; import javax.management.MBeanServerPermission;
import javax.management.NotificationEmitter;
import javax.management.ObjectInstance;
import javax.management.ObjectName; import javax.management.ObjectName;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException; import javax.management.InstanceNotFoundException;
import javax.management.MalformedObjectNameException; import javax.management.MalformedObjectNameException;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.util.Collections;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.security.AccessController; import java.security.AccessController;
import java.security.Permission; import java.security.Permission;
import java.security.PrivilegedAction; import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import javax.management.JMX; import javax.management.JMX;
import sun.management.ManagementFactoryHelper;
/** /**
* The <tt>ManagementFactory</tt> class is a factory class for getting * The <tt>ManagementFactory</tt> class is a factory class for getting
...@@ -49,13 +63,16 @@ import javax.management.JMX; ...@@ -49,13 +63,16 @@ import javax.management.JMX;
* <ul> * <ul>
* <li><i>Direct access to an MXBean interface</i> * <li><i>Direct access to an MXBean interface</i>
* <ol type="a"> * <ol type="a">
* <li>Get the MXBean instance through the static factory method * <li>Get the MXBean instance through the static factory method,
* or the {@link #getPlatformMXBeans(Class)} method
* and access the MXBean locally of the running * and access the MXBean locally of the running
* virtual machine. * virtual machine.
* </li> * </li>
* <li>Construct an MXBean proxy instance that forwards the * <li>Construct an MXBean proxy instance that forwards the
* method calls to a given {@link MBeanServer MBeanServer} by calling * method calls to a given {@link MBeanServer MBeanServer} by calling
* {@link #newPlatformMXBeanProxy newPlatfromMXBeanProxy}. * the {@link #newPlatformMXBeanProxy newPlatformMXBeanProxy} method
* or the {@link #getPlatformMXBeans(MBeanServerConnection, Class)}
* method.
* A proxy is typically constructed to remotely access * A proxy is typically constructed to remotely access
* an MXBean of another running virtual machine. * an MXBean of another running virtual machine.
* </li> * </li>
...@@ -83,6 +100,10 @@ import javax.management.JMX; ...@@ -83,6 +100,10 @@ import javax.management.JMX;
* a set of basic data types described below. * a set of basic data types described below.
* See <a href="../../../javax/management/MXBean.html#MXBean-spec"> * See <a href="../../../javax/management/MXBean.html#MXBean-spec">
* the specification of MXBeans</a> for details. * the specification of MXBeans</a> for details.
* All platform MXBean interfaces extend {@link PlatformManagedObject}s
* and new methods may be added in these interfaces
* in future Java SE releases.
* <p>
* A JMX management application and the platform <tt>MBeanServer</tt> * A JMX management application and the platform <tt>MBeanServer</tt>
* can interoperate without requiring classes for MXBean specific * can interoperate without requiring classes for MXBean specific
* data types. * data types.
...@@ -191,7 +212,10 @@ import javax.management.JMX; ...@@ -191,7 +212,10 @@ import javax.management.JMX;
* <h4><a name="MXBeanNames">MXBean Names</a></h4> * <h4><a name="MXBeanNames">MXBean Names</a></h4>
* Each platform MXBean for a Java virtual machine has a unique * Each platform MXBean for a Java virtual machine has a unique
* {@link javax.management.ObjectName ObjectName} for * {@link javax.management.ObjectName ObjectName} for
* registration in the platform <tt>MBeanServer</tt>. * registration in the platform <tt>MBeanServer</tt> that can
* be obtained by calling the {@link PlatformManagedObject#getObjectName}
* method.
*
* A Java virtual machine has a single instance of the following management * A Java virtual machine has a single instance of the following management
* interfaces: * interfaces:
* *
...@@ -275,7 +299,7 @@ import javax.management.JMX; ...@@ -275,7 +299,7 @@ import javax.management.JMX;
* </blockquote> * </blockquote>
* *
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
* Ways to Access Management Metrics</a> * Ways to Access Management Metrics</a>
* @see java.util.logging.LoggingMXBean * @see java.util.logging.LoggingMXBean
...@@ -368,7 +392,7 @@ public class ManagementFactory { ...@@ -368,7 +392,7 @@ public class ManagementFactory {
* the Java virtual machine. * the Java virtual machine.
*/ */
public static ClassLoadingMXBean getClassLoadingMXBean() { public static ClassLoadingMXBean getClassLoadingMXBean() {
return sun.management.ManagementFactory.getClassLoadingMXBean(); return ManagementFactoryHelper.getClassLoadingMXBean();
} }
/** /**
...@@ -378,7 +402,7 @@ public class ManagementFactory { ...@@ -378,7 +402,7 @@ public class ManagementFactory {
* @return a {@link MemoryMXBean} object for the Java virtual machine. * @return a {@link MemoryMXBean} object for the Java virtual machine.
*/ */
public static MemoryMXBean getMemoryMXBean() { public static MemoryMXBean getMemoryMXBean() {
return sun.management.ManagementFactory.getMemoryMXBean(); return ManagementFactoryHelper.getMemoryMXBean();
} }
/** /**
...@@ -388,7 +412,7 @@ public class ManagementFactory { ...@@ -388,7 +412,7 @@ public class ManagementFactory {
* @return a {@link ThreadMXBean} object for the Java virtual machine. * @return a {@link ThreadMXBean} object for the Java virtual machine.
*/ */
public static ThreadMXBean getThreadMXBean() { public static ThreadMXBean getThreadMXBean() {
return sun.management.ManagementFactory.getThreadMXBean(); return ManagementFactoryHelper.getThreadMXBean();
} }
/** /**
...@@ -399,7 +423,7 @@ public class ManagementFactory { ...@@ -399,7 +423,7 @@ public class ManagementFactory {
*/ */
public static RuntimeMXBean getRuntimeMXBean() { public static RuntimeMXBean getRuntimeMXBean() {
return sun.management.ManagementFactory.getRuntimeMXBean(); return ManagementFactoryHelper.getRuntimeMXBean();
} }
/** /**
...@@ -412,7 +436,7 @@ public class ManagementFactory { ...@@ -412,7 +436,7 @@ public class ManagementFactory {
* no compilation system. * no compilation system.
*/ */
public static CompilationMXBean getCompilationMXBean() { public static CompilationMXBean getCompilationMXBean() {
return sun.management.ManagementFactory.getCompilationMXBean(); return ManagementFactoryHelper.getCompilationMXBean();
} }
/** /**
...@@ -423,7 +447,7 @@ public class ManagementFactory { ...@@ -423,7 +447,7 @@ public class ManagementFactory {
* the Java virtual machine. * the Java virtual machine.
*/ */
public static OperatingSystemMXBean getOperatingSystemMXBean() { public static OperatingSystemMXBean getOperatingSystemMXBean() {
return sun.management.ManagementFactory.getOperatingSystemMXBean(); return ManagementFactoryHelper.getOperatingSystemMXBean();
} }
/** /**
...@@ -436,7 +460,7 @@ public class ManagementFactory { ...@@ -436,7 +460,7 @@ public class ManagementFactory {
* *
*/ */
public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() { public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
return sun.management.ManagementFactory.getMemoryPoolMXBeans(); return ManagementFactoryHelper.getMemoryPoolMXBeans();
} }
/** /**
...@@ -449,7 +473,7 @@ public class ManagementFactory { ...@@ -449,7 +473,7 @@ public class ManagementFactory {
* *
*/ */
public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() { public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
return sun.management.ManagementFactory.getMemoryManagerMXBeans(); return ManagementFactoryHelper.getMemoryManagerMXBeans();
} }
...@@ -465,7 +489,7 @@ public class ManagementFactory { ...@@ -465,7 +489,7 @@ public class ManagementFactory {
* *
*/ */
public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() { public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
return sun.management.ManagementFactory.getGarbageCollectorMXBeans(); return ManagementFactoryHelper.getGarbageCollectorMXBeans();
} }
private static MBeanServer platformMBeanServer; private static MBeanServer platformMBeanServer;
...@@ -518,8 +542,25 @@ public class ManagementFactory { ...@@ -518,8 +542,25 @@ public class ManagementFactory {
} }
if (platformMBeanServer == null) { if (platformMBeanServer == null) {
platformMBeanServer = platformMBeanServer = MBeanServerFactory.createMBeanServer();
sun.management.ManagementFactory.createPlatformMBeanServer(); for (PlatformComponent pc : PlatformComponent.values()) {
List<? extends PlatformManagedObject> list =
pc.getMXBeans(pc.getMXBeanInterface());
for (PlatformManagedObject o : list) {
// Each PlatformComponent represents one management
// interface. Some MXBean may extend another one.
// The MXBean instances for one platform component
// (returned by pc.getMXBeans()) might be also
// the MXBean instances for another platform component.
// e.g. com.sun.management.GarbageCollectorMXBean
//
// So need to check if an MXBean instance is registered
// before registering into the platform MBeanServer
if (!platformMBeanServer.isRegistered(o.getObjectName())) {
addMXBean(platformMBeanServer, o);
}
}
}
} }
return platformMBeanServer; return platformMBeanServer;
} }
...@@ -657,6 +698,136 @@ public class ManagementFactory { ...@@ -657,6 +698,136 @@ public class ManagementFactory {
} }
} }
/**
* Returns the list of platform MXBeans that implement
* the given {@code mxbeanInterface} in the running Java
* virtual machine.
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
*
* @param mxbeanInterface a management interface for a platform
* MXBean
*
* @return the list of platform MXBeans that implements
* {@code mxbeanInterface}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a management interface for the platform.
*
* @since 1.7
*/
public static <T extends PlatformManagedObject> List<T>
getPlatformMXBeans(Class<T> mxbeanInterface) {
String className = mxbeanInterface.getName();
for (PlatformComponent component: PlatformComponent.values()) {
// comparing the class name first instead of the Class instance
// to avoid causing unnecessary class loading of
// the other MXBean interfaces
if (className.equals(component.getMXBeanInterfaceName())) {
if (component.getMXBeanInterface() == mxbeanInterface) {
return component.getMXBeans(mxbeanInterface);
}
}
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not implemented by any of the platform MXBeans.");
}
/**
* Returns the list of the platform MXBean proxies for
* forwarding the method calls of the {@code mxbeanInterface}
* through the given {@code MBeanServerConnection}.
* The returned list may contain zero, one, or more instances.
* The number of instances in the returned list is defined
* in the specification of the given management interface.
*
* @param connection the {@code MBeanServerConnection} to forward to.
* @param mxbeanInterface a management interface for a platform
* MXBean
*
* @return the list of platform MXBean proxies for
* forwarding the method calls of the {@code mxbeanInterface}
* through the given {@code MBeanServerConnection}.
*
* @throws IllegalArgumentException if {@code mxbeanInterface}
* is not a management interface for the platform.
*
* @throws java.io.IOException if a communication problem
* occurred when accessing the {@code MBeanServerConnection}.
*
* @since 1.7
*/
public static <T extends PlatformManagedObject>
List<T> getPlatformMXBeans(MBeanServerConnection connection,
Class<T> mxbeanInterface)
throws java.io.IOException
{
String className = mxbeanInterface.getName();
for (PlatformComponent component: PlatformComponent.values()) {
// comparing the class name first instead of the Class instance
// to avoid causing unnecessary class loading of
// the other MXBean interfaces
if (className.equals(component.getMXBeanInterfaceName())) {
if (component.getMXBeanInterface() == mxbeanInterface) {
return component.getMXBeans(connection,
mxbeanInterface);
}
}
}
throw new IllegalArgumentException(mxbeanInterface.getName() +
" is not implemented by any of the platform MXBeans.");
}
/**
* Returns a list of {@code Class} objects, subinterface of
* {@link PlatformManagedObject}, representing
* all management interfaces for
* monitoring and managing the Java platform.
*
* @return a list of {@code Class} objects, subinterface of
* {@link PlatformManagedObject} representing
* the management interfaces for
* monitoring and managing the Java platform.
*
* @since 1.7
*/
public static List<Class<? extends PlatformManagedObject>> getAllPlatformMXBeanInterfaces() {
List<Class<? extends PlatformManagedObject>> result =
new ArrayList<Class<? extends PlatformManagedObject>>();
for (PlatformComponent component: PlatformComponent.values()) {
result.add(component.getMXBeanInterface());
}
return result;
}
private static final String NOTIF_EMITTER = private static final String NOTIF_EMITTER =
"javax.management.NotificationEmitter"; "javax.management.NotificationEmitter";
/**
* Registers an MXBean.
*/
private static void addMXBean(final MBeanServer mbs, final PlatformManagedObject pmo) {
// Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
final DynamicMBean dmbean;
if (pmo instanceof NotificationEmitter) {
dmbean = new StandardEmitterMBean(pmo, null, true, (NotificationEmitter) pmo);
} else {
dmbean = new StandardMBean(pmo, null, true);
}
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
mbs.registerMBean(dmbean, pmo.getObjectName());
return null;
}
});
} catch (PrivilegedActionException e) {
throw new RuntimeException(e.getException());
}
}
} }
...@@ -46,6 +46,9 @@ import javax.management.openmbean.CompositeData; ...@@ -46,6 +46,9 @@ import javax.management.openmbean.CompositeData;
* <tt>java.lang:type=Memory</tt>} * <tt>java.lang:type=Memory</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4> Memory </h4> * <h4> Memory </h4>
* The memory system of the Java virtual machine manages * The memory system of the Java virtual machine manages
* the following kinds of memory: * the following kinds of memory:
...@@ -190,6 +193,7 @@ import javax.management.openmbean.CompositeData; ...@@ -190,6 +193,7 @@ import javax.management.openmbean.CompositeData;
* emitter.addNotificationListener(listener, null, null); * emitter.addNotificationListener(listener, null, null);
* </pre></blockquote> * </pre></blockquote>
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -198,7 +202,7 @@ import javax.management.openmbean.CompositeData; ...@@ -198,7 +202,7 @@ import javax.management.openmbean.CompositeData;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface MemoryMXBean { public interface MemoryMXBean extends PlatformManagedObject {
/** /**
* Returns the approximate number of objects for which * Returns the approximate number of objects for which
* finalization is pending. * finalization is pending.
......
...@@ -45,6 +45,10 @@ package java.lang.management; ...@@ -45,6 +45,10 @@ package java.lang.management;
* <tt>java.lang:type=MemoryManager</tt>}<tt>,name=</tt><i>manager's name</i> * <tt>java.lang:type=MemoryManager</tt>}<tt>,name=</tt><i>manager's name</i>
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see MemoryMXBean * @see MemoryMXBean
* *
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
...@@ -55,7 +59,7 @@ package java.lang.management; ...@@ -55,7 +59,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface MemoryManagerMXBean { public interface MemoryManagerMXBean extends PlatformManagedObject {
/** /**
* Returns the name representing this memory manager. * Returns the name representing this memory manager.
* *
......
...@@ -46,6 +46,9 @@ package java.lang.management; ...@@ -46,6 +46,9 @@ package java.lang.management;
* <tt>java.lang:type=MemoryPool</tt>}<tt>,name=</tt><i>pool's name</i> * <tt>java.lang:type=MemoryPool</tt>}<tt>,name=</tt><i>pool's name</i>
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4>Memory Type</h4> * <h4>Memory Type</h4>
* <p>The Java virtual machine has a heap for object allocation and also * <p>The Java virtual machine has a heap for object allocation and also
* maintains non-heap memory for the method area and the Java virtual * maintains non-heap memory for the method area and the Java virtual
...@@ -349,6 +352,7 @@ package java.lang.management; ...@@ -349,6 +352,7 @@ package java.lang.management;
* described above for the <a href="#UsageThreshold">usage threshold</a> * described above for the <a href="#UsageThreshold">usage threshold</a>
* in a similar fashion. * in a similar fashion.
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -357,7 +361,7 @@ package java.lang.management; ...@@ -357,7 +361,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface MemoryPoolMXBean { public interface MemoryPoolMXBean extends PlatformManagedObject {
/** /**
* Returns the name representing this memory pool. * Returns the name representing this memory pool.
* *
......
...@@ -44,10 +44,14 @@ package java.lang.management; ...@@ -44,10 +44,14 @@ package java.lang.management;
* <tt>java.lang:type=OperatingSystem</tt>} * <tt>java.lang:type=OperatingSystem</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <p> This interface defines several convenient methods for accessing * <p> This interface defines several convenient methods for accessing
* system properties about the operating system on which the Java * system properties about the operating system on which the Java
* virtual machine is running. * virtual machine is running.
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -56,7 +60,7 @@ package java.lang.management; ...@@ -56,7 +60,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface OperatingSystemMXBean { public interface OperatingSystemMXBean extends PlatformManagedObject {
/** /**
* Returns the operating system name. * Returns the operating system name.
* This method is equivalent to <tt>System.getProperty("os.name")</tt>. * This method is equivalent to <tt>System.getProperty("os.name")</tt>.
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package java.lang.management;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.LoggingMXBean;
import java.util.logging.LogManager;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.UnixOperatingSystemMXBean;
import sun.management.ManagementFactoryHelper;
/**
* This enum class defines the list of platform components
* that provides monitoring and management support.
* Each enum represents one MXBean interface. A MXBean
* instance could implement one or more MXBean interfaces.
*
* For example, com.sun.management.GarbageCollectorMXBean
* extends java.lang.management.GarbageCollectorMXBean
* and there is one set of garbage collection MXBean instances,
* each of which implements both c.s.m. and j.l.m. interfaces.
* There are two separate enums GARBAGE_COLLECTOR
* and SUN_GARBAGE_COLLECTOR so that ManagementFactory.getPlatformMXBeans(Class)
* will return the list of MXBeans of the specified type.
*
* To add a new MXBean interface for the Java platform,
* add a new enum constant and implement the MXBeanFetcher.
*/
enum PlatformComponent {
/**
* Class loading system of the Java virtual machine.
*/
CLASS_LOADING(
"java.lang.management.ClassLoadingMXBean",
"java.lang", "ClassLoading", defaultKeyProperties(),
new MXBeanFetcher<ClassLoadingMXBean>() {
public List<ClassLoadingMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getClassLoadingMXBean());
}
}),
/**
* Compilation system of the Java virtual machine.
*/
COMPILATION(
"java.lang.management.CompilationMXBean",
"java.lang", "Compilation", defaultKeyProperties(),
new MXBeanFetcher<CompilationMXBean>() {
public List<CompilationMXBean> getMXBeans() {
CompilationMXBean m = ManagementFactoryHelper.getCompilationMXBean();
if (m == null) {
return Collections.emptyList();
} else {
return Collections.singletonList(m);
}
}
}),
/**
* Memory system of the Java virtual machine.
*/
MEMORY(
"java.lang.management.MemoryMXBean",
"java.lang", "Memory", defaultKeyProperties(),
new MXBeanFetcher<MemoryMXBean>() {
public List<MemoryMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getMemoryMXBean());
}
}),
/**
* Garbage Collector in the Java virtual machine.
*/
GARBAGE_COLLECTOR(
"java.lang.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
new MXBeanFetcher<GarbageCollectorMXBean>() {
public List<GarbageCollectorMXBean> getMXBeans() {
return ManagementFactoryHelper.
getGarbageCollectorMXBeans();
}
}),
/**
* Memory manager in the Java virtual machine.
*/
MEMORY_MANAGER(
"java.lang.management.MemoryManagerMXBean",
"java.lang", "MemoryManager", keyProperties("name"),
new MXBeanFetcher<MemoryManagerMXBean>() {
public List<MemoryManagerMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryManagerMXBeans();
}
},
GARBAGE_COLLECTOR),
/**
* Memory pool in the Java virtual machine.
*/
MEMORY_POOL(
"java.lang.management.MemoryPoolMXBean",
"java.lang", "MemoryPool", keyProperties("name"),
new MXBeanFetcher<MemoryPoolMXBean>() {
public List<MemoryPoolMXBean> getMXBeans() {
return ManagementFactoryHelper.getMemoryPoolMXBeans();
}
}),
/**
* Operating system on which the Java virtual machine is running
*/
OPERATING_SYSTEM(
"java.lang.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
new MXBeanFetcher<OperatingSystemMXBean>() {
public List<OperatingSystemMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getOperatingSystemMXBean());
}
}),
/**
* Runtime system of the Java virtual machine.
*/
RUNTIME(
"java.lang.management.RuntimeMXBean",
"java.lang", "Runtime", defaultKeyProperties(),
new MXBeanFetcher<RuntimeMXBean>() {
public List<RuntimeMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getRuntimeMXBean());
}
}),
/**
* Threading system of the Java virtual machine.
*/
THREADING(
"java.lang.management.ThreadMXBean",
"java.lang", "Threading", defaultKeyProperties(),
new MXBeanFetcher<ThreadMXBean>() {
public List<ThreadMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getThreadMXBean());
}
}),
/**
* Logging facility.
*/
LOGGING(
"java.util.logging.LoggingMXBean",
"java.util.logging", "Logging", defaultKeyProperties(),
new MXBeanFetcher<LoggingMXBean>() {
public List<LoggingMXBean> getMXBeans() {
return Collections.singletonList(LogManager.getLoggingMXBean());
}
}),
// Sun Platform Extension
/**
* Sun extension garbage collector that performs collections in cycles.
*/
SUN_GARBAGE_COLLECTOR(
"com.sun.management.GarbageCollectorMXBean",
"java.lang", "GarbageCollector", keyProperties("name"),
new MXBeanFetcher<com.sun.management.GarbageCollectorMXBean>() {
public List<com.sun.management.GarbageCollectorMXBean> getMXBeans() {
return getGcMXBeanList(com.sun.management.GarbageCollectorMXBean.class);
}
}),
/**
* Sun extension operating system on which the Java virtual machine
* is running.
*/
SUN_OPERATING_SYSTEM(
"com.sun.management.OperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
new MXBeanFetcher<com.sun.management.OperatingSystemMXBean>() {
public List<com.sun.management.OperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.OperatingSystemMXBean.class);
}
}),
/**
* Unix operating system.
*/
SUN_UNIX_OPERATING_SYSTEM(
"com.sun.management.UnixOperatingSystemMXBean",
"java.lang", "OperatingSystem", defaultKeyProperties(),
new MXBeanFetcher<UnixOperatingSystemMXBean>() {
public List<UnixOperatingSystemMXBean> getMXBeans() {
return getOSMXBeanList(com.sun.management.UnixOperatingSystemMXBean.class);
}
}),
/**
* Diagnostic support for the HotSpot Virtual Machine.
*/
HOTSPOT_DIAGNOSTIC(
"com.sun.management.HotSpotDiagnosticMXBean",
"com.sun.management", "HotSpotDiagnostic", defaultKeyProperties(),
new MXBeanFetcher<HotSpotDiagnosticMXBean>() {
public List<HotSpotDiagnosticMXBean> getMXBeans() {
return Collections.singletonList(ManagementFactoryHelper.getDiagnosticMXBean());
}
});
/**
* A task that returns the MXBeans for a component.
*/
interface MXBeanFetcher<T extends PlatformManagedObject> {
public List<T> getMXBeans();
}
/*
* Returns a list of the GC MXBeans of the given type.
*/
private static <T extends GarbageCollectorMXBean>
List<T> getGcMXBeanList(Class<T> gcMXBeanIntf) {
List<GarbageCollectorMXBean> list =
ManagementFactoryHelper.getGarbageCollectorMXBeans();
List<T> result = new ArrayList<T>(list.size());
for (GarbageCollectorMXBean m : list) {
if (gcMXBeanIntf.isInstance(m)) {
result.add(gcMXBeanIntf.cast(m));
}
}
return result;
}
/*
* Returns the OS mxbean instance of the given type.
*/
private static <T extends OperatingSystemMXBean>
List<T> getOSMXBeanList(Class<T> osMXBeanIntf) {
OperatingSystemMXBean m =
ManagementFactoryHelper.getOperatingSystemMXBean();
if (osMXBeanIntf.isInstance(m)) {
return Collections.singletonList(osMXBeanIntf.cast(m));
} else {
return Collections.emptyList();
}
}
private final String mxbeanInterfaceName;
private final String domain;
private final String type;
private final Set<String> keyProperties;
private final MXBeanFetcher fetcher;
private final PlatformComponent[] subComponents;
private PlatformComponent(String intfName,
String domain, String type,
Set<String> keyProperties,
MXBeanFetcher fetcher) {
this.mxbeanInterfaceName = intfName;
this.domain = domain;
this.type = type;
this.keyProperties = keyProperties;
this.fetcher = fetcher;
this.subComponents = new PlatformComponent[0];
}
private PlatformComponent(String intfName,
String domain, String type,
Set<String> keyProperties,
MXBeanFetcher fetcher,
PlatformComponent... subComponents) {
this.mxbeanInterfaceName = intfName;
this.domain = domain;
this.type = type;
this.keyProperties = keyProperties;
this.fetcher = fetcher;
this.subComponents = subComponents;
}
private static Set<String> defaultKeyProps;
private static Set<String> defaultKeyProperties() {
if (defaultKeyProps == null) {
defaultKeyProps = Collections.singleton("type");
}
return defaultKeyProps;
}
private static Set<String> keyProperties(String... keyNames) {
Set<String> set = new HashSet<String>();
set.add("type");
for (String s : keyNames) {
set.add(s);
}
return set;
}
String getMXBeanInterfaceName() {
return mxbeanInterfaceName;
}
@SuppressWarnings("unchecked")
Class<? extends PlatformManagedObject> getMXBeanInterface() {
try {
// Lazy loading the MXBean interface only when it is needed
return (Class<? extends PlatformManagedObject>)
Class.forName(mxbeanInterfaceName, false, null);
} catch (ClassNotFoundException x) {
throw new AssertionError(x);
}
}
@SuppressWarnings("unchecked")
<T extends PlatformManagedObject>
List<T> getMXBeans(Class<T> mxbeanInterface)
{
return fetcher.getMXBeans();
}
<T extends PlatformManagedObject>
List<T> getMXBeans(MBeanServerConnection mbs, Class<T> mxbeanInterface)
throws java.io.IOException
{
List<T> result = new ArrayList<T>();
for (ObjectName on : getObjectNames(mbs)) {
result.add(ManagementFactory.
newPlatformMXBeanProxy(mbs,
on.getCanonicalName(),
mxbeanInterface)
);
}
return result;
}
private Set<ObjectName> getObjectNames(MBeanServerConnection mbs)
throws java.io.IOException
{
String domainAndType = domain + ":type=" + type;
if (keyProperties.size() > 1) {
// if there are more than 1 key properties (i.e. other than "type")
domainAndType += ",*";
}
ObjectName on = com.sun.jmx.mbeanserver.Util.newObjectName(domainAndType);
Set<ObjectName> set = mbs.queryNames(on, null);
for (PlatformComponent pc : subComponents) {
set.addAll(pc.getObjectNames(mbs));
}
return set;
}
private static final long serialVersionUID = 6992337162326171013L;
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package java.lang.management;
import javax.management.ObjectName;
/**
* A platform managed object is a {@linkplain javax.management.MXBean JMX MXBean}
* for monitoring and managing a component in the Java platform.
* Each platform managed object has a unique
* <a href="ManagementFactory.html#MXBean">object name</a>
* for the {@linkplain ManagementFactory.getPlatformMBeanServer
* platform MBeanServer} access.
* All platform MXBeans will implement this interface.
*
* <p>
* Note:
* The platform MXBean interfaces (i.e. all subinterfaces
* of {@code PlatformManagedObject}) are implemented
* by the Java platform only. New methods may be added in these interfaces
* in future Java SE releases.
* In addition, this {@code PlatformManagedObject} interface is only
* intended for the management interfaces for the platform to extend but
* not for applications.
*
* @see <a href="ManagementFactory.html#MXBean">Platform MXBeans</a>
* @since 1.7
*/
public interface PlatformManagedObject {
/**
* Returns an {@link ObjectName ObjectName} instance representing
* the object name of this platform managed object.
*
* @return an {@link ObjectName ObjectName} instance representing
* the object name of this platform managed object.
*/
public ObjectName getObjectName();
}
...@@ -44,9 +44,13 @@ package java.lang.management; ...@@ -44,9 +44,13 @@ package java.lang.management;
* <tt>java.lang:type=Runtime</tt>} * <tt>java.lang:type=Runtime</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <p> This interface defines several convenient methods for accessing * <p> This interface defines several convenient methods for accessing
* system properties about the Java virtual machine. * system properties about the Java virtual machine.
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -55,7 +59,7 @@ package java.lang.management; ...@@ -55,7 +59,7 @@ package java.lang.management;
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
*/ */
public interface RuntimeMXBean { public interface RuntimeMXBean extends PlatformManagedObject {
/** /**
* Returns the name representing the running Java virtual machine. * Returns the name representing the running Java virtual machine.
* The returned name string can be any arbitrary string and * The returned name string can be any arbitrary string and
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package java.lang.management; package java.lang.management;
import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeData;
import sun.management.ManagementFactoryHelper;
import sun.management.ThreadInfoCompositeData; import sun.management.ThreadInfoCompositeData;
import static java.lang.Thread.State.*; import static java.lang.Thread.State.*;
...@@ -220,12 +221,9 @@ public class ThreadInfo { ...@@ -220,12 +221,9 @@ public class ThreadInfo {
LockInfo[] lockedSynchronizers) { LockInfo[] lockedSynchronizers) {
this.threadId = t.getId(); this.threadId = t.getId();
this.threadName = t.getName(); this.threadName = t.getName();
this.threadState = this.threadState = ManagementFactoryHelper.toThreadState(state);
sun.management.ManagementFactory.toThreadState(state); this.suspended = ManagementFactoryHelper.isThreadSuspended(state);
this.suspended = this.inNative = ManagementFactoryHelper.isThreadRunningNative(state);
sun.management.ManagementFactory.isThreadSuspended(state);
this.inNative =
sun.management.ManagementFactory.isThreadRunningNative(state);
this.blockedCount = blockedCount; this.blockedCount = blockedCount;
this.blockedTime = blockedTime; this.blockedTime = blockedTime;
this.waitedCount = waitedCount; this.waitedCount = waitedCount;
......
...@@ -46,6 +46,9 @@ import java.util.Map; ...@@ -46,6 +46,9 @@ import java.util.Map;
* <tt>java.lang:type=Threading</tt>} * <tt>java.lang:type=Threading</tt>}
* </blockquote> * </blockquote>
* *
* It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* <h4>Thread ID</h4> * <h4>Thread ID</h4>
* Thread ID is a positive long value returned by calling the * Thread ID is a positive long value returned by calling the
* {@link java.lang.Thread#getId} method for a thread. * {@link java.lang.Thread#getId} method for a thread.
...@@ -108,6 +111,7 @@ import java.util.Map; ...@@ -108,6 +111,7 @@ import java.util.Map;
* {@link #findDeadlockedThreads} methods to find deadlocks in * {@link #findDeadlockedThreads} methods to find deadlocks in
* the running application. * the running application.
* *
* @see ManagementFactory#getPlatformMXBeans(Class)
* @see <a href="../../../javax/management/package-summary.html"> * @see <a href="../../../javax/management/package-summary.html">
* JMX Specification.</a> * JMX Specification.</a>
* @see <a href="package-summary.html#examples"> * @see <a href="package-summary.html#examples">
...@@ -117,7 +121,7 @@ import java.util.Map; ...@@ -117,7 +121,7 @@ import java.util.Map;
* @since 1.5 * @since 1.5
*/ */
public interface ThreadMXBean { public interface ThreadMXBean extends PlatformManagedObject {
/** /**
* Returns the current number of live threads including both * Returns the current number of live threads including both
* daemon and non-daemon threads. * daemon and non-daemon threads.
......
...@@ -29,6 +29,8 @@ import java.util.Enumeration; ...@@ -29,6 +29,8 @@ import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import javax.management.ObjectName;
/** /**
* Logging is the implementation class of LoggingMXBean. * Logging is the implementation class of LoggingMXBean.
* *
...@@ -115,4 +117,7 @@ class Logging implements LoggingMXBean { ...@@ -115,4 +117,7 @@ class Logging implements LoggingMXBean {
} }
} }
public ObjectName getObjectName() {
return com.sun.jmx.mbeanserver.Util.newObjectName(LogManager.LOGGING_MXBEAN_NAME);
}
} }
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
package java.util.logging; package java.util.logging;
import java.lang.management.PlatformManagedObject;
/** /**
* The management interface for the logging facility. * The management interface for the logging facility.
* *
...@@ -43,14 +45,17 @@ package java.util.logging; ...@@ -43,14 +45,17 @@ package java.util.logging;
* <tt>java.util.logging:type=Logging</tt>} * <tt>java.util.logging:type=Logging</tt>}
* </blockquote> * </blockquote>
* *
* @see java.lang.management.ManagementFactory * It can be obtained by calling the
* {@link PlatformManagedObject#getObjectName} method.
*
* @see java.lang.management.ManagementFactory#getPlatformMXBeans(Class)
* *
* @author Ron Mann * @author Ron Mann
* @author Mandy Chung * @author Mandy Chung
* @since 1.5 * @since 1.5
* *
*/ */
public interface LoggingMXBean { public interface LoggingMXBean extends PlatformManagedObject {
/** /**
* Returns the list of currently registered loggers. This method * Returns the list of currently registered loggers. This method
......
...@@ -2844,7 +2844,15 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) { ...@@ -2844,7 +2844,15 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
/** /**
* Utility method for parsing unicode escape sequences. * Utility method for parsing unicode escape sequences.
*/ */
private int u() { private int cursor() {
return cursor;
}
private void setcursor(int pos) {
cursor = pos;
}
private int uxxxx() {
int n = 0; int n = 0;
for (int i = 0; i < 4; i++) { for (int i = 0; i < 4; i++) {
int ch = read(); int ch = read();
...@@ -2856,6 +2864,20 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) { ...@@ -2856,6 +2864,20 @@ loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
return n; return n;
} }
private int u() {
int n = uxxxx();
if (Character.isHighSurrogate((char)n)) {
int cur = cursor();
if (read() == '\\' && read() == 'u') {
int n2 = uxxxx();
if (Character.isLowSurrogate((char)n2))
return Character.toCodePoint((char)n, (char)n2);
}
setcursor(cur);
}
return n;
}
// //
// Utility methods for code point support // Utility methods for code point support
// //
......
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
package sun.management; package sun.management;
import java.lang.management.ClassLoadingMXBean; import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
/** /**
* Implementation class for the class loading subsystem. * Implementation class for the class loading subsystem.
...@@ -62,9 +64,13 @@ class ClassLoadingImpl implements ClassLoadingMXBean { ...@@ -62,9 +64,13 @@ class ClassLoadingImpl implements ClassLoadingMXBean {
} }
public void setVerbose(boolean value) { public void setVerbose(boolean value) {
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
setVerboseClass(value); setVerboseClass(value);
} }
native static void setVerboseClass(boolean value); native static void setVerboseClass(boolean value);
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.CLASS_LOADING_MXBEAN_NAME);
}
} }
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
package sun.management; package sun.management;
import java.lang.management.CompilationMXBean; import java.lang.management.CompilationMXBean;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
/** /**
* Implementation class for the compilation subsystem. * Implementation class for the compilation subsystem.
...@@ -46,7 +48,7 @@ class CompilationImpl implements CompilationMXBean { ...@@ -46,7 +48,7 @@ class CompilationImpl implements CompilationMXBean {
this.jvm = vm; this.jvm = vm;
this.name = jvm.getCompilerName(); this.name = jvm.getCompilerName();
if (name == null) { if (name == null) {
throw new InternalError("Null compiler name"); throw new AssertionError("Null compiler name");
} }
} }
...@@ -67,4 +69,9 @@ class CompilationImpl implements CompilationMXBean { ...@@ -67,4 +69,9 @@ class CompilationImpl implements CompilationMXBean {
return jvm.getTotalCompileTime(); return jvm.getTotalCompileTime();
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.COMPILATION_MXBEAN_NAME);
}
} }
...@@ -34,6 +34,7 @@ import com.sun.management.GcInfo; ...@@ -34,6 +34,7 @@ import com.sun.management.GcInfo;
import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeData;
import javax.management.MBeanInfo; import javax.management.MBeanInfo;
import javax.management.MBeanAttributeInfo; import javax.management.MBeanAttributeInfo;
import javax.management.ObjectName;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
...@@ -88,4 +89,8 @@ class GarbageCollectorImpl extends MemoryManagerImpl ...@@ -88,4 +89,8 @@ class GarbageCollectorImpl extends MemoryManagerImpl
return info; return info;
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE, getName());
}
} }
...@@ -145,7 +145,7 @@ public class GcInfoBuilder { ...@@ -145,7 +145,7 @@ public class GcInfoBuilder {
allItemTypes[i] = SimpleType.DOUBLE; allItemTypes[i] = SimpleType.DOUBLE;
break; break;
default: default:
throw new InternalError( throw new AssertionError(
"Unsupported type [" + gcExtItemTypes[i] + "]"); "Unsupported type [" + gcExtItemTypes[i] + "]");
} }
} }
......
...@@ -80,19 +80,19 @@ public class GcInfoCompositeData extends LazyCompositeData { ...@@ -80,19 +80,19 @@ public class GcInfoCompositeData extends LazyCompositeData {
}; };
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
// Get the item values for the extension attributes // Get the item values for the extension attributes
final int gcExtItemCount = builder.getGcExtItemCount(); final int gcExtItemCount = builder.getGcExtItemCount();
if (gcExtItemCount == 0 && if (gcExtItemCount == 0 &&
gcExtItemValues != null && gcExtItemValues.length != 0) { gcExtItemValues != null && gcExtItemValues.length != 0) {
throw new InternalError("Unexpected Gc Extension Item Values"); throw new AssertionError("Unexpected Gc Extension Item Values");
} }
if (gcExtItemCount > 0 && (gcExtItemValues == null || if (gcExtItemCount > 0 && (gcExtItemValues == null ||
gcExtItemCount != gcExtItemValues.length)) { gcExtItemCount != gcExtItemValues.length)) {
throw new InternalError("Unmatched Gc Extension Item Values"); throw new AssertionError("Unmatched Gc Extension Item Values");
} }
Object[] values = new Object[baseGcInfoItemValues.length + Object[] values = new Object[baseGcInfoItemValues.length +
...@@ -111,7 +111,7 @@ public class GcInfoCompositeData extends LazyCompositeData { ...@@ -111,7 +111,7 @@ public class GcInfoCompositeData extends LazyCompositeData {
values); values);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -141,10 +141,10 @@ public class GcInfoCompositeData extends LazyCompositeData { ...@@ -141,10 +141,10 @@ public class GcInfoCompositeData extends LazyCompositeData {
MappedMXBeanType.getMappedType(m.getGenericReturnType()); MappedMXBeanType.getMappedType(m.getGenericReturnType());
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
} }
...@@ -186,10 +186,10 @@ public class GcInfoCompositeData extends LazyCompositeData { ...@@ -186,10 +186,10 @@ public class GcInfoCompositeData extends LazyCompositeData {
return cast(memoryUsageMapType.toJavaTypeData(td)); return cast(memoryUsageMapType.toJavaTypeData(td));
} catch (InvalidObjectException e) { } catch (InvalidObjectException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
} }
...@@ -205,10 +205,10 @@ public class GcInfoCompositeData extends LazyCompositeData { ...@@ -205,10 +205,10 @@ public class GcInfoCompositeData extends LazyCompositeData {
return cast(memoryUsageMapType.toJavaTypeData(td)); return cast(memoryUsageMapType.toJavaTypeData(td));
} catch (InvalidObjectException e) { } catch (InvalidObjectException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
} }
......
...@@ -28,6 +28,8 @@ package sun.management; ...@@ -28,6 +28,8 @@ package sun.management;
import java.util.*; import java.util.*;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import javax.management.ObjectName;
import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption; import com.sun.management.VMOption;
...@@ -72,7 +74,7 @@ public class HotSpotDiagnostic implements HotSpotDiagnosticMXBean { ...@@ -72,7 +74,7 @@ public class HotSpotDiagnostic implements HotSpotDiagnosticMXBean {
throw new NullPointerException("value cannot be null"); throw new NullPointerException("value cannot be null");
} }
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
Flag flag = Flag.getFlag(name); Flag flag = Flag.getFlag(name);
if (flag == null) { if (flag == null) {
throw new IllegalArgumentException("VM option \"" + throw new IllegalArgumentException("VM option \"" +
...@@ -113,4 +115,8 @@ public class HotSpotDiagnostic implements HotSpotDiagnosticMXBean { ...@@ -113,4 +115,8 @@ public class HotSpotDiagnostic implements HotSpotDiagnosticMXBean {
v.getClass().getName()); v.getClass().getName());
} }
} }
public ObjectName getObjectName() {
return Util.newObjectName("com.sun.management:type=HotSpotDiagnostic");
}
} }
...@@ -131,7 +131,7 @@ class HotspotCompilation ...@@ -131,7 +131,7 @@ class HotspotCompilation
} }
// FIXME: should tolerate if counter doesn't exist // FIXME: should tolerate if counter doesn't exist
throw new InternalError("Counter " + name + " does not exist"); throw new AssertionError("Counter " + name + " does not exist");
} }
private void initCompilerCounters() { private void initCompilerCounters() {
......
...@@ -39,6 +39,9 @@ import javax.management.ObjectName; ...@@ -39,6 +39,9 @@ import javax.management.ObjectName;
public class HotspotInternal public class HotspotInternal
implements HotspotInternalMBean, MBeanRegistration { implements HotspotInternalMBean, MBeanRegistration {
private final static String HOTSPOT_INTERNAL_MBEAN_NAME =
"sun.management:type=HotspotInternal";
private static ObjectName objName = Util.newObjectName(HOTSPOT_INTERNAL_MBEAN_NAME);
private MBeanServer server = null; private MBeanServer server = null;
/** /**
...@@ -52,16 +55,16 @@ public class HotspotInternal ...@@ -52,16 +55,16 @@ public class HotspotInternal
ObjectName name) throws java.lang.Exception { ObjectName name) throws java.lang.Exception {
// register all internal MBeans when this MBean is instantiated // register all internal MBeans when this MBean is instantiated
// and to be registered in a MBeanServer. // and to be registered in a MBeanServer.
ManagementFactory.registerInternalMBeans(server); ManagementFactoryHelper.registerInternalMBeans(server);
this.server = server; this.server = server;
return ManagementFactory.getHotspotInternalObjectName(); return objName;
} }
public void postRegister(Boolean registrationDone) {}; public void postRegister(Boolean registrationDone) {};
public void preDeregister() throws java.lang.Exception { public void preDeregister() throws java.lang.Exception {
// unregister all internal MBeans when this MBean is unregistered. // unregister all internal MBeans when this MBean is unregistered.
ManagementFactory.unregisterInternalMBeans(server); ManagementFactoryHelper.unregisterInternalMBeans(server);
} }
public void postDeregister() {}; public void postDeregister() {};
......
...@@ -73,7 +73,7 @@ class LockDataConverter extends StandardMBean ...@@ -73,7 +73,7 @@ class LockDataConverter extends StandardMBean
try { try {
return (CompositeData) getAttribute("LockInfo"); return (CompositeData) getAttribute("LockInfo");
} catch (Exception e) { } catch (Exception e) {
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -81,7 +81,7 @@ class LockDataConverter extends StandardMBean ...@@ -81,7 +81,7 @@ class LockDataConverter extends StandardMBean
try { try {
return (CompositeData[]) getAttribute("LockedSynchronizers"); return (CompositeData[]) getAttribute("LockedSynchronizers");
} catch (Exception e) { } catch (Exception e) {
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -89,7 +89,7 @@ class LockDataConverter extends StandardMBean ...@@ -89,7 +89,7 @@ class LockDataConverter extends StandardMBean
try { try {
setAttribute(new Attribute("LockInfo", cd)); setAttribute(new Attribute("LockInfo", cd));
} catch (Exception e) { } catch (Exception e) {
throw Util.newInternalError(e); throw new AssertionError(e);
} }
return getLockInfo(); return getLockInfo();
} }
...@@ -98,7 +98,7 @@ class LockDataConverter extends StandardMBean ...@@ -98,7 +98,7 @@ class LockDataConverter extends StandardMBean
try { try {
setAttribute(new Attribute("LockedSynchronizers", cd)); setAttribute(new Attribute("LockedSynchronizers", cd));
} catch (Exception e) { } catch (Exception e) {
throw Util.newInternalError(e); throw new AssertionError(e);
} }
return getLockedSynchronizers(); return getLockedSynchronizers();
} }
......
/* /*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -25,445 +25,17 @@ ...@@ -25,445 +25,17 @@
package sun.management; package sun.management;
import java.lang.management.*; import java.lang.management.MemoryManagerMXBean;
import java.util.logging.LogManager; import java.lang.management.MemoryPoolMXBean;
import java.lang.management.GarbageCollectorMXBean;
import javax.management.DynamicMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MBeanInfo;
import javax.management.NotificationEmitter;
import javax.management.ObjectName;
import javax.management.ObjectInstance;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.MalformedObjectNameException;
import javax.management.RuntimeOperationsException;
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.security.action.LoadLibraryAction;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.util.ListIterator;
import com.sun.management.OSMBeanFactory;
import com.sun.management.HotSpotDiagnosticMXBean;
import static java.lang.management.ManagementFactory.*;
/** /**
* ManagementFactory provides static factory methods to create * ManagementFactory class provides the methods that the HotSpot VM
* instances of the management interface. * will invoke. So the class and method names cannot be renamed.
*/ */
public class ManagementFactory { class ManagementFactory {
private ManagementFactory() {}; private ManagementFactory() {};
private static VMManagement jvm;
private static boolean mbeansCreated = false;
private static ClassLoadingImpl classMBean = null;
private static MemoryImpl memoryMBean = null;
private static ThreadImpl threadMBean = null;
private static RuntimeImpl runtimeMBean = null;
private static CompilationImpl compileMBean = null;
private static OperatingSystemImpl osMBean = null;
public static synchronized ClassLoadingMXBean getClassLoadingMXBean() {
if (classMBean == null) {
classMBean = new ClassLoadingImpl(jvm);
}
return classMBean;
}
public static synchronized MemoryMXBean getMemoryMXBean() {
if (memoryMBean == null) {
memoryMBean = new MemoryImpl(jvm);
}
return memoryMBean;
}
public static synchronized ThreadMXBean getThreadMXBean() {
if (threadMBean == null) {
threadMBean = new ThreadImpl(jvm);
}
return threadMBean;
}
public static synchronized RuntimeMXBean getRuntimeMXBean() {
if (runtimeMBean == null) {
runtimeMBean = new RuntimeImpl(jvm);
}
return runtimeMBean;
}
public static synchronized CompilationMXBean getCompilationMXBean() {
if (compileMBean == null && jvm.getCompilerName() != null) {
compileMBean = new CompilationImpl(jvm);
}
return compileMBean;
}
public static synchronized OperatingSystemMXBean getOperatingSystemMXBean() {
if (osMBean == null) {
osMBean = (OperatingSystemImpl)
OSMBeanFactory.getOperatingSystemMXBean(jvm);
}
return osMBean;
}
public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
MemoryPoolMXBean[] pools = MemoryImpl.getMemoryPools();
List<MemoryPoolMXBean> list = new ArrayList<MemoryPoolMXBean>(pools.length);
for (int i = 0; i < pools.length; i++) {
MemoryPoolMXBean p = pools[i];
list.add(p);
}
return list;
}
public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers();
List<MemoryManagerMXBean> result = new ArrayList<MemoryManagerMXBean>(mgrs.length);
for (int i = 0; i < mgrs.length; i++) {
MemoryManagerMXBean m = mgrs[i];
result.add(m);
}
return result;
}
public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers();
List<GarbageCollectorMXBean> result = new ArrayList<GarbageCollectorMXBean>(mgrs.length);
for (int i = 0; i < mgrs.length; i++) {
if (mgrs[i] instanceof GarbageCollectorMXBean) {
GarbageCollectorMXBean gc = (GarbageCollectorMXBean) mgrs[i];
result.add(gc);
}
}
return result;
}
private static HotSpotDiagnostic hsDiagMBean = null;
private static HotspotRuntime hsRuntimeMBean = null;
private static HotspotClassLoading hsClassMBean = null;
private static HotspotThread hsThreadMBean = null;
private static HotspotCompilation hsCompileMBean = null;
private static HotspotMemory hsMemoryMBean = null;
public static synchronized HotSpotDiagnosticMXBean getDiagnosticMXBean() {
if (hsDiagMBean == null) {
hsDiagMBean = new HotSpotDiagnostic();
}
return hsDiagMBean;
}
/**
/**
* This method is for testing only.
*/
public static synchronized HotspotRuntimeMBean getHotspotRuntimeMBean() {
if (hsRuntimeMBean == null) {
hsRuntimeMBean = new HotspotRuntime(jvm);
}
return hsRuntimeMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotClassLoadingMBean getHotspotClassLoadingMBean() {
if (hsClassMBean == null) {
hsClassMBean = new HotspotClassLoading(jvm);
}
return hsClassMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotThreadMBean getHotspotThreadMBean() {
if (hsThreadMBean == null) {
hsThreadMBean = new HotspotThread(jvm);
}
return hsThreadMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotMemoryMBean getHotspotMemoryMBean() {
if (hsMemoryMBean == null) {
hsMemoryMBean = new HotspotMemory(jvm);
}
return hsMemoryMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotCompilationMBean getHotspotCompilationMBean() {
if (hsCompileMBean == null) {
hsCompileMBean = new HotspotCompilation(jvm);
}
return hsCompileMBean;
}
private static Permission monitorPermission =
new ManagementPermission("monitor");
private static Permission controlPermission =
new ManagementPermission("control");
/**
* Check that the current context is trusted to perform monitoring
* or management.
* <p>
* If the check fails we throw a SecurityException, otherwise
* we return normally.
*
* @exception SecurityException if a security manager exists and if
* the caller does not have ManagementPermission("control").
*/
static void checkAccess(Permission p)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(p);
}
}
static void checkMonitorAccess() throws SecurityException {
checkAccess(monitorPermission);
}
static void checkControlAccess() throws SecurityException {
checkAccess(controlPermission);
}
/**
* Registers an MXBean and throws exception if an instance with the same
* name exists.
*
* This method makes a DynamicMBean out of an MXBean by wrapping it with a
* StandardMBean (StandardEmitterMBean if the supplied emitter is not null),
* so it can be registered in an MBeanServer which does not have support for
* MXBeans.
*/
private static void addMXBean(MBeanServer mbs, Object mbean,
String mbeanName, NotificationEmitter emitter) {
// Make DynamicMBean out of MXBean by wrapping it with a StandardMBean
//
final DynamicMBean dmbean;
if (emitter == null) {
dmbean = new StandardMBean(mbean, null, true);
} else {
dmbean = new StandardEmitterMBean(mbean, null, true, emitter);
}
addMBean(mbs, dmbean, mbeanName, false);
}
/**
* Registers a Standard MBean or a Dynamic MBean and throws
* exception if an instance with the same name exists.
*/
private static void addMBean(MBeanServer mbs, Object mbean, String mbeanName) {
addMBean(mbs, mbean, mbeanName, false);
}
private static void addMBean(MBeanServer mbs, Object mbean,
String mbeanName, boolean ignoreConflicts) {
try {
final ObjectName objName = new ObjectName(mbeanName);
// inner class requires these fields to be final
final MBeanServer mbs0 = mbs;
final Object mbean0 = mbean;
final boolean ignore = ignoreConflicts;
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws InstanceAlreadyExistsException,
MBeanRegistrationException,
NotCompliantMBeanException {
try {
ObjectInstance o = mbs0.registerMBean(mbean0,
objName);
return null;
} catch (InstanceAlreadyExistsException e) {
// if an instance with the object name exists in
// the MBeanServer ignore the exception
// if ignoreConflicts is true;
// otherwise, throws exception.
if (!ignore) {
throw e;
}
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw Util.newException(e.getException());
} catch (MalformedObjectNameException e) {
// should not reach here
throw Util.newException(e);
}
}
public static MBeanServer createPlatformMBeanServer() {
MBeanServer mbs = MBeanServerFactory.createMBeanServer();
// Register all the platform MBeans to this MBeanServer
addMXBean(mbs, getClassLoadingMXBean(),
CLASS_LOADING_MXBEAN_NAME, null);
addMXBean(mbs, getMemoryMXBean(),
MEMORY_MXBEAN_NAME, (NotificationEmitter) getMemoryMXBean());
addMXBean(mbs, getOperatingSystemMXBean(),
OPERATING_SYSTEM_MXBEAN_NAME, null);
addMXBean(mbs, getRuntimeMXBean(),
RUNTIME_MXBEAN_NAME, null);
addMXBean(mbs, getThreadMXBean(),
THREAD_MXBEAN_NAME, null);
addMXBean(mbs, getDiagnosticMXBean(),
HOTSPOT_DIAGNOSTIC_MXBEAN_NAME, null);
// CompilationMBean may not exist
if (getCompilationMXBean() != null) {
addMXBean(mbs, getCompilationMXBean(),
COMPILATION_MXBEAN_NAME, null);
}
// Register MBeans for memory pools and memory managers
addMemoryManagers(mbs);
addMemoryPools(mbs);
// Register platform extension
addMXBean(mbs, LogManager.getLoggingMXBean(),
LogManager.LOGGING_MXBEAN_NAME, null);
return mbs;
}
private final static String HOTSPOT_DIAGNOSTIC_MXBEAN_NAME =
"com.sun.management:type=HotSpotDiagnostic";
private final static String HOTSPOT_CLASS_LOADING_MBEAN_NAME =
"sun.management:type=HotspotClassLoading";
private final static String HOTSPOT_COMPILATION_MBEAN_NAME =
"sun.management:type=HotspotCompilation";
private final static String HOTSPOT_MEMORY_MBEAN_NAME =
"sun.management:type=HotspotMemory";
private static final String HOTSPOT_RUNTIME_MBEAN_NAME =
"sun.management:type=HotspotRuntime";
private final static String HOTSPOT_THREAD_MBEAN_NAME =
"sun.management:type=HotspotThreading";
private final static String HOTSPOT_INTERNAL_MBEAN_NAME =
"sun.management:type=HotspotInternal";
private static ObjectName hsInternalObjName = null;
static synchronized ObjectName getHotspotInternalObjectName() {
if (hsInternalObjName == null) {
try {
hsInternalObjName = new ObjectName(HOTSPOT_INTERNAL_MBEAN_NAME);
} catch (MalformedObjectNameException e) {
// should not reach here
throw Util.newException(e);
}
}
return hsInternalObjName;
}
static void registerInternalMBeans(MBeanServer mbs) {
// register all internal MBeans if not registered
// No exception is thrown if a MBean with that object name
// already registered (i.e. ignore if name conflicts).
addMBean(mbs, getHotspotClassLoadingMBean(),
HOTSPOT_CLASS_LOADING_MBEAN_NAME, true);
addMBean(mbs, getHotspotMemoryMBean(),
HOTSPOT_MEMORY_MBEAN_NAME, true);
addMBean(mbs, getHotspotRuntimeMBean(),
HOTSPOT_RUNTIME_MBEAN_NAME, true);
addMBean(mbs, getHotspotThreadMBean(),
HOTSPOT_THREAD_MBEAN_NAME, true);
// CompilationMBean may not exist
if (getCompilationMXBean() != null) {
addMBean(mbs, getHotspotCompilationMBean(),
HOTSPOT_COMPILATION_MBEAN_NAME, true);
}
}
private static void unregisterMBean(MBeanServer mbs, String mbeanName) {
try {
final ObjectName objName = new ObjectName(mbeanName);
// inner class requires these fields to be final
final MBeanServer mbs0 = mbs;
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws MBeanRegistrationException,
RuntimeOperationsException {
try {
mbs0.unregisterMBean(objName);
} catch (InstanceNotFoundException e) {
// ignore exception if not found
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw Util.newException(e.getException());
} catch (MalformedObjectNameException e) {
// should not reach here
throw Util.newException(e);
}
}
static void unregisterInternalMBeans(MBeanServer mbs) {
// unregister all internal MBeans
unregisterMBean(mbs, HOTSPOT_CLASS_LOADING_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_MEMORY_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_RUNTIME_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_THREAD_MBEAN_NAME);
// CompilationMBean may not exist
if (getCompilationMXBean() != null) {
unregisterMBean(mbs, HOTSPOT_COMPILATION_MBEAN_NAME);
}
}
private static synchronized void addMemoryPools(MBeanServer mbs) {
// Get a list of memory pools
MemoryPoolMXBean[] newPools = MemoryImpl.getMemoryPools();
for (int i = 0; i < newPools.length; i++) {
String poolObjNameString = Util.getMBeanObjectName(newPools[i]);
addMXBean(mbs, newPools[i], poolObjNameString, null);
}
}
// Register all memory managers with the MBeanServer;
private static synchronized void addMemoryManagers(MBeanServer mbs) {
// Get a list of memory managers
MemoryManagerMXBean[] newMgrs = MemoryImpl.getMemoryManagers();
for (int i = 0; i < newMgrs.length; i++) {
String mgrObjNameString = Util.getMBeanObjectName(newMgrs[i]);
addMXBean(mbs, newMgrs[i], mgrObjNameString, null);
}
}
// Invoked by the VM // Invoked by the VM
private static MemoryPoolMXBean createMemoryPool private static MemoryPoolMXBean createMemoryPool
(String name, boolean isHeap, long uThreshold, long gcThreshold) { (String name, boolean isHeap, long uThreshold, long gcThreshold) {
...@@ -480,29 +52,4 @@ public class ManagementFactory { ...@@ -480,29 +52,4 @@ public class ManagementFactory {
// ignore type parameter which is for future extension // ignore type parameter which is for future extension
return new GarbageCollectorImpl(name); return new GarbageCollectorImpl(name);
} }
static {
AccessController.doPrivileged(new LoadLibraryAction("management"));
jvm = new VMManagementImpl();
}
public static boolean isThreadSuspended(int state) {
return ((state & JMM_THREAD_STATE_FLAG_SUSPENDED) != 0);
}
public static boolean isThreadRunningNative(int state) {
return ((state & JMM_THREAD_STATE_FLAG_NATIVE) != 0);
}
public static Thread.State toThreadState(int state) {
// suspended and native bits may be set in state
int threadStatus = state & ~JMM_THREAD_STATE_FLAG_MASK;
return sun.misc.VM.toThreadState(threadStatus);
}
// These values are defined in jmm.h
private static final int JMM_THREAD_STATE_FLAG_MASK = 0xFFF00000;
private static final int JMM_THREAD_STATE_FLAG_SUSPENDED = 0x00100000;
private static final int JMM_THREAD_STATE_FLAG_NATIVE = 0x00400000;
} }
/*
* Copyright 2003-2006 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.management;
import java.lang.management.*;
import java.util.logging.LogManager;
import javax.management.DynamicMBean;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MBeanInfo;
import javax.management.NotificationEmitter;
import javax.management.ObjectName;
import javax.management.ObjectInstance;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanRegistrationException;
import javax.management.NotCompliantMBeanException;
import javax.management.RuntimeOperationsException;
import javax.management.StandardEmitterMBean;
import javax.management.StandardMBean;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import sun.security.action.LoadLibraryAction;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.util.ListIterator;
import com.sun.management.OSMBeanFactory;
import com.sun.management.HotSpotDiagnosticMXBean;
import static java.lang.management.ManagementFactory.*;
/**
* ManagementFactoryHelper provides static factory methods to create
* instances of the management interface.
*/
public class ManagementFactoryHelper {
private ManagementFactoryHelper() {};
private static VMManagement jvm;
private static boolean mbeansCreated = false;
private static ClassLoadingImpl classMBean = null;
private static MemoryImpl memoryMBean = null;
private static ThreadImpl threadMBean = null;
private static RuntimeImpl runtimeMBean = null;
private static CompilationImpl compileMBean = null;
private static OperatingSystemImpl osMBean = null;
public static synchronized ClassLoadingMXBean getClassLoadingMXBean() {
if (classMBean == null) {
classMBean = new ClassLoadingImpl(jvm);
}
return classMBean;
}
public static synchronized MemoryMXBean getMemoryMXBean() {
if (memoryMBean == null) {
memoryMBean = new MemoryImpl(jvm);
}
return memoryMBean;
}
public static synchronized ThreadMXBean getThreadMXBean() {
if (threadMBean == null) {
threadMBean = new ThreadImpl(jvm);
}
return threadMBean;
}
public static synchronized RuntimeMXBean getRuntimeMXBean() {
if (runtimeMBean == null) {
runtimeMBean = new RuntimeImpl(jvm);
}
return runtimeMBean;
}
public static synchronized CompilationMXBean getCompilationMXBean() {
if (compileMBean == null && jvm.getCompilerName() != null) {
compileMBean = new CompilationImpl(jvm);
}
return compileMBean;
}
public static synchronized OperatingSystemMXBean getOperatingSystemMXBean() {
if (osMBean == null) {
osMBean = (OperatingSystemImpl)
OSMBeanFactory.getOperatingSystemMXBean(jvm);
}
return osMBean;
}
public static List<MemoryPoolMXBean> getMemoryPoolMXBeans() {
MemoryPoolMXBean[] pools = MemoryImpl.getMemoryPools();
List<MemoryPoolMXBean> list = new ArrayList<MemoryPoolMXBean>(pools.length);
for (MemoryPoolMXBean p : pools) {
list.add(p);
}
return list;
}
public static List<MemoryManagerMXBean> getMemoryManagerMXBeans() {
MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers();
List<MemoryManagerMXBean> result = new ArrayList<MemoryManagerMXBean>(mgrs.length);
for (MemoryManagerMXBean m : mgrs) {
result.add(m);
}
return result;
}
public static List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() {
MemoryManagerMXBean[] mgrs = MemoryImpl.getMemoryManagers();
List<GarbageCollectorMXBean> result = new ArrayList<GarbageCollectorMXBean>(mgrs.length);
for (MemoryManagerMXBean m : mgrs) {
if (GarbageCollectorMXBean.class.isInstance(m)) {
result.add(GarbageCollectorMXBean.class.cast(m));
}
}
return result;
}
private static HotSpotDiagnostic hsDiagMBean = null;
private static HotspotRuntime hsRuntimeMBean = null;
private static HotspotClassLoading hsClassMBean = null;
private static HotspotThread hsThreadMBean = null;
private static HotspotCompilation hsCompileMBean = null;
private static HotspotMemory hsMemoryMBean = null;
public static synchronized HotSpotDiagnosticMXBean getDiagnosticMXBean() {
if (hsDiagMBean == null) {
hsDiagMBean = new HotSpotDiagnostic();
}
return hsDiagMBean;
}
/**
/**
* This method is for testing only.
*/
public static synchronized HotspotRuntimeMBean getHotspotRuntimeMBean() {
if (hsRuntimeMBean == null) {
hsRuntimeMBean = new HotspotRuntime(jvm);
}
return hsRuntimeMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotClassLoadingMBean getHotspotClassLoadingMBean() {
if (hsClassMBean == null) {
hsClassMBean = new HotspotClassLoading(jvm);
}
return hsClassMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotThreadMBean getHotspotThreadMBean() {
if (hsThreadMBean == null) {
hsThreadMBean = new HotspotThread(jvm);
}
return hsThreadMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotMemoryMBean getHotspotMemoryMBean() {
if (hsMemoryMBean == null) {
hsMemoryMBean = new HotspotMemory(jvm);
}
return hsMemoryMBean;
}
/**
* This method is for testing only.
*/
public static synchronized HotspotCompilationMBean getHotspotCompilationMBean() {
if (hsCompileMBean == null) {
hsCompileMBean = new HotspotCompilation(jvm);
}
return hsCompileMBean;
}
/**
* Registers a given MBean if not registered in the MBeanServer;
* otherwise, just return.
*/
private static void addMBean(MBeanServer mbs, Object mbean, String mbeanName) {
try {
final ObjectName objName = Util.newObjectName(mbeanName);
// inner class requires these fields to be final
final MBeanServer mbs0 = mbs;
final Object mbean0 = mbean;
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws MBeanRegistrationException,
NotCompliantMBeanException {
try {
mbs0.registerMBean(mbean0, objName);
return null;
} catch (InstanceAlreadyExistsException e) {
// if an instance with the object name exists in
// the MBeanServer ignore the exception
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw Util.newException(e.getException());
}
}
private final static String HOTSPOT_CLASS_LOADING_MBEAN_NAME =
"sun.management:type=HotspotClassLoading";
private final static String HOTSPOT_COMPILATION_MBEAN_NAME =
"sun.management:type=HotspotCompilation";
private final static String HOTSPOT_MEMORY_MBEAN_NAME =
"sun.management:type=HotspotMemory";
private static final String HOTSPOT_RUNTIME_MBEAN_NAME =
"sun.management:type=HotspotRuntime";
private final static String HOTSPOT_THREAD_MBEAN_NAME =
"sun.management:type=HotspotThreading";
static void registerInternalMBeans(MBeanServer mbs) {
// register all internal MBeans if not registered
// No exception is thrown if a MBean with that object name
// already registered
addMBean(mbs, getHotspotClassLoadingMBean(),
HOTSPOT_CLASS_LOADING_MBEAN_NAME);
addMBean(mbs, getHotspotMemoryMBean(),
HOTSPOT_MEMORY_MBEAN_NAME);
addMBean(mbs, getHotspotRuntimeMBean(),
HOTSPOT_RUNTIME_MBEAN_NAME);
addMBean(mbs, getHotspotThreadMBean(),
HOTSPOT_THREAD_MBEAN_NAME);
// CompilationMBean may not exist
if (getCompilationMXBean() != null) {
addMBean(mbs, getHotspotCompilationMBean(),
HOTSPOT_COMPILATION_MBEAN_NAME);
}
}
private static void unregisterMBean(MBeanServer mbs, String mbeanName) {
try {
final ObjectName objName = Util.newObjectName(mbeanName);
// inner class requires these fields to be final
final MBeanServer mbs0 = mbs;
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws MBeanRegistrationException,
RuntimeOperationsException {
try {
mbs0.unregisterMBean(objName);
} catch (InstanceNotFoundException e) {
// ignore exception if not found
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw Util.newException(e.getException());
}
}
static void unregisterInternalMBeans(MBeanServer mbs) {
// unregister all internal MBeans
unregisterMBean(mbs, HOTSPOT_CLASS_LOADING_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_MEMORY_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_RUNTIME_MBEAN_NAME);
unregisterMBean(mbs, HOTSPOT_THREAD_MBEAN_NAME);
// CompilationMBean may not exist
if (getCompilationMXBean() != null) {
unregisterMBean(mbs, HOTSPOT_COMPILATION_MBEAN_NAME);
}
}
static {
AccessController.doPrivileged(new LoadLibraryAction("management"));
jvm = new VMManagementImpl();
}
public static boolean isThreadSuspended(int state) {
return ((state & JMM_THREAD_STATE_FLAG_SUSPENDED) != 0);
}
public static boolean isThreadRunningNative(int state) {
return ((state & JMM_THREAD_STATE_FLAG_NATIVE) != 0);
}
public static Thread.State toThreadState(int state) {
// suspended and native bits may be set in state
int threadStatus = state & ~JMM_THREAD_STATE_FLAG_MASK;
return sun.misc.VM.toThreadState(threadStatus);
}
// These values are defined in jmm.h
private static final int JMM_THREAD_STATE_FLAG_MASK = 0xFFF00000;
private static final int JMM_THREAD_STATE_FLAG_SUSPENDED = 0x00100000;
private static final int JMM_THREAD_STATE_FLAG_NATIVE = 0x00400000;
}
...@@ -735,14 +735,14 @@ public abstract class MappedMXBeanType { ...@@ -735,14 +735,14 @@ public abstract class MappedMXBeanType {
throws OpenDataException, InvalidObjectException { throws OpenDataException, InvalidObjectException {
if (fromMethod == null) { if (fromMethod == null) {
throw new InternalError("Does not support data conversion"); throw new AssertionError("Does not support data conversion");
} }
try { try {
return fromMethod.invoke(null, data); return fromMethod.invoke(null, data);
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
// should never reach here // should never reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
final OpenDataException ode = final OpenDataException ode =
new OpenDataException("Failed to invoke " + new OpenDataException("Failed to invoke " +
...@@ -785,7 +785,7 @@ public abstract class MappedMXBeanType { ...@@ -785,7 +785,7 @@ public abstract class MappedMXBeanType {
t = new InProgress(); t = new InProgress();
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should not reach here // Should not reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
inProgress = t; inProgress = t;
} }
...@@ -807,9 +807,9 @@ public abstract class MappedMXBeanType { ...@@ -807,9 +807,9 @@ public abstract class MappedMXBeanType {
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
// the classes that these predefined types declare // the classes that these predefined types declare
// must exist! // must exist!
throw Util.newAssertionError(e); throw new AssertionError(e);
} catch (OpenDataException e) { } catch (OpenDataException e) {
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
if (c.getName().startsWith("java.lang.")) { if (c.getName().startsWith("java.lang.")) {
...@@ -821,12 +821,12 @@ public abstract class MappedMXBeanType { ...@@ -821,12 +821,12 @@ public abstract class MappedMXBeanType {
// OK: must not be a primitive wrapper // OK: must not be a primitive wrapper
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
// Should not reach here // Should not reach here
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
} }
} }
} catch (OpenDataException e) { } catch (OpenDataException e) {
throw Util.newAssertionError(e); throw new AssertionError(e);
} }
} }
......
...@@ -25,13 +25,13 @@ ...@@ -25,13 +25,13 @@
package sun.management; package sun.management;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean; import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage; import java.lang.management.MemoryUsage;
import java.lang.management.MemoryNotificationInfo; import java.lang.management.MemoryNotificationInfo;
import java.lang.management.MemoryManagerMXBean; import java.lang.management.MemoryManagerMXBean;
import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryPoolMXBean;
import javax.management.ObjectName; import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;
import javax.management.MBeanNotificationInfo; import javax.management.MBeanNotificationInfo;
import javax.management.Notification; import javax.management.Notification;
import javax.management.NotificationEmitter; import javax.management.NotificationEmitter;
...@@ -88,7 +88,7 @@ class MemoryImpl extends NotificationEmitterSupport ...@@ -88,7 +88,7 @@ class MemoryImpl extends NotificationEmitterSupport
} }
public void setVerbose(boolean value) { public void setVerbose(boolean value) {
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
setVerboseGC(value); setVerboseGC(value);
} }
...@@ -150,19 +150,6 @@ class MemoryImpl extends NotificationEmitterSupport ...@@ -150,19 +150,6 @@ class MemoryImpl extends NotificationEmitterSupport
return ++seqNumber; return ++seqNumber;
} }
private static ObjectName objname = null;
private static synchronized ObjectName getObjectName() {
if (objname != null) return objname;
try {
objname = new ObjectName(java.lang.management.ManagementFactory.MEMORY_MXBEAN_NAME);
} catch (MalformedObjectNameException e) {
// should never reach here
throw Util.newInternalError(e);
}
return objname;
}
static void createNotification(String notifType, static void createNotification(String notifType,
String poolName, String poolName,
MemoryUsage usage, MemoryUsage usage,
...@@ -175,7 +162,7 @@ class MemoryImpl extends NotificationEmitterSupport ...@@ -175,7 +162,7 @@ class MemoryImpl extends NotificationEmitterSupport
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
String msg = getNotifMsg(notifType); String msg = getNotifMsg(notifType);
Notification notif = new Notification(notifType, Notification notif = new Notification(notifType,
getObjectName(), mbean.getObjectName(),
getNextSeqNumber(), getNextSeqNumber(),
timestamp, timestamp,
msg); msg);
...@@ -189,4 +176,8 @@ class MemoryImpl extends NotificationEmitterSupport ...@@ -189,4 +176,8 @@ class MemoryImpl extends NotificationEmitterSupport
mbean.sendNotification(notif); mbean.sendNotification(notif);
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.MEMORY_MXBEAN_NAME);
}
} }
...@@ -25,9 +25,12 @@ ...@@ -25,9 +25,12 @@
package sun.management; package sun.management;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryManagerMXBean; import java.lang.management.MemoryManagerMXBean;
import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryPoolMXBean;
import javax.management.ObjectName;
/** /**
* Implementation class for a memory manager. * Implementation class for a memory manager.
* Standard and committed hotspot-specific metrics if any. * Standard and committed hotspot-specific metrics if any.
...@@ -73,4 +76,8 @@ class MemoryManagerImpl implements MemoryManagerMXBean { ...@@ -73,4 +76,8 @@ class MemoryManagerImpl implements MemoryManagerMXBean {
} }
private native MemoryPoolMXBean[] getMemoryPools0(); private native MemoryPoolMXBean[] getMemoryPools0();
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE, getName());
}
} }
...@@ -69,7 +69,7 @@ public class MemoryNotifInfoCompositeData extends LazyCompositeData { ...@@ -69,7 +69,7 @@ public class MemoryNotifInfoCompositeData extends LazyCompositeData {
memoryNotifInfoItemValues); memoryNotifInfoItemValues);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -80,7 +80,7 @@ public class MemoryNotifInfoCompositeData extends LazyCompositeData { ...@@ -80,7 +80,7 @@ public class MemoryNotifInfoCompositeData extends LazyCompositeData {
MappedMXBeanType.toOpenType(MemoryNotificationInfo.class); MappedMXBeanType.toOpenType(MemoryNotificationInfo.class);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
......
...@@ -25,12 +25,13 @@ ...@@ -25,12 +25,13 @@
package sun.management; package sun.management;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage; import java.lang.management.MemoryUsage;
import java.lang.management.MemoryType; import java.lang.management.MemoryType;
import java.lang.management.MemoryManagerMXBean; import java.lang.management.MemoryManagerMXBean;
import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeData;
import javax.management.ObjectName;
import static java.lang.management.MemoryNotificationInfo.*; import static java.lang.management.MemoryNotificationInfo.*;
...@@ -114,7 +115,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean { ...@@ -114,7 +115,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean {
"Usage threshold is not supported"); "Usage threshold is not supported");
} }
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
MemoryUsage usage = getUsage0(); MemoryUsage usage = getUsage0();
if (newThreshold < 0) { if (newThreshold < 0) {
...@@ -159,7 +160,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean { ...@@ -159,7 +160,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean {
} }
public void resetPeakUsage() { public void resetPeakUsage() {
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
synchronized (this) { synchronized (this) {
// synchronized since getPeakUsage may be called concurrently // synchronized since getPeakUsage may be called concurrently
...@@ -211,7 +212,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean { ...@@ -211,7 +212,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean {
"CollectionUsage threshold is not supported"); "CollectionUsage threshold is not supported");
} }
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
MemoryUsage usage = getUsage0(); MemoryUsage usage = getUsage0();
if (newThreshold < 0) { if (newThreshold < 0) {
...@@ -304,7 +305,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean { ...@@ -304,7 +305,7 @@ class MemoryPoolImpl implements MemoryPoolMXBean {
} }
void triggerAction() { void triggerAction() {
// Should not reach here // Should not reach here
throw new InternalError(); throw new AssertionError("Should not reach here");
} }
void clearAction() { void clearAction() {
// do nothing // do nothing
...@@ -332,10 +333,15 @@ class MemoryPoolImpl implements MemoryPoolMXBean { ...@@ -332,10 +333,15 @@ class MemoryPoolImpl implements MemoryPoolMXBean {
} }
void triggerAction() { void triggerAction() {
// Should not reach here // Should not reach here
throw new InternalError(); throw new AssertionError("Should not reach here");
} }
void clearAction() { void clearAction() {
// do nothing // do nothing
} }
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.MEMORY_POOL_MXBEAN_DOMAIN_TYPE, getName());
}
} }
...@@ -68,7 +68,7 @@ public class MemoryUsageCompositeData extends LazyCompositeData { ...@@ -68,7 +68,7 @@ public class MemoryUsageCompositeData extends LazyCompositeData {
memoryUsageItemValues); memoryUsageItemValues);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -79,7 +79,7 @@ public class MemoryUsageCompositeData extends LazyCompositeData { ...@@ -79,7 +79,7 @@ public class MemoryUsageCompositeData extends LazyCompositeData {
MappedMXBeanType.toOpenType(MemoryUsage.class); MappedMXBeanType.toOpenType(MemoryUsage.class);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
......
...@@ -81,7 +81,7 @@ public class MonitorInfoCompositeData extends LazyCompositeData { ...@@ -81,7 +81,7 @@ public class MonitorInfoCompositeData extends LazyCompositeData {
values); values);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -95,7 +95,7 @@ public class MonitorInfoCompositeData extends LazyCompositeData { ...@@ -95,7 +95,7 @@ public class MonitorInfoCompositeData extends LazyCompositeData {
monitorInfoItemNames = (String[]) s.toArray(new String[0]); monitorInfoItemNames = (String[]) s.toArray(new String[0]);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
......
...@@ -156,7 +156,7 @@ abstract class NotificationEmitterSupport implements NotificationEmitter { ...@@ -156,7 +156,7 @@ abstract class NotificationEmitterSupport implements NotificationEmitter {
li.listener.handleNotification(notification, li.handback); li.listener.handleNotification(notification, li.handback);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new InternalError("Error in invoking listener"); throw new AssertionError("Error in invoking listener");
} }
} }
} }
......
...@@ -26,6 +26,8 @@ ...@@ -26,6 +26,8 @@
package sun.management; package sun.management;
import java.lang.management.OperatingSystemMXBean; import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
import sun.misc.Unsafe; import sun.misc.Unsafe;
/** /**
...@@ -71,4 +73,9 @@ public class OperatingSystemImpl implements OperatingSystemMXBean { ...@@ -71,4 +73,9 @@ public class OperatingSystemImpl implements OperatingSystemMXBean {
return -1.0; return -1.0;
} }
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
}
} }
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package sun.management; package sun.management;
import java.lang.management.RuntimeMXBean; import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
import java.util.List; import java.util.List;
import java.util.HashMap; import java.util.HashMap;
...@@ -38,6 +39,7 @@ import javax.management.openmbean.CompositeType; ...@@ -38,6 +39,7 @@ import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType; import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType; import javax.management.openmbean.SimpleType;
import javax.management.openmbean.OpenDataException; import javax.management.openmbean.OpenDataException;
import javax.management.ObjectName;
/** /**
* Implementation class for the runtime subsystem. * Implementation class for the runtime subsystem.
...@@ -104,12 +106,12 @@ class RuntimeImpl implements RuntimeMXBean { ...@@ -104,12 +106,12 @@ class RuntimeImpl implements RuntimeMXBean {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Boot class path mechanism is not supported"); "Boot class path mechanism is not supported");
} }
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
return jvm.getBootClassPath(); return jvm.getBootClassPath();
} }
public List<String> getInputArguments() { public List<String> getInputArguments() {
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
return jvm.getVmArguments(); return jvm.getVmArguments();
} }
...@@ -145,4 +147,9 @@ class RuntimeImpl implements RuntimeMXBean { ...@@ -145,4 +147,9 @@ class RuntimeImpl implements RuntimeMXBean {
return map; return map;
} }
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
}
} }
...@@ -76,7 +76,7 @@ public class StackTraceElementCompositeData extends LazyCompositeData { ...@@ -76,7 +76,7 @@ public class StackTraceElementCompositeData extends LazyCompositeData {
stackTraceElementItemValues); stackTraceElementItemValues);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -87,7 +87,7 @@ public class StackTraceElementCompositeData extends LazyCompositeData { ...@@ -87,7 +87,7 @@ public class StackTraceElementCompositeData extends LazyCompositeData {
MappedMXBeanType.toOpenType(StackTraceElement.class); MappedMXBeanType.toOpenType(StackTraceElement.class);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
......
...@@ -26,6 +26,7 @@ ...@@ -26,6 +26,7 @@
package sun.management; package sun.management;
import java.lang.management.ThreadMXBean; import java.lang.management.ThreadMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo; import java.lang.management.ThreadInfo;
import java.lang.management.LockInfo; import java.lang.management.LockInfo;
...@@ -33,6 +34,8 @@ import java.lang.management.MonitorInfo; ...@@ -33,6 +34,8 @@ import java.lang.management.MonitorInfo;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import javax.management.ObjectName;
/** /**
* Implementation class for the thread subsystem. * Implementation class for the thread subsystem.
* Standard and committed hotspot-specific metrics if any. * Standard and committed hotspot-specific metrics if any.
...@@ -102,7 +105,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -102,7 +105,7 @@ class ThreadImpl implements ThreadMXBean {
} }
public long[] getAllThreadIds() { public long[] getAllThreadIds() {
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
Thread[] threads = getThreads(); Thread[] threads = getThreads();
int length = threads.length; int length = threads.length;
...@@ -156,7 +159,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -156,7 +159,7 @@ class ThreadImpl implements ThreadMXBean {
"Invalid maxDepth parameter: " + maxDepth); "Invalid maxDepth parameter: " + maxDepth);
} }
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
ThreadInfo[] infos = new ThreadInfo[ids.length]; ThreadInfo[] infos = new ThreadInfo[ids.length];
if (maxDepth == Integer.MAX_VALUE) { if (maxDepth == Integer.MAX_VALUE) {
...@@ -175,7 +178,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -175,7 +178,7 @@ class ThreadImpl implements ThreadMXBean {
"Thread contention monitoring is not supported"); "Thread contention monitoring is not supported");
} }
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
synchronized (this) { synchronized (this) {
if (contentionMonitoringEnabled != enable) { if (contentionMonitoringEnabled != enable) {
...@@ -297,7 +300,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -297,7 +300,7 @@ class ThreadImpl implements ThreadMXBean {
"Thread CPU time measurement is not supported"); "Thread CPU time measurement is not supported");
} }
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
synchronized (this) { synchronized (this) {
if (cpuTimeEnabled != enable) { if (cpuTimeEnabled != enable) {
// update VM of the state change // update VM of the state change
...@@ -308,7 +311,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -308,7 +311,7 @@ class ThreadImpl implements ThreadMXBean {
} }
public long[] findMonitorDeadlockedThreads() { public long[] findMonitorDeadlockedThreads() {
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
Thread[] threads = findMonitorDeadlockedThreads0(); Thread[] threads = findMonitorDeadlockedThreads0();
if (threads == null) { if (threads == null) {
...@@ -329,7 +332,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -329,7 +332,7 @@ class ThreadImpl implements ThreadMXBean {
"Monitoring of Synchronizer Usage is not supported."); "Monitoring of Synchronizer Usage is not supported.");
} }
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
Thread[] threads = findDeadlockedThreads0(); Thread[] threads = findDeadlockedThreads0();
if (threads == null) { if (threads == null) {
...@@ -345,7 +348,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -345,7 +348,7 @@ class ThreadImpl implements ThreadMXBean {
} }
public void resetPeakThreadCount() { public void resetPeakThreadCount() {
ManagementFactory.checkControlAccess(); Util.checkControlAccess();
resetPeakThreadCount0(); resetPeakThreadCount0();
} }
...@@ -373,7 +376,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -373,7 +376,7 @@ class ThreadImpl implements ThreadMXBean {
"Monitoring of Synchronizer Usage is not supported."); "Monitoring of Synchronizer Usage is not supported.");
} }
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
return dumpThreads0(ids, lockedMonitors, lockedSynchronizers); return dumpThreads0(ids, lockedMonitors, lockedSynchronizers);
} }
...@@ -388,7 +391,7 @@ class ThreadImpl implements ThreadMXBean { ...@@ -388,7 +391,7 @@ class ThreadImpl implements ThreadMXBean {
"Monitoring of Synchronizer Usage is not supported."); "Monitoring of Synchronizer Usage is not supported.");
} }
ManagementFactory.checkMonitorAccess(); Util.checkMonitorAccess();
return dumpThreads0(null, lockedMonitors, lockedSynchronizers); return dumpThreads0(null, lockedMonitors, lockedSynchronizers);
} }
...@@ -410,4 +413,10 @@ class ThreadImpl implements ThreadMXBean { ...@@ -410,4 +413,10 @@ class ThreadImpl implements ThreadMXBean {
// tid == 0 to reset contention times for all threads // tid == 0 to reset contention times for all threads
private static native void resetContentionTimes0(long tid); private static native void resetContentionTimes0(long tid);
public ObjectName getObjectName() {
return Util.newObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
}
} }
...@@ -126,7 +126,7 @@ public class ThreadInfoCompositeData extends LazyCompositeData { ...@@ -126,7 +126,7 @@ public class ThreadInfoCompositeData extends LazyCompositeData {
threadInfoItemValues); threadInfoItemValues);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -209,7 +209,7 @@ public class ThreadInfoCompositeData extends LazyCompositeData { ...@@ -209,7 +209,7 @@ public class ThreadInfoCompositeData extends LazyCompositeData {
v5ItemTypes); v5ItemTypes);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
// Each CompositeData object has its CompositeType associated // Each CompositeData object has its CompositeType associated
......
...@@ -26,48 +26,58 @@ ...@@ -26,48 +26,58 @@
package sun.management; package sun.management;
import java.lang.management.*; import java.lang.management.*;
import static java.lang.management.ManagementFactory.*;
import java.util.List; import java.util.List;
import java.security.Permission;
import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;
import static java.lang.management.ManagementFactory.*;
class Util { class Util {
static String getMBeanObjectName(MemoryPoolMXBean pool) { static RuntimeException newException(Exception e) {
return MEMORY_POOL_MXBEAN_DOMAIN_TYPE + throw new RuntimeException(e);
",name=" + pool.getName();
} }
static String getMBeanObjectName(MemoryManagerMXBean mgr) { private static final String[] EMPTY_STRING_ARRAY = new String[0];
if (mgr instanceof GarbageCollectorMXBean) { static String[] toStringArray(List<String> list) {
return getMBeanObjectName((GarbageCollectorMXBean) mgr); return (String[]) list.toArray(EMPTY_STRING_ARRAY);
} else {
return MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE +
",name=" + mgr.getName();
}
} }
static String getMBeanObjectName(GarbageCollectorMXBean gc) { static ObjectName newObjectName(String name) {
return GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE + return com.sun.jmx.mbeanserver.Util.newObjectName(name);
",name=" + gc.getName();
} }
static RuntimeException newException(Exception e) { public static ObjectName newObjectName(String domainAndType, String name) {
RuntimeException e1 = new RuntimeException(e.getMessage()); return newObjectName(domainAndType + ",name=" + name);
e1.initCause(e);
return e1;
} }
static InternalError newInternalError(Exception e) { private static ManagementPermission monitorPermission =
InternalError e1 = new InternalError(e.getMessage()); new ManagementPermission("monitor");
e1.initCause(e); private static ManagementPermission controlPermission =
return e1; new ManagementPermission("control");
/**
* Check that the current context is trusted to perform monitoring
* or management.
* <p>
* If the check fails we throw a SecurityException, otherwise
* we return normally.
*
* @exception SecurityException if a security manager exists and if
* the caller does not have ManagementPermission("control").
*/
static void checkAccess(ManagementPermission p)
throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(p);
} }
static AssertionError newAssertionError(Exception e) {
AssertionError e1 = new AssertionError(e.getMessage());
e1.initCause(e);
return e1;
} }
private static String[] EMPTY_STRING_ARRAY = new String[0]; static void checkMonitorAccess() throws SecurityException {
static String[] toStringArray(List<String> list) { checkAccess(monitorPermission);
return (String[]) list.toArray(EMPTY_STRING_ARRAY); }
static void checkControlAccess() throws SecurityException {
checkAccess(controlPermission);
} }
} }
...@@ -59,7 +59,7 @@ class VMManagementImpl implements VMManagement { ...@@ -59,7 +59,7 @@ class VMManagementImpl implements VMManagement {
static { static {
version = getVersion0(); version = getVersion0();
if (version == null) { if (version == null) {
throw new InternalError("Invalid Management Version"); throw new AssertionError("Invalid Management Version");
} }
initOptionalSupportFields(); initOptionalSupportFields();
} }
...@@ -244,7 +244,7 @@ class VMManagementImpl implements VMManagement { ...@@ -244,7 +244,7 @@ class VMManagementImpl implements VMManagement {
// was set // was set
noPerfData = true; noPerfData = true;
} catch (IOException e) { } catch (IOException e) {
throw new InternalError(e.getMessage()); throw new AssertionError(e);
} }
return perfInstr; return perfInstr;
} }
......
...@@ -69,7 +69,7 @@ public class VMOptionCompositeData extends LazyCompositeData { ...@@ -69,7 +69,7 @@ public class VMOptionCompositeData extends LazyCompositeData {
vmOptionItemValues); vmOptionItemValues);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
...@@ -80,7 +80,7 @@ public class VMOptionCompositeData extends LazyCompositeData { ...@@ -80,7 +80,7 @@ public class VMOptionCompositeData extends LazyCompositeData {
MappedMXBeanType.toOpenType(VMOption.class); MappedMXBeanType.toOpenType(VMOption.class);
} catch (OpenDataException e) { } catch (OpenDataException e) {
// Should never reach here // Should never reach here
throw Util.newInternalError(e); throw new AssertionError(e);
} }
} }
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.nio.cs;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
import java.security.*;
public class CharsetMapping {
public final static char UNMAPPABLE_DECODING = '\uFFFD';
public final static int UNMAPPABLE_ENCODING = -1;
char[] b2cSB; //singlebyte b->c
char[] b2cDB1; //dobulebyte b->c /db1
char[] b2cDB2; //dobulebyte b->c /db2
int b2Min, b2Max; //min/max(start/end) value of 2nd byte
int b1MinDB1, b1MaxDB1; //min/Max(start/end) value of 1st byte/db1
int b1MinDB2, b1MaxDB2; //min/Max(start/end) value of 1st byte/db2
int dbSegSize;
char[] c2b;
char[] c2bIndex;
// Supplementary
char[] b2cSupp;
char[] c2bSupp;
// Composite
Entry[] b2cComp;
Entry[] c2bComp;
public char decodeSingle(int b) {
return b2cSB[b];
}
public char decodeDouble(int b1, int b2) {
if (b2 >= b2Min && b2 < b2Max) {
b2 -= b2Min;
if (b1 >= b1MinDB1 && b1 <= b1MaxDB1) {
b1 -= b1MinDB1;
return b2cDB1[b1 * dbSegSize + b2];
}
if (b1 >= b1MinDB2 && b1 <= b1MaxDB2) {
b1 -= b1MinDB2;
return b2cDB2[b1 * dbSegSize + b2];
}
}
return UNMAPPABLE_DECODING;
}
// for jis0213 all supplementary characters are in 0x2xxxx range,
// so only the xxxx part is now stored, should actually store the
// codepoint value instead.
public char[] decodeSurrogate(int db, char[] cc) {
int end = b2cSupp.length / 2;
int i = Arrays.binarySearch(b2cSupp, 0, end, (char)db);
if (i >= 0) {
Character.toChars(b2cSupp[end + i] + 0x20000, cc, 0);
return cc;
}
return null;
}
public char[] decodeComposite(Entry comp, char[] cc) {
int i = findBytes(b2cComp, comp);
if (i >= 0) {
cc[0] = (char)b2cComp[i].cp;
cc[1] = (char)b2cComp[i].cp2;
return cc;
}
return null;
}
public int encodeChar(char ch) {
int index = c2bIndex[ch >> 8];
if (index == 0xffff)
return UNMAPPABLE_ENCODING;
return c2b[index + (ch & 0xff)];
}
public int encodeSurrogate(char hi, char lo) {
char c = (char)Character.toCodePoint(hi, lo);
int end = c2bSupp.length / 2;
int i = Arrays.binarySearch(c2bSupp, 0, end, c);
if (i >= 0)
return c2bSupp[end + i];
return UNMAPPABLE_ENCODING;
}
public boolean isCompositeBase(Entry comp) {
if (comp.cp <= 0x31f7 && comp.cp >= 0xe6) {
return (findCP(c2bComp, comp) >= 0);
}
return false;
}
public int encodeComposite(Entry comp) {
int i = findComp(c2bComp, comp);
if (i >= 0)
return c2bComp[i].bs;
return UNMAPPABLE_ENCODING;
}
// init the CharsetMapping object from the .dat binary file
public static CharsetMapping get(final InputStream is) {
return AccessController.doPrivileged(new PrivilegedAction<CharsetMapping>() {
public CharsetMapping run() {
return new CharsetMapping().load(is);
}
});
}
public static class Entry {
public int bs; //byte sequence reps
public int cp; //Unicode codepoint
public int cp2; //CC of composite
}
static Comparator<Entry> comparatorBytes =
new Comparator<Entry>() {
public int compare(Entry m1, Entry m2) {
return m1.bs - m2.bs;
}
public boolean equals(Object obj) {
return this == obj;
}
};
static Comparator<Entry> comparatorCP =
new Comparator<Entry>() {
public int compare(Entry m1, Entry m2) {
return m1.cp - m2.cp;
}
public boolean equals(Object obj) {
return this == obj;
}
};
static Comparator<Entry> comparatorComp =
new Comparator<Entry>() {
public int compare(Entry m1, Entry m2) {
int v = m1.cp - m2.cp;
if (v == 0)
v = m1.cp2 - m2.cp2;
return v;
}
public boolean equals(Object obj) {
return this == obj;
}
};
static int findBytes(Entry[] a, Entry k) {
return Arrays.binarySearch(a, 0, a.length, k, comparatorBytes);
}
static int findCP(Entry[] a, Entry k) {
return Arrays.binarySearch(a, 0, a.length, k, comparatorCP);
}
static int findComp(Entry[] a, Entry k) {
return Arrays.binarySearch(a, 0, a.length, k, comparatorComp);
}
/*****************************************************************************/
// tags of different charset mapping tables
private final static int MAP_SINGLEBYTE = 0x1; // 0..256 : c
private final static int MAP_DOUBLEBYTE1 = 0x2; // min..max: c
private final static int MAP_DOUBLEBYTE2 = 0x3; // min..max: c [DB2]
private final static int MAP_SUPPLEMENT = 0x5; // db,c
private final static int MAP_SUPPLEMENT_C2B = 0x6; // c,db
private final static int MAP_COMPOSITE = 0x7; // db,base,cc
private final static int MAP_INDEXC2B = 0x8; // index table of c->bb
private static final boolean readNBytes(InputStream in, byte[] bb, int N)
throws IOException
{
int off = 0;
while (N > 0) {
int n = in.read(bb, off, N);
if (n == -1)
return false;
N = N - n;
off += n;
}
return true;
}
int off = 0;
byte[] bb;
private char[] readCharArray() {
// first 2 bytes are the number of "chars" stored in this table
int size = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
char [] cc = new char[size];
for (int i = 0; i < size; i++) {
cc[i] = (char)(((bb[off++]&0xff)<<8) | (bb[off++]&0xff));
}
return cc;
}
void readSINGLEBYTE() {
char[] map = readCharArray();
for (int i = 0; i < map.length; i++) {
char c = map[i];
if (c != UNMAPPABLE_DECODING) {
c2b[c2bIndex[c >> 8] + (c&0xff)] = (char)i;
}
}
b2cSB = map;
}
void readINDEXC2B() {
char[] map = readCharArray();
for (int i = map.length - 1; i >= 0; i--) {
if (c2b == null && map[i] != -1) {
c2b = new char[map[i] + 256];
Arrays.fill(c2b, (char)UNMAPPABLE_ENCODING);
break;
}
}
c2bIndex = map;
}
char[] readDB(int b1Min, int b2Min, int segSize) {
char[] map = readCharArray();
for (int i = 0; i < map.length; i++) {
char c = map[i];
if (c != UNMAPPABLE_DECODING) {
int b1 = i / segSize;
int b2 = i % segSize;
int b = (b1 + b1Min)* 256 + (b2 + b2Min);
//System.out.printf(" DB %x\t%x%n", b, c & 0xffff);
c2b[c2bIndex[c >> 8] + (c&0xff)] = (char)(b);
}
}
return map;
}
void readDOUBLEBYTE1() {
b1MinDB1 = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b1MaxDB1 = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b2Min = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b2Max = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
dbSegSize = b2Max - b2Min + 1;
b2cDB1 = readDB(b1MinDB1, b2Min, dbSegSize);
}
void readDOUBLEBYTE2() {
b1MinDB2 = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b1MaxDB2 = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b2Min = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
b2Max = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
dbSegSize = b2Max - b2Min + 1;
b2cDB2 = readDB(b1MinDB2, b2Min, dbSegSize);
}
void readCOMPOSITE() {
char[] map = readCharArray();
int mLen = map.length/3;
b2cComp = new Entry[mLen];
c2bComp = new Entry[mLen];
for (int i = 0, j= 0; i < mLen; i++) {
Entry m = new Entry();
m.bs = map[j++];
m.cp = map[j++];
m.cp2 = map[j++];
b2cComp[i] = m;
c2bComp[i] = m;
}
Arrays.sort(c2bComp, 0, c2bComp.length, comparatorComp);
}
CharsetMapping load(InputStream in) {
try {
// The first 4 bytes are the size of the total data followed in
// this .dat file.
int len = ((in.read()&0xff) << 24) | ((in.read()&0xff) << 16) |
((in.read()&0xff) << 8) | (in.read()&0xff);
bb = new byte[len];
off = 0;
//System.out.printf("In : Total=%d%n", len);
// Read in all bytes
if (!readNBytes(in, bb, len))
throw new RuntimeException("Corrupted data file");
in.close();
while (off < len) {
int type = ((bb[off++]&0xff)<<8) | (bb[off++]&0xff);
switch(type) {
case MAP_INDEXC2B:
readINDEXC2B();
break;
case MAP_SINGLEBYTE:
readSINGLEBYTE();
break;
case MAP_DOUBLEBYTE1:
readDOUBLEBYTE1();
break;
case MAP_DOUBLEBYTE2:
readDOUBLEBYTE2();
break;
case MAP_SUPPLEMENT:
b2cSupp = readCharArray();
break;
case MAP_SUPPLEMENT_C2B:
c2bSupp = readCharArray();
break;
case MAP_COMPOSITE:
readCOMPOSITE();
break;
default:
throw new RuntimeException("Corrupted data file");
}
}
bb = null;
return this;
} catch (IOException x) {
x.printStackTrace();
return null;
}
}
}
...@@ -23,9 +23,6 @@ ...@@ -23,9 +23,6 @@
* have any questions. * have any questions.
*/ */
/*
*/
package sun.nio.cs.ext; package sun.nio.cs.ext;
import java.lang.ref.SoftReference; import java.lang.ref.SoftReference;
...@@ -183,6 +180,25 @@ public class ExtendedCharsets ...@@ -183,6 +180,25 @@ public class ExtendedCharsets
"csISO159JISX02121990" "csISO159JISX02121990"
}); });
charset("x-SJIS_0213", "SJIS_0213",
new String[] {
"sjis-0213",
"sjis_0213",
"sjis:2004",
"sjis_0213:2004",
"shift_jis_0213:2004",
"shift_jis:2004"
});
charset("x-MS932_0213", "MS932_0213",
new String[] {
"MS932-0213",
"MS932_0213",
"MS932:2004",
"windows-932-0213",
"windows-932:2004"
});
charset("EUC-JP", "EUC_JP", charset("EUC-JP", "EUC_JP",
new String[] { new String[] {
"euc_jp", // JDK historical "euc_jp", // JDK historical
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.nio.cs.ext;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
public class MS932_0213 extends Charset {
public MS932_0213() {
super("x-MS932_0213", ExtendedCharsets.aliasesFor("MS932_0213"));
}
public boolean contains(Charset cs) {
return ((cs.name().equals("US-ASCII"))
|| (cs instanceof MS932)
|| (cs instanceof MS932_0213));
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public CharsetEncoder newEncoder() {
return new Encoder(this);
}
protected static class Decoder extends SJIS_0213.Decoder {
MS932DB.Decoder decMS932;
protected Decoder(Charset cs) {
super(cs);
decMS932 = new MS932DB.Decoder(cs);
}
protected char decodeDouble(int b1, int b2) {
char c = decMS932.decodeDouble(b1, b2);
if (c == DoubleByteDecoder.REPLACE_CHAR)
return super.decodeDouble(b1, b2);
return c;
}
}
protected static class Encoder extends SJIS_0213.Encoder {
MS932DB.Encoder encMS932;
protected Encoder(Charset cs) {
super(cs);
encMS932 = new MS932DB.Encoder(cs);
}
protected int encodeChar(char ch) {
int db = encMS932.encodeDouble(ch);
if (db == 0)
return super.encodeChar(ch);
return db;
}
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.nio.cs.ext;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.util.Arrays;
import sun.nio.cs.CharsetMapping;
/*
* 5 types of entry in SJIS_X_0213/Unicode mapping table
*
* (1)Single-Byte
* JIS_X_0213 does not define single-byte character itself, the
* JIS_X_0201 entries are added in for sjis implementation.
*
* (2)Double-Byte SJIS <-> BMP Unicode
* ex: 0x8140 U+3000 # IDEOGRAPHIC SPACE
*
* (3)Double-Byte SJIS <-> Supplementary
* ex: 0xFCF0 U+2A61A # <cjk> [2000] [Unicode3.1]
*
* (4)Double-Byte SJIS <-> Composite
* ex: 0x83F6 U+31F7+309A # [2000]
*
* (5)"Windows-only" special mapping entries
* are handled by MS932_0213.
*/
public class SJIS_0213 extends Charset {
public SJIS_0213() {
super("x-SJIS_0213", ExtendedCharsets.aliasesFor("SJIS_0213"));
}
public boolean contains(Charset cs) {
return ((cs.name().equals("US-ASCII"))
|| (cs instanceof SJIS)
|| (cs instanceof SJIS_0213));
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public CharsetEncoder newEncoder() {
return new Encoder(this);
}
static CharsetMapping mapping =
CharsetMapping.get(SJIS_0213.class.getResourceAsStream("sjis0213.dat"));
protected static class Decoder extends CharsetDecoder {
protected static final char UNMAPPABLE = CharsetMapping.UNMAPPABLE_DECODING;
protected Decoder(Charset cs) {
super(cs, 0.5f, 1.0f);
}
private CoderResult decodeArrayLoop(ByteBuffer src, CharBuffer dst) {
byte[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
char[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
try {
while (sp < sl) {
int b1 = sa[sp] & 0xff;
char c = decodeSingle(b1);
int inSize = 1, outSize = 1;
char[] cc = null;
if (c == UNMAPPABLE) {
if (sl - sp < 2)
return CoderResult.UNDERFLOW;
int b2 = sa[sp + 1] & 0xff;
c = decodeDouble(b1, b2);
inSize++;
if (c == UNMAPPABLE) {
cc = decodeDoubleEx(b1, b2);
if (cc == null) {
if (decodeSingle(b2) == UNMAPPABLE)
return CoderResult.unmappableForLength(2);
else
return CoderResult.unmappableForLength(1);
}
outSize++;
}
}
if (dl - dp < outSize)
return CoderResult.OVERFLOW;
if (outSize == 2) {
da[dp++] = cc[0];
da[dp++] = cc[1];
} else {
da[dp++] = c;
}
sp += inSize;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
private CoderResult decodeBufferLoop(ByteBuffer src, CharBuffer dst) {
int mark = src.position();
try {
while (src.hasRemaining()) {
char[] cc = null;
int b1 = src.get() & 0xff;
char c = decodeSingle(b1);
int inSize = 1, outSize = 1;
if (c == UNMAPPABLE) {
if (src.remaining() < 1)
return CoderResult.UNDERFLOW;
int b2 = src.get() & 0xff;
inSize++;
c = decodeDouble(b1, b2);
if (c == UNMAPPABLE) {
cc = decodeDoubleEx(b1, b2);
if (cc == null) {
if (decodeSingle(b2) == UNMAPPABLE)
return CoderResult.unmappableForLength(2);
else
return CoderResult.unmappableForLength(1);
}
outSize++;
}
}
if (dst.remaining() < outSize)
return CoderResult.OVERFLOW;
if (outSize == 2) {
dst.put(cc[0]);
dst.put(cc[1]);
} else {
dst.put(c);
}
mark += inSize;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(mark);
}
}
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
if (src.hasArray() && dst.hasArray())
return decodeArrayLoop(src, dst);
else
return decodeBufferLoop(src, dst);
}
protected char decodeSingle(int b) {
return mapping.decodeSingle(b);
}
protected char decodeDouble(int b1, int b2) {
return mapping.decodeDouble(b1, b2);
}
private char[] cc = new char[2];
private CharsetMapping.Entry comp = new CharsetMapping.Entry();
protected char[] decodeDoubleEx(int b1, int b2) {
int db = (b1 << 8) | b2;
if (mapping.decodeSurrogate(db, cc) != null)
return cc;
comp.bs = db;
if (mapping.decodeComposite(comp, cc) != null)
return cc;
return null;
}
}
protected static class Encoder extends CharsetEncoder {
protected static final int UNMAPPABLE = CharsetMapping.UNMAPPABLE_ENCODING;
protected static final int MAX_SINGLEBYTE = 0xff;
protected Encoder(Charset cs) {
super(cs, 2.0f, 2.0f);
}
public boolean canEncode(char c) {
return (encodeChar(c) != UNMAPPABLE);
}
protected int encodeChar(char ch) {
return mapping.encodeChar(ch);
}
protected int encodeSurrogate(char hi, char lo) {
return mapping.encodeSurrogate(hi, lo);
}
private CharsetMapping.Entry comp = new CharsetMapping.Entry();
protected int encodeComposite(char base, char cc) {
comp.cp = base;
comp.cp2 = cc;
return mapping.encodeComposite(comp);
}
protected boolean isCompositeBase(char ch) {
comp.cp = ch;
return mapping.isCompositeBase(comp);
}
// Unlike surrogate pair, the base character of a base+cc composite
// itself is a legal codepoint in 0213, if we simply return UNDERFLOW
// when a base candidate is the last input char in the CharBuffer, like
// what we do for the surrogte pair, encoding will fail if this base
// character is indeed the last character of the input char sequence.
// Keep this base candidate in "leftoverBase" so we can flush it out
// at the end of the encoding circle.
char leftoverBase = 0;
protected CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
char[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
byte[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
try {
while (sp < sl) {
int db;
char c = sa[sp];
if (leftoverBase != 0) {
boolean isComp = false;
db = encodeComposite(leftoverBase, c);
if (db == UNMAPPABLE)
db = encodeChar(leftoverBase);
else
isComp = true;
if (dl - dp < 2)
return CoderResult.OVERFLOW;
da[dp++] = (byte)(db >> 8);
da[dp++] = (byte)db;
leftoverBase = 0;
if (isComp) {
sp++;
continue;
}
}
if (isCompositeBase(c)) {
leftoverBase = c;
} else {
db = encodeChar(c);
if (db > MAX_SINGLEBYTE) { // DoubleByte
if (dl - dp < 2)
return CoderResult.OVERFLOW;
da[dp++] = (byte)(db >> 8);
da[dp++] = (byte)db;
} else if (db != UNMAPPABLE) { // SingleByte
if (dl <= dp)
return CoderResult.OVERFLOW;
da[dp++] = (byte)db;
} else if (Character.isHighSurrogate(c)) {
if ((sp + 1) == sl)
return CoderResult.UNDERFLOW;
char c2 = sa[sp + 1];
if (!Character.isLowSurrogate(c2))
return CoderResult.malformedForLength(1);
db = encodeSurrogate(c, c2);
if (db == UNMAPPABLE)
return CoderResult.unmappableForLength(2);
if (dl - dp < 2)
return CoderResult.OVERFLOW;
da[dp++] = (byte)(db >> 8);
da[dp++] = (byte)db;
sp++;
} else {
return CoderResult.unmappableForLength(1);
}
}
sp++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
protected CoderResult encodeBufferLoop(CharBuffer src, ByteBuffer dst) {
int mark = src.position();
try {
while (src.hasRemaining()) {
int db;
char c = src.get();
if (leftoverBase != 0) {
boolean isComp = false;
db = encodeComposite(leftoverBase, c);
if (db == UNMAPPABLE)
db = encodeChar(leftoverBase);
else
isComp = true;
if (dst.remaining() < 2)
return CoderResult.OVERFLOW;
dst.put((byte)(db >> 8));
dst.put((byte)(db));
leftoverBase = 0;
if (isComp) {
mark++;
continue;
}
}
if (isCompositeBase(c)) {
leftoverBase = c;
} else {
db = encodeChar(c);
if (db > MAX_SINGLEBYTE) { // DoubleByte
if (dst.remaining() < 2)
return CoderResult.OVERFLOW;
dst.put((byte)(db >> 8));
dst.put((byte)(db));
} else if (db != UNMAPPABLE) { // Single-byte
if (dst.remaining() < 1)
return CoderResult.OVERFLOW;
dst.put((byte)db);
} else if (Character.isHighSurrogate(c)) {
if (!src.hasRemaining()) // Surrogates
return CoderResult.UNDERFLOW;
char c2 = src.get();
if (!Character.isLowSurrogate(c2))
return CoderResult.malformedForLength(1);
db = encodeSurrogate(c, c2);
if (db == UNMAPPABLE)
return CoderResult.unmappableForLength(2);
if (dst.remaining() < 2)
return CoderResult.OVERFLOW;
dst.put((byte)(db >> 8));
dst.put((byte)(db));
mark++;
} else {
return CoderResult.unmappableForLength(1);
}
}
mark++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(mark);
}
}
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
if (src.hasArray() && dst.hasArray())
return encodeArrayLoop(src, dst);
else
return encodeBufferLoop(src, dst);
}
protected CoderResult implFlush(ByteBuffer dst) {
if (leftoverBase > 0) {
if (dst.remaining() < 2)
return CoderResult.OVERFLOW;
int db = encodeChar(leftoverBase);
dst.put((byte)(db >> 8));
dst.put((byte)(db));
leftoverBase = 0;
}
return CoderResult.UNDERFLOW;
}
protected void implReset() {
leftoverBase = 0;
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import com.sun.tracing.ProviderFactory;
import com.sun.tracing.Provider;
import com.sun.tracing.Probe;
/**
* Factory class to create tracing Providers.
*
* This factory creates a "multiplex provider", which is a provider that
* encapsulates a list of providers and whose probes trigger a corresponding
* trigger in each of the encapsulated providers' probes.
*
* This is used when there are multiple tracing frameworks activated at once.
* A user-defined provider gets implementation for each of the activated
* frameworks and this multiplex framework is what is ultimately passed
* back to the user. All probe triggers are multiplexed to each
* active framework.
*
* @since 1.7
*/
public class MultiplexProviderFactory extends ProviderFactory {
private Set<ProviderFactory> factories;
public MultiplexProviderFactory(Set<ProviderFactory> factories) {
this.factories = factories;
}
public <T extends Provider> T createProvider(Class<T> cls) {
HashSet<Provider> providers = new HashSet<Provider>();
for (ProviderFactory factory : factories) {
providers.add(factory.createProvider(cls));
}
MultiplexProvider provider = new MultiplexProvider(cls, providers);
try {
provider.init();
} catch (Exception e) {
// Probably a permission problem (can't get declared members)
Logger.getAnonymousLogger().warning(
"Could not initialize tracing provider: " + e.getMessage());
}
return provider.newProxyInstance();
}
}
class MultiplexProvider extends ProviderSkeleton {
private Set<Provider> providers;
protected ProbeSkeleton createProbe(Method m) {
return new MultiplexProbe(m, providers);
}
MultiplexProvider(Class<? extends Provider> type, Set<Provider> providers) {
super(type);
this.providers = providers;
}
public void dispose() {
for (Provider p : providers) {
p.dispose();
}
super.dispose();
}
}
class MultiplexProbe extends ProbeSkeleton {
private Set<Probe> probes;
MultiplexProbe(Method m, Set<Provider> providers) {
super(m.getParameterTypes());
probes = new HashSet<Probe>();
for (Provider p : providers) {
Probe probe = p.getProbe(m);
if (probe != null) {
probes.add(probe);
}
}
}
public boolean isEnabled() {
for (Probe p : probes) {
if (p.isEnabled()) {
return true;
}
}
return false;
}
public void uncheckedTrigger(Object[] args) {
for (Probe p : probes) {
try {
// try the fast path
ProbeSkeleton ps = (ProbeSkeleton)p;
ps.uncheckedTrigger(args);
} catch (ClassCastException e) {
// Probe.trigger takes an "Object ..." varargs parameter,
// so we can't call it directly.
try {
Method m = Probe.class.getMethod(
"trigger", Class.forName("[java.lang.Object"));
m.invoke(p, args);
} catch (Exception e1) {
assert false; // This shouldn't happen
}
}
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing;
import java.lang.reflect.Method;
import java.util.logging.Logger;
import com.sun.tracing.ProviderFactory;
import com.sun.tracing.Provider;
/**
* Factory class to create tracing Providers.
*
* This factory will create tracing instances that do nothing.
* It is used when no tracing is desired, but Provider instances still
* must be generated so that tracing calls in the application continue to
* run.
*
* @since 1.7
*/
public class NullProviderFactory extends ProviderFactory {
/**
* Creates and returns a Null provider.
*
* See comments at {@code ProviderSkeleton.createProvider()} for more
* details.
*
* @return a provider whose probe trigger are no-ops.
*/
public <T extends Provider> T createProvider(Class<T> cls) {
NullProvider provider = new NullProvider(cls);
try {
provider.init();
} catch (Exception e) {
// Probably a permission problem (can't get declared members)
Logger.getAnonymousLogger().warning(
"Could not initialize tracing provider: " + e.getMessage());
}
return provider.newProxyInstance();
}
}
class NullProvider extends ProviderSkeleton {
NullProvider(Class<? extends Provider> type) {
super(type);
}
protected ProbeSkeleton createProbe(Method m) {
return new NullProbe(m.getParameterTypes());
}
}
class NullProbe extends ProbeSkeleton {
public NullProbe(Class<?>[] parameters) {
super(parameters);
}
public boolean isEnabled() {
return false;
}
public void uncheckedTrigger(Object[] args) {
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing;
import java.lang.reflect.Method;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.logging.Logger;
import com.sun.tracing.ProviderFactory;
import com.sun.tracing.Provider;
import com.sun.tracing.ProviderName;
import com.sun.tracing.Probe;
import com.sun.tracing.ProbeName;
/**
* Factory class to create tracing Providers.
*
* This factory will create tracing instances that print to a PrintStream
* when activated.
*
* @since 1.7
*/
public class PrintStreamProviderFactory extends ProviderFactory {
private PrintStream stream;
public PrintStreamProviderFactory(PrintStream stream) {
this.stream = stream;
}
public <T extends Provider> T createProvider(Class<T> cls) {
PrintStreamProvider provider = new PrintStreamProvider(cls, stream);
try {
provider.init();
} catch (Exception e) {
// Probably a permission problem (can't get declared members)
Logger.getAnonymousLogger().warning(
"Could not initialize tracing provider: " + e.getMessage());
}
return provider.newProxyInstance();
}
}
class PrintStreamProvider extends ProviderSkeleton {
private PrintStream stream;
private String providerName;
protected ProbeSkeleton createProbe(Method m) {
String probeName = getAnnotationString(m, ProbeName.class, m.getName());
return new PrintStreamProbe(this, probeName, m.getParameterTypes());
}
PrintStreamProvider(Class<? extends Provider> type, PrintStream stream) {
super(type);
this.stream = stream;
this.providerName = getProviderName();
}
PrintStream getStream() {
return stream;
}
String getName() {
return providerName;
}
}
class PrintStreamProbe extends ProbeSkeleton {
private PrintStreamProvider provider;
private String name;
PrintStreamProbe(PrintStreamProvider p, String name, Class<?>[] params) {
super(params);
this.provider = p;
this.name = name;
}
public boolean isEnabled() {
return true;
}
public void uncheckedTrigger(Object[] args) {
StringBuffer sb = new StringBuffer();
sb.append(provider.getName());
sb.append(".");
sb.append(name);
sb.append("(");
boolean first = true;
for (Object o : args) {
if (first == false) {
sb.append(",");
} else {
first = false;
}
sb.append(o.toString());
}
sb.append(")");
provider.getStream().println(sb.toString());
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import com.sun.tracing.Probe;
/**
* Provides common code for implementation of {@code Probe} classes.
*
* @since 1.7
*/
public abstract class ProbeSkeleton implements Probe {
protected Class<?>[] parameters;
protected ProbeSkeleton(Class<?>[] parameters) {
this.parameters = parameters;
}
public abstract boolean isEnabled(); // framework-dependent
/**
* Triggers the probe with verified arguments.
*
* The caller of this method must have already determined that the
* arity and types of the arguments match what the probe was
* declared with.
*/
public abstract void uncheckedTrigger(Object[] args); // framework-dependent
private static boolean isAssignable(Object o, Class<?> formal) {
if (o != null) {
if ( !formal.isInstance(o) ) {
if ( formal.isPrimitive() ) { // o might be a boxed primitive
try {
// Yuck. There must be a better way of doing this
Field f = o.getClass().getField("TYPE");
return formal.isAssignableFrom((Class<?>)f.get(null));
} catch (Exception e) {
/* fall-through. */
}
}
return false;
}
}
return true;
}
/**
* Performs a type-check of the parameters before triggering the probe.
*/
public void trigger(Object ... args) {
if (args.length != parameters.length) {
throw new IllegalArgumentException("Wrong number of arguments");
} else {
for (int i = 0; i < parameters.length; ++i) {
if ( !isAssignable(args[i], parameters[i]) ) {
throw new IllegalArgumentException(
"Wrong type of argument at position " + i);
}
}
uncheckedTrigger(args);
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.AnnotatedElement;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import com.sun.tracing.Provider;
import com.sun.tracing.Probe;
import com.sun.tracing.ProviderName;
/**
* Provides a common code for implementation of {@code Provider} classes.
*
* Each tracing subsystem needs to provide three classes, a factory
* (derived from {@code ProviderFactory}, a provider (a subclass of
* {@code Provider}, and a probe type (subclass of {@code ProbeSkeleton}).
*
* The factory object takes a user-defined interface and provides an
* implementation of it whose method calls will trigger probes in the
* tracing framework.
*
* The framework's provider class, and its instances, are not seen by the
* user at all -- they usually sit in the background and receive and dispatch
* the calls to the user's provider interface. The {@code ProviderSkeleton}
* class provides almost all of the implementation needed by a framework
* provider. Framework providers must only provide a constructor and
* disposal method, and implement the {@code createProbe} method to create
* an appropriate {@code ProbeSkeleton} subclass.
*
* The framework's probe class provides the implementation of the two
* probe methods, {@code isEnabled()} and {@code uncheckedTrigger()}. Both are
* framework-dependent implementations.
*
* @since 1.7
*/
public abstract class ProviderSkeleton implements InvocationHandler, Provider {
protected boolean active; // set to false after dispose() is called
protected Class<? extends Provider> providerType; // user's interface
protected HashMap<Method, ProbeSkeleton> probes; // methods to probes
/**
* Creates a framework-specific probe subtype.
*
* This method is implemented by the framework's provider and returns
* framework-specific probes for a method.
*
* @param method A method in the user's interface
* @return a subclass of ProbeSkeleton for the particular framework.
*/
protected abstract ProbeSkeleton createProbe(Method method);
/**
* Initializes the provider.
*
* @param type the user's interface
*/
protected ProviderSkeleton(Class<? extends Provider> type) {
this.active = false; // in case of some error during initialization
this.providerType = type;
this.probes = new HashMap<Method,ProbeSkeleton>();
}
/**
* Post-constructor initialization routine.
*
* Subclass instances must be initialized before they can create probes.
* It is up to the factory implementations to call this after construction.
*/
public void init() {
for (Method m : providerType.getDeclaredMethods()) {
if ( m.getReturnType() != Void.TYPE ) {
throw new IllegalArgumentException(
"Return value of method is not void");
} else {
probes.put(m, createProbe(m));
}
}
this.active = true;
}
/**
* Magic routine which creates an implementation of the user's interface.
*
* This method creates the instance of the user's interface which is
* passed back to the user. Every call upon that interface will be
* redirected to the {@code invoke()} method of this class (until
* overridden by the VM).
*
* @return an implementation of the user's interface
*/
@SuppressWarnings("unchecked")
public <T extends Provider> T newProxyInstance() {
return (T)Proxy.newProxyInstance(providerType.getClassLoader(),
new Class<?>[] { providerType }, this);
}
/**
* Triggers a framework probe when a user interface method is called.
*
* This method dispatches a user interface method call to the appropriate
* probe associated with this framework.
*
* If the invoked method is not a user-defined member of the interface,
* then it is a member of {@code Provider} or {@code Object} and we
* invoke the method directly.
*
* @param proxy the instance whose method was invoked
* @param method the method that was called
* @param args the arguments passed in the call.
* @return always null, if the method is a user-defined probe
*/
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getDeclaringClass() != providerType) {
try {
return method.invoke(this, args);
} catch (IllegalAccessException e) {
assert false;
} catch (InvocationTargetException e) {
assert false;
}
} else if (active) {
ProbeSkeleton p = probes.get(method);
if (p != null) {
// Skips argument check -- already done by javac
p.uncheckedTrigger(args);
}
}
return null;
}
/**
* Direct accessor for {@code Probe} objects.
*
* @param m the method corresponding to a probe
* @return the method associated probe object, or null
*/
public Probe getProbe(Method m) {
return active ? probes.get(m) : null;
}
/**
* Default provider disposal method.
*
* This is overridden in subclasses as needed.
*/
public void dispose() {
active = false;
probes.clear();
}
/**
* Gets the user-specified provider name for the user's interface.
*
* If the user's interface has a {@ProviderName} annotation, that value
* is used. Otherwise we use the simple name of the user interface's class.
* @return the provider name
*/
protected String getProviderName() {
return getAnnotationString(
providerType, ProviderName.class, providerType.getSimpleName());
}
/**
* Utility method for getting a string value from an annotation.
*
* Used for getting a string value from an annotation with a 'value' method.
*
* @param element the element that was annotated, either a class or method
* @param annotation the class of the annotation we're interested in
* @param defaultValue the value to return if the annotation doesn't
* exist, doesn't have a "value", or the value is empty.
*/
protected static String getAnnotationString(
AnnotatedElement element, Class<? extends Annotation> annotation,
String defaultValue) {
String ret = (String)getAnnotationValue(
element, annotation, "value", defaultValue);
return ret.isEmpty() ? defaultValue : ret;
}
/**
* Utility method for calling an arbitrary method in an annotation.
*
* @param element the element that was annotated, either a class or method
* @param annotation the class of the annotation we're interested in
* @param methodName the name of the method in the annotation we wish
* to call.
* @param defaultValue the value to return if the annotation doesn't
* exist, or we couldn't invoke the method for some reason.
* @return the result of calling the annotation method, or the default.
*/
protected static Object getAnnotationValue(
AnnotatedElement element, Class<? extends Annotation> annotation,
String methodName, Object defaultValue) {
Object ret = defaultValue;
try {
Method m = annotation.getMethod(methodName);
Annotation a = element.getAnnotation(annotation);
ret = m.invoke(a);
} catch (NoSuchMethodException e) {
assert false;
} catch (IllegalAccessException e) {
assert false;
} catch (InvocationTargetException e) {
assert false;
} catch (NullPointerException e) {
assert false;
}
return ret;
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing.dtrace;
import java.lang.ref.WeakReference;
import java.lang.ref.ReferenceQueue;
import java.security.Permission;
import java.util.HashSet;
class Activation {
private SystemResource resource;
private int referenceCount;
Activation(String moduleName, DTraceProvider[] providers) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
Permission perm =
new RuntimePermission("com.sun.tracing.dtrace.createProvider");
security.checkPermission(perm);
}
referenceCount = providers.length;
for (DTraceProvider p : providers) {
p.setActivation(this);
}
resource = new SystemResource(
this, JVM.activate(moduleName, providers));
}
void disposeProvider(DTraceProvider p) {
if (--referenceCount == 0) {
resource.dispose();
}
}
}
/**
* The native resource part of an Activation.
*
* This holds the native handle.
*
* If the user loses a reference to a set of Providers without disposing them,
* and GC determines the Activation is unreachable, then the next
* activation or flush call will automatically dispose the unreachable objects
*
* The SystemResource instances are creating during activation, and
* unattached during disposal. When created, they always have a
* strong reference to them via the {@code resources} static member. Explicit
* {@code dispose} calls will unregister the native resource and remove
* references to the SystemResource object. Absent an explicit dispose,
* when their associated Activation object becomes garbage, the SystemResource
* object will be enqueued on the reference queue and disposed at the
* next call to {@code flush}.
*/
class SystemResource extends WeakReference<Activation> {
private long handle;
private static ReferenceQueue<Activation> referenceQueue =
referenceQueue = new ReferenceQueue<Activation>();
static HashSet<SystemResource> resources = new HashSet<SystemResource>();
SystemResource(Activation activation, long handle) {
super(activation, referenceQueue);
this.handle = handle;
flush();
resources.add(this);
}
void dispose() {
JVM.dispose(handle);
resources.remove(this);
handle = 0;
}
static void flush() {
SystemResource resource = null;
while ((resource = (SystemResource)referenceQueue.poll()) != null) {
if (resource.handle != 0) {
resource.dispose();
}
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing.dtrace;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import sun.tracing.ProbeSkeleton;
class DTraceProbe extends ProbeSkeleton {
private Object proxy;
private Method declared_method;
private Method implementing_method;
DTraceProbe(Object proxy, Method m) {
super(m.getParameterTypes());
this.proxy = proxy;
this.declared_method = m;
try {
// The JVM will override the proxy method's implementation with
// a version that will invoke the probe.
this.implementing_method = proxy.getClass().getMethod(
m.getName(), m.getParameterTypes());
} catch (NoSuchMethodException e) {
throw new RuntimeException("Internal error, wrong proxy class");
}
}
public boolean isEnabled() {
return JVM.isEnabled(implementing_method);
}
public void uncheckedTrigger(Object[] args) {
try {
implementing_method.invoke(proxy, args);
} catch (IllegalAccessException e) {
assert false;
} catch (InvocationTargetException e) {
assert false;
}
}
String getProbeName() {
return DTraceProvider.getProbeName(declared_method);
}
String getFunctionName() {
return DTraceProvider.getFunctionName(declared_method);
}
Method getMethod() {
return implementing_method;
}
Class<?>[] getParameterTypes() {
return this.parameters;
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing.dtrace;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import sun.tracing.ProviderSkeleton;
import sun.tracing.ProbeSkeleton;
import com.sun.tracing.Provider;
import com.sun.tracing.ProviderName;
import com.sun.tracing.ProbeName;
import com.sun.tracing.dtrace.Attributes;
import com.sun.tracing.dtrace.ModuleName;
import com.sun.tracing.dtrace.FunctionName;
import com.sun.tracing.dtrace.StabilityLevel;
import com.sun.tracing.dtrace.DependencyClass;
import sun.misc.ProxyGenerator;
class DTraceProvider extends ProviderSkeleton {
private Activation activation;
private Object proxy;
// For proxy generation
private final static Class[] constructorParams = { InvocationHandler.class };
private final String proxyClassNamePrefix = "$DTraceTracingProxy";
static final String DEFAULT_MODULE = "java_tracing";
static final String DEFAULT_FUNCTION = "unspecified";
private static long nextUniqueNumber = 0;
private static synchronized long getUniqueNumber() {
return nextUniqueNumber++;
}
protected ProbeSkeleton createProbe(Method m) {
return new DTraceProbe(proxy, m);
}
DTraceProvider(Class<? extends Provider> type) {
super(type);
}
void setProxy(Object p) {
proxy = p;
}
void setActivation(Activation a) {
this.activation = a;
}
public void dispose() {
if (activation != null) {
activation.disposeProvider(this);
activation = null;
}
super.dispose();
}
/**
* Magic routine which creates an implementation of the user's interface.
*
* This method uses the ProxyGenerator directly to bypass the
* java.lang.reflect.proxy cache so that we get a unique class each
* time it's called and can't accidently reuse a $Proxy class.
*
* @return an implementation of the user's interface
*/
@SuppressWarnings("unchecked")
public <T extends Provider> T newProxyInstance() {
/*
* Choose a name for the proxy class to generate.
*/
long num = getUniqueNumber();
String proxyPkg = "";
if (!Modifier.isPublic(providerType.getModifiers())) {
String name = providerType.getName();
int n = name.lastIndexOf('.');
proxyPkg = ((n == -1) ? "" : name.substring(0, n + 1));
}
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
*/
Class<?> proxyClass = null;
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, new Class<?>[] { providerType });
try {
proxyClass = JVM.defineClass(
providerType.getClassLoader(), proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
Constructor cons = proxyClass.getConstructor(constructorParams);
return (T)cons.newInstance(new Object[] { this });
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
} catch (IllegalAccessException e) {
throw new InternalError(e.toString());
} catch (InstantiationException e) {
throw new InternalError(e.toString());
} catch (InvocationTargetException e) {
throw new InternalError(e.toString());
}
}
// In the normal case, the proxy object's method implementations will call
// this method (it usually calls the ProviderSkeleton's version). That
// method uses the passed 'method' object to lookup the associated
// 'ProbeSkeleton' and calls uncheckedTrigger() on that probe to cause the
// probe to fire. DTrace probes are different in that the proxy class's
// methods are immediately overridden with native code to fire the probe
// directly. So this method should never get invoked. We also wire up the
// DTraceProbe.uncheckedTrigger() method to call the proxy method instead
// of doing the work itself.
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.getDeclaringClass() != providerType) {
try {
return method.invoke(this, args);
} catch (IllegalAccessException e) {
assert false;
} catch (InvocationTargetException e) {
assert false;
}
} else if (active) {
assert false : "This method should have been overridden by the JVM";
}
return null;
}
public String getProviderName() {
return super.getProviderName();
}
String getModuleName() {
return getAnnotationString(
providerType, ModuleName.class, DEFAULT_MODULE);
}
static String getProbeName(Method method) {
return getAnnotationString(
method, ProbeName.class, method.getName());
}
static String getFunctionName(Method method) {
return getAnnotationString(
method, FunctionName.class, DEFAULT_FUNCTION);
}
DTraceProbe[] getProbes() {
return probes.values().toArray(new DTraceProbe[0]);
}
StabilityLevel getNameStabilityFor(Class<? extends Annotation> type) {
Attributes attrs = (Attributes)getAnnotationValue(
providerType, type, "value", null);
if (attrs == null) {
return StabilityLevel.PRIVATE;
} else {
return attrs.name();
}
}
StabilityLevel getDataStabilityFor(Class<? extends Annotation> type) {
Attributes attrs = (Attributes)getAnnotationValue(
providerType, type, "value", null);
if (attrs == null) {
return StabilityLevel.PRIVATE;
} else {
return attrs.data();
}
}
DependencyClass getDependencyClassFor(Class<? extends Annotation> type) {
Attributes attrs = (Attributes)getAnnotationValue(
providerType, type, "value", null);
if (attrs == null) {
return DependencyClass.UNKNOWN;
} else {
return attrs.dependency();
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing.dtrace;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Logger;
import java.security.Permission;
import com.sun.tracing.ProviderFactory;
import com.sun.tracing.Provider;
/**
* Factory class to create JSDT Providers.
*
* This class contains methods to create an instance of a Provider
* interface which can be used to place tracepoints in an application.
* Method calls upon that instance trigger DTrace probes that
* are visible from DTrace scripts. Such calls have no other
* side effects in the application.
* <p>
* The DTrace script mechanisms for listing and matching probes will not see
* nor match any probes until the provider they reside in is created by a
* call to {@code createProvider()} (or {@code createProviders()}).
* <p>
* Providers that are created should be disposed of when they are no longer
* needed to free up system resources, at which point the associated
* DTrace probes will no longer be available to DTrace. One disposes a
* provider by calling
* {@link com.sun.tracing.Provider#dispose Provider.dispose()} on a
* created provider instance.
*
* @since 1.7
*/
public final class DTraceProviderFactory extends ProviderFactory {
/**
* Creates an instance of a provider which can then be used to trigger
* DTrace probes.
*
* The provider specification, provided as an argument, should only
* contain methods which have a 'void' return type and String or
* integer-based typed arguments (long, int, short, char, byte, or boolean).
*
* @param cls A user-defined interface which extends {@code Provider}.
* @return An instance of the interface which is used to trigger
* the DTrace probes.
* @throws java.lang.SecurityException if a security manager has been
* installed and it denies
* RuntimePermission("com.sun.dtrace.jsdt.createProvider")
* @throws java.lang.IllegalArgumentException if the interface contains
* methods that do not return null, or that contain arguments that are
* not String or integer types.
*/
public <T extends Provider> T createProvider(Class<T> cls) {
DTraceProvider jsdt = new DTraceProvider(cls);
T proxy = jsdt.newProxyInstance();
jsdt.setProxy(proxy);
try {
jsdt.init();
new Activation(jsdt.getModuleName(), new DTraceProvider[] { jsdt });
} catch (Exception e) {
// Probably a permission problem (can't get declared members)
Logger.getAnonymousLogger().warning(
"Could not initialize tracing provider: " + e.getMessage());
jsdt.dispose();
}
return proxy;
}
/**
* Creates multiple providers at once.
*
* This method batches together a number of provider instantiations.
* It works similarly
* to {@code createProvider}, but operates on a set of providers instead
* of one at a time. This method is in place since some DTrace
* implementations limit the number of times that providers can be
* created. When numerous providers can be created at once with this
* method, it will count only as a single creation point to DTrace, thus
* it uses less system resources.
* <p>
* All of the probes in the providers will be visible to DTrace after
* this call and all will remain visible until all of the providers
* are disposed.
* <p>
* The {@code moduleName} parameter will override any {@code ModuleName}
* annotation associated with any of the providers in the set.
* All of the probes created by this call will share the same
* module name.
* <p>
* @param providers a set of provider specification interfaces
* @param moduleName the module name to associate with all probes
* @return A map which maps the provider interface specification to an
* implementing instance.
* @throws java.lang.SecurityException if a security manager has been
* installed and it denies
* RuntimePermission("com.sun.dtrace.jsdt.createProvider")
* @throws java.lang.IllegalArgumentException if any of the interface
* contains methods that do not return null, or that contain arguments
* that are not String or integer types.
*/
public Map<Class<? extends Provider>,Provider> createProviders(
Set<Class<? extends Provider>> providers, String moduleName) {
HashMap<Class<? extends Provider>,Provider> map =
new HashMap<Class<? extends Provider>,Provider>();
HashSet<DTraceProvider> jsdts = new HashSet<DTraceProvider>();
for (Class<? extends Provider> cls : providers) {
DTraceProvider jsdt = new DTraceProvider(cls);
jsdts.add(jsdt);
map.put(cls, jsdt.newProxyInstance());
}
new Activation(moduleName, jsdts.toArray(new DTraceProvider[0]));
return map;
}
/**
* Used to check the status of DTrace support in the underlying JVM and
* operating system.
*
* This is an informative method only - the Java-level effects of
* creating providers and triggering probes will not change whether or
* not DTrace is supported by the underlying systems.
*
* @return true if DTrace is supported
*/
public static boolean isSupported() {
try {
SecurityManager security = System.getSecurityManager();
if (security != null) {
Permission perm = new RuntimePermission(
"com.sun.tracing.dtrace.createProvider");
security.checkPermission(perm);
}
return JVM.isSupported();
} catch (SecurityException e) {
return false;
}
}
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package sun.tracing.dtrace;
import java.lang.reflect.Method;
/**
* Container class for JVM interface native methods
*
* @since 1.7
*/
class JVM {
static {
java.security.AccessController.doPrivileged(
new sun.security.action.LoadLibraryAction("jsdt"));
}
static long activate(String moduleName, DTraceProvider[] providers) {
return activate0(moduleName, providers);
}
static void dispose(long handle) {
dispose0(handle);
}
static boolean isEnabled(Method m) {
return isEnabled0(m);
}
static boolean isSupported() {
return isSupported0();
}
static Class<?> defineClass(
ClassLoader loader, String name, byte[] b, int off, int len) {
return defineClass0(loader, name, b, off, len);
}
private static native long activate0(
String moduleName, DTraceProvider[] providers);
private static native void dispose0(long activation_handle);
private static native boolean isEnabled0(Method m);
private static native boolean isSupported0();
private static native Class<?> defineClass0(
ClassLoader loader, String name, byte[] b, int off, int len);
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/**
* This package contains internal common code for implementing tracing
* frameworks, and defined a number of existing frameworks.
* <p>
* There are four tracing frameworks currently defined. The "Null" and
* "Multiplex" frameworks are used internally as part of the implementation.
* The "DTrace" framework is the prime consumer framework at the moment,
* while the "PrintStream" framework is a functional, but hidden, framework
* which can be used to track probe firings. All but the "DTrace" framework
* are defined in this package. The "DTrace" framework is implemented in the
* {@code sun.tracing.dtrace} package.
* <p>
* This package also contains the {@code ProviderSkeleton} class, which
* holds most of the common code needed for implementing frameworks.
* <p>
* The "Null" framework is used when there are no other active frameworks.
* It accomplishes absolutely nothing and is merely a placeholder so that
* the application can call the tracing routines without error.
* <p>
* The "Multiplex" framework is used when there are multiple active frameworks.
* It is initialized with the framework factories and create providers and
* probes that dispatch to each active framework in turn.
* <p>
* The "PrintStream" framework is currently a debugging framework which
* dispatches trace calls to a user-defined PrintStream class, defined by
* a property. It may some day be opened up to general use.
* <p>
* See the {@code sun.tracing.dtrace} and {@code com.sun.tracing.dtrace}
* packages for information on the "DTrace" framework.
*/
package sun.tracing;
...@@ -591,6 +591,80 @@ JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused); ...@@ -591,6 +591,80 @@ JVM_AssertionStatusDirectives(JNIEnv *env, jclass unused);
JNIEXPORT jboolean JNICALL JNIEXPORT jboolean JNICALL
JVM_SupportsCX8(void); JVM_SupportsCX8(void);
/*
* com.sun.dtrace.jsdt support
*/
#define JVM_TRACING_DTRACE_VERSION 1
/*
* Structure to pass one probe description to JVM
*/
typedef struct {
jmethodID method;
jstring function;
jstring name;
void* reserved[4]; // for future use
} JVM_DTraceProbe;
/**
* Encapsulates the stability ratings for a DTrace provider field
*/
typedef struct {
jint nameStability;
jint dataStability;
jint dependencyClass;
} JVM_DTraceInterfaceAttributes;
/*
* Structure to pass one provider description to JVM
*/
typedef struct {
jstring name;
JVM_DTraceProbe* probes;
jint probe_count;
JVM_DTraceInterfaceAttributes providerAttributes;
JVM_DTraceInterfaceAttributes moduleAttributes;
JVM_DTraceInterfaceAttributes functionAttributes;
JVM_DTraceInterfaceAttributes nameAttributes;
JVM_DTraceInterfaceAttributes argsAttributes;
void* reserved[4]; // for future use
} JVM_DTraceProvider;
/*
* Get the version number the JVM was built with
*/
JNIEXPORT jint JNICALL
JVM_DTraceGetVersion(JNIEnv* env);
/*
* Register new probe with given signature, return global handle
*
* The version passed in is the version that the library code was
* built with.
*/
JNIEXPORT jlong JNICALL
JVM_DTraceActivate(JNIEnv* env, jint version, jstring module_name,
jint providers_count, JVM_DTraceProvider* providers);
/*
* Check JSDT probe
*/
JNIEXPORT jboolean JNICALL
JVM_DTraceIsProbeEnabled(JNIEnv* env, jmethodID method);
/*
* Destroy custom DOF
*/
JNIEXPORT void JNICALL
JVM_DTraceDispose(JNIEnv* env, jlong activation_handle);
/*
* Check to see if DTrace is supported by OS
*/
JNIEXPORT jboolean JNICALL
JVM_DTraceIsSupported(JNIEnv* env);
/************************************************************************* /*************************************************************************
PART 2: Support for the Verifier and Class File Format Checker PART 2: Support for the Verifier and Class File Format Checker
************************************************************************/ ************************************************************************/
......
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
#include <stdlib.h>
#include "jvm.h"
#include "jni.h"
#include "jni_util.h"
#include "jvm_symbols.h"
#include "sun_tracing_dtrace_JVM.h"
#ifdef __cplusplus
extern "C" {
#endif
static JvmSymbols* jvm_symbols = NULL;
static void initialize() {
static int initialized = 0;
if (initialized == 0) {
jvm_symbols = lookupJvmSymbols();
initialized = 1;
}
}
/*
* Class: sun_tracing_dtrace_JVM
* Method: isSupported0
* Signature: ()I
*/
JNIEXPORT jboolean JNICALL Java_sun_tracing_dtrace_JVM_isSupported0(
JNIEnv* env, jclass cls) {
initialize();
if (jvm_symbols != NULL) {
return jvm_symbols->IsSupported(env) ? JNI_TRUE : JNI_FALSE;
} else {
return JNI_FALSE;
}
}
// Macros that cause an immediate return if we detect an exception
#define CHECK if ((*env)->ExceptionOccurred(env)) { return; }
#define CHECK_(x) if ((*env)->ExceptionOccurred(env)) { return x; }
static void readProbeData (
JNIEnv* env, jobject probe, JVM_DTraceProbe* jvm_probe) {
jclass clazz;
jmethodID mid;
jobject method;
if (jvm_probe == NULL) {
return; // just in case
}
clazz = (*env)->GetObjectClass(env, probe); CHECK
mid = (*env)->GetMethodID(
env, clazz, "getFunctionName", "()Ljava/lang/String;"); CHECK
jvm_probe->function = (jstring)(*env)->CallObjectMethod(
env, probe, mid); CHECK
mid = (*env)->GetMethodID(
env, clazz, "getProbeName", "()Ljava/lang/String;"); CHECK
jvm_probe->name = (jstring)(*env)->CallObjectMethod(env, probe, mid); CHECK
mid = (*env)->GetMethodID(
env, clazz, "getMethod", "()Ljava/lang/reflect/Method;"); CHECK
method = (*env)->CallObjectMethod(env, probe, mid); CHECK
jvm_probe->method = (*env)->FromReflectedMethod(env, method); CHECK
}
static void readFieldInterfaceAttributes(
char* annotationName, JNIEnv* env, jobject provider,
JVM_DTraceInterfaceAttributes* attrs) {
jobject result;
jobject result_clazz;
jclass provider_clazz;
jclass annotation_clazz;
jmethodID get;
jmethodID enc;
provider_clazz = (*env)->GetObjectClass(env, provider); CHECK
annotation_clazz = (*env)->FindClass(env, annotationName); CHECK
get = (*env)->GetMethodID(env, provider_clazz, "getNameStabilityFor",
"(Ljava/lang/Class;)Lcom/sun/tracing/dtrace/StabilityLevel;"); CHECK
result = (*env)->CallObjectMethod(
env, provider, get, annotation_clazz); CHECK
result_clazz = (*env)->GetObjectClass(env, result); CHECK
enc = (*env)->GetMethodID(env, result_clazz, "getEncoding", "()I"); CHECK
attrs->nameStability = (*env)->CallIntMethod(env, result, enc); CHECK
get = (*env)->GetMethodID(env, provider_clazz, "getDataStabilityFor",
"(Ljava/lang/Class;)Lcom/sun/tracing/dtrace/StabilityLevel;"); CHECK
result = (*env)->CallObjectMethod(
env, provider, get, annotation_clazz); CHECK
result_clazz = (*env)->GetObjectClass(env, result); CHECK
enc = (*env)->GetMethodID(env, result_clazz, "getEncoding", "()I"); CHECK
attrs->dataStability = (*env)->CallIntMethod(env, result, enc); CHECK
get = (*env)->GetMethodID(env, provider_clazz, "getDependencyClassFor",
"(Ljava/lang/Class;)Lcom/sun/tracing/dtrace/DependencyClass;"); CHECK
result = (*env)->CallObjectMethod(
env, provider, get, annotation_clazz); CHECK
result_clazz = (*env)->GetObjectClass(env, result); CHECK
enc = (*env)->GetMethodID(env, result_clazz, "getEncoding", "()I"); CHECK
attrs->dependencyClass = (*env)->CallIntMethod(env, result, enc); CHECK
}
static void readInterfaceAttributes(
JNIEnv* env, jobject provider, JVM_DTraceProvider* jvm_provider) {
readFieldInterfaceAttributes("com/sun/tracing/dtrace/ProviderAttributes",
env, provider, &(jvm_provider->providerAttributes));
readFieldInterfaceAttributes("com/sun/tracing/dtrace/ModuleAttributes",
env, provider, &(jvm_provider->moduleAttributes));
readFieldInterfaceAttributes("com/sun/tracing/dtrace/FunctionAttributes",
env, provider, &(jvm_provider->functionAttributes));
readFieldInterfaceAttributes("com/sun/tracing/dtrace/NameAttributes",
env, provider, &(jvm_provider->nameAttributes));
readFieldInterfaceAttributes("com/sun/tracing/dtrace/ArgsAttributes",
env, provider, &(jvm_provider->argsAttributes));
}
static void readProviderData(
JNIEnv* env, jobject provider, JVM_DTraceProvider* jvm_provider) {
jmethodID mid;
jobjectArray probes;
jsize i;
jclass clazz = (*env)->GetObjectClass(env, provider); CHECK
mid = (*env)->GetMethodID(
env, clazz, "getProbes", "()[Lsun/tracing/dtrace/DTraceProbe;"); CHECK
probes = (jobjectArray)(*env)->CallObjectMethod(
env, provider, mid); CHECK
// Fill JVM structure, describing provider
jvm_provider->probe_count = (*env)->GetArrayLength(env, probes); CHECK
jvm_provider->probes = (JVM_DTraceProbe*)calloc(
jvm_provider->probe_count, sizeof(*jvm_provider->probes));
mid = (*env)->GetMethodID(
env, clazz, "getProviderName", "()Ljava/lang/String;"); CHECK
jvm_provider->name = (jstring)(*env)->CallObjectMethod(
env, provider, mid); CHECK
readInterfaceAttributes(env, provider, jvm_provider); CHECK
for (i = 0; i < jvm_provider->probe_count; ++i) {
jobject probe = (*env)->GetObjectArrayElement(env, probes, i); CHECK
readProbeData(env, probe, &jvm_provider->probes[i]); CHECK
}
}
/*
* Class: sun_tracing_dtrace_JVM
* Method: activate0
* Signature: ()J
*/
JNIEXPORT jlong JNICALL Java_sun_tracing_dtrace_JVM_activate0(
JNIEnv* env, jclass cls, jstring moduleName, jobjectArray providers) {
jlong handle = 0;
jsize num_providers;
jsize i;
JVM_DTraceProvider* jvm_providers;
initialize();
if (jvm_symbols == NULL) {
return 0;
}
num_providers = (*env)->GetArrayLength(env, providers); CHECK_(0L)
jvm_providers = (JVM_DTraceProvider*)calloc(
num_providers, sizeof(*jvm_providers));
for (i = 0; i < num_providers; ++i) {
JVM_DTraceProvider* p = &(jvm_providers[i]);
jobject provider = (*env)->GetObjectArrayElement(
env, providers, i);
readProviderData(env, provider, p);
}
handle = jvm_symbols->Activate(
env, JVM_TRACING_DTRACE_VERSION, moduleName,
num_providers, jvm_providers);
for (i = 0; i < num_providers; ++i) {
JVM_DTraceProvider* p = &(jvm_providers[i]);
free(p->probes);
}
free(jvm_providers);
return handle;
}
/*
* Class: sun_tracing_dtrace_JVM
* Method: dispose0
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_sun_tracing_dtrace_JVM_dispose0(
JNIEnv* env, jclass cls, jlong handle) {
if (jvm_symbols != NULL && handle != 0) {
jvm_symbols->Dispose(env, handle);
}
}
/*
* Class: sun_tracing_dtrace_JVM
* Method: isEnabled0
* Signature: (Ljava/lang/String;Ljava/lang/String;)Z
*/
JNIEXPORT jboolean JNICALL Java_sun_tracing_dtrace_JVM_isEnabled0(
JNIEnv* env, jclass cls, jobject method) {
jmethodID mid;
if (jvm_symbols != NULL && method != NULL) {
mid = (*env)->FromReflectedMethod(env, method);
return jvm_symbols->IsProbeEnabled(env, mid);
}
return JNI_FALSE;
}
/*
* Class: sun_tracing_dtrace_JVM
* Method: defineClass0
* Signature: (Ljava/lang/ClassLoader;Ljava/lang/String;[BII)Ljava/lang/Class;
*
* The implementation of this native static method is a copy of that of
* the native instance method Java_java_lang_ClassLoader_defineClass0()
* with the implicit "this" parameter becoming the "loader" parameter.
*
* This code was cloned and modified from java_lang_reflect_Proxy
*/
JNIEXPORT jclass JNICALL
Java_sun_tracing_dtrace_JVM_defineClass0(
JNIEnv *env, jclass ignore, jobject loader, jstring name, jbyteArray data,
jint offset, jint length)
{
jbyte *body;
char *utfName;
jclass result = 0;
char buf[128];
if (data == NULL) {
return 0;
}
/* Work around 4153825. malloc crashes on Solaris when passed a
* negative size.
*/
if (length < 0) {
return 0;
}
body = (jbyte *)malloc(length);
if (body == 0) {
return 0;
}
(*env)->GetByteArrayRegion(env, data, offset, length, body);
if ((*env)->ExceptionOccurred(env))
goto free_body;
if (name != NULL) {
int i;
int len = (*env)->GetStringUTFLength(env, name);
int unicode_len = (*env)->GetStringLength(env, name);
if (len >= sizeof(buf)) {
utfName = malloc(len + 1);
if (utfName == NULL) {
goto free_body;
}
} else {
utfName = buf;
}
(*env)->GetStringUTFRegion(env, name, 0, unicode_len, utfName);
// Convert '.' to '/' in the package name
for (i = 0; i < unicode_len; ++i) {
if (utfName[i] == '.') {
utfName[i] = '/';
}
}
} else {
utfName = NULL;
}
result = (*env)->DefineClass(env, utfName, loader, body, length);
if (utfName && utfName != buf)
free(utfName);
free_body:
free(body);
return result;
}
#ifdef __cplusplus
}
#endif
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
#ifndef _JVM_SYMBOLS_H
#define _JVM_SYMBOLS_H
#include "jvm.h"
typedef jint (JNICALL* GetVersion_t)(JNIEnv*);
typedef jboolean (JNICALL *IsSupported_t)(JNIEnv*);
typedef jlong (JNICALL* Activate_t)(
JNIEnv*, jint, jstring, jint, JVM_DTraceProvider*);
typedef void (JNICALL *Dispose_t)(JNIEnv*, jlong);
typedef jboolean (JNICALL *IsProbeEnabled_t)(JNIEnv*, jmethodID);
typedef struct {
GetVersion_t GetVersion;
IsSupported_t IsSupported;
Activate_t Activate;
Dispose_t Dispose;
IsProbeEnabled_t IsProbeEnabled;
} JvmSymbols;
// Platform-dependent implementation.
// Returns NULL if the symbols are not found
extern JvmSymbols* lookupJvmSymbols();
#endif // def _JVM_SYMBOLS_H
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
#include <dlfcn.h>
#include <stdlib.h>
#include <jvm.h>
#include "jvm_symbols.h"
JvmSymbols* lookupJvmSymbols() {
JvmSymbols* syms = (JvmSymbols*)malloc(sizeof(JvmSymbols));
if (syms != NULL) {
syms->GetVersion = (GetVersion_t)
dlsym(RTLD_DEFAULT, "JVM_DTraceGetVersion");
syms->IsSupported = (IsSupported_t)
dlsym(RTLD_DEFAULT, "JVM_DTraceIsSupported");
syms->Activate = (Activate_t)
dlsym(RTLD_DEFAULT, "JVM_DTraceActivate");
syms->Dispose = (Dispose_t)
dlsym(RTLD_DEFAULT, "JVM_DTraceDispose");
syms->IsProbeEnabled = (IsProbeEnabled_t)
dlsym(RTLD_DEFAULT, "JVM_DTraceIsProbeEnabled");
if ( syms->GetVersion == NULL || syms->Activate == NULL ||
syms->IsProbeEnabled == NULL || syms->Dispose == NULL ||
syms->IsSupported == NULL) {
free(syms);
syms = NULL;
}
}
return syms;
}
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <jvm.h>
#include "jvm_symbols.h"
JvmSymbols* lookupJvmSymbols() {
JvmSymbols* syms = (JvmSymbols*)malloc(sizeof(JvmSymbols));
if (syms != NULL) {
HINSTANCE jvm = LoadLibrary("jvm.dll");
if (jvm == NULL) {
free(syms);
return NULL;
}
syms->GetVersion = (GetVersion_t)
GetProcAddress(jvm, "JVM_DTraceGetVersion");
syms->IsSupported = (IsSupported_t)
GetProcAddress(jvm, "JVM_DTraceIsSupported");
syms->Activate = (Activate_t)
GetProcAddress(jvm, "JVM_DTraceActivate");
syms->Dispose = (Dispose_t)
GetProcAddress(jvm, "JVM_DTraceDispose");
syms->IsProbeEnabled = (IsProbeEnabled_t)
GetProcAddress(jvm, "JVM_DTraceIsProbeEnabled");
(void)FreeLibrary(jvm);
if ( syms->GetVersion == NULL || syms->IsSupported == NULL ||
syms->Activate == NULL || syms->Dispose == NULL ||
syms->IsProbeEnabled == NULL) {
free(syms);
syms = NULL;
}
}
return syms;
}
...@@ -29,14 +29,14 @@ ...@@ -29,14 +29,14 @@
*/ */
import java.lang.management.*; import java.lang.management.*;
import java.util.List;
import javax.management.MBeanServer; import javax.management.MBeanServer;
import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.HotSpotDiagnosticMXBean;
public class DumpHeap { public class DumpHeap {
public static void main(String[] argv) throws Exception { public static void main(String[] argv) throws Exception {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); List<HotSpotDiagnosticMXBean> list = ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
HotSpotDiagnosticMXBean dm = sun.management.ManagementFactory.getDiagnosticMXBean();
System.out.println("Dumping to file: " + argv[0] + " ...."); System.out.println("Dumping to file: " + argv[0] + " ....");
dm.dumpHeap(argv[0], true); list.get(0).dumpHeap(argv[0], true);
} }
} }
...@@ -41,8 +41,9 @@ public class GetDiagnosticOptions { ...@@ -41,8 +41,9 @@ public class GetDiagnosticOptions {
"com.sun.management:type=HotSpotDiagnostic"; "com.sun.management:type=HotSpotDiagnostic";
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HotSpotDiagnosticMXBean mbean = List<HotSpotDiagnosticMXBean> list =
sun.management.ManagementFactory.getDiagnosticMXBean(); ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
HotSpotDiagnosticMXBean mbean = list.get(0);
checkDiagnosticOptions(mbean); checkDiagnosticOptions(mbean);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
......
...@@ -34,6 +34,7 @@ import com.sun.management.HotSpotDiagnosticMXBean; ...@@ -34,6 +34,7 @@ import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption; import com.sun.management.VMOption;
import com.sun.management.VMOption.Origin; import com.sun.management.VMOption.Origin;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.util.List;
import javax.management.MBeanServer; import javax.management.MBeanServer;
public class GetVMOption { public class GetVMOption {
...@@ -44,8 +45,9 @@ public class GetVMOption { ...@@ -44,8 +45,9 @@ public class GetVMOption {
"com.sun.management:type=HotSpotDiagnostic"; "com.sun.management:type=HotSpotDiagnostic";
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
HotSpotDiagnosticMXBean mbean = List<HotSpotDiagnosticMXBean> list =
sun.management.ManagementFactory.getDiagnosticMXBean(); ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
HotSpotDiagnosticMXBean mbean = list.get(0);
checkVMOption(mbean); checkVMOption(mbean);
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
......
...@@ -31,11 +31,11 @@ ...@@ -31,11 +31,11 @@
* @run main/othervm -XX:+PrintGCDetails SetVMOption * @run main/othervm -XX:+PrintGCDetails SetVMOption
*/ */
import java.lang.management.ManagementFactory;
import java.util.*; import java.util.*;
import com.sun.management.HotSpotDiagnosticMXBean; import com.sun.management.HotSpotDiagnosticMXBean;
import com.sun.management.VMOption; import com.sun.management.VMOption;
import com.sun.management.VMOption.Origin; import com.sun.management.VMOption.Origin;
import sun.management.ManagementFactory;
import sun.misc.Version; import sun.misc.Version;
public class SetVMOption { public class SetVMOption {
...@@ -44,10 +44,11 @@ public class SetVMOption { ...@@ -44,10 +44,11 @@ public class SetVMOption {
private static String BAD_VALUE = "yes"; private static String BAD_VALUE = "yes";
private static String NEW_VALUE = "false"; private static String NEW_VALUE = "false";
private static String MANAGEMENT_SERVER = "ManagementServer"; private static String MANAGEMENT_SERVER = "ManagementServer";
private static HotSpotDiagnosticMXBean mbean = private static HotSpotDiagnosticMXBean mbean;
ManagementFactory.getDiagnosticMXBean();
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
List<HotSpotDiagnosticMXBean> list =
ManagementFactory.getPlatformMXBeans(HotSpotDiagnosticMXBean.class);
// The following test is transitional only and should be removed // The following test is transitional only and should be removed
// once build 52 is promoted. // once build 52 is promoted.
......
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/**
* @test
* @bug 6537506
* @summary Basic unit test for tracing framework
*/
import com.sun.tracing.*;
import java.lang.reflect.Method;
@ProviderName("NamedProvider")
interface BasicProvider extends Provider {
void plainProbe();
void probeWithArgs(int a, float f, String s, Long l);
@ProbeName("namedProbe") void probeWithName();
void overloadedProbe();
void overloadedProbe(int i);
}
interface InvalidProvider extends Provider {
int nonVoidProbe();
}
public class BasicFunctionality {
public static ProviderFactory factory;
public static BasicProvider bp;
public static void main(String[] args) throws Exception {
factory = ProviderFactory.getDefaultFactory();
if (factory != null) {
bp = factory.createProvider(BasicProvider.class);
}
testProviderFactory();
testProbe();
testProvider();
}
static void fail(String s) throws Exception {
throw new Exception(s);
}
static void testProviderFactory() throws Exception {
if (factory == null) {
fail("ProviderFactory.getDefaultFactory: Did not create factory");
}
if (bp == null) {
fail("ProviderFactory.createProvider: Did not create provider");
}
try {
factory.createProvider(null);
fail("ProviderFactory.createProvider: Did not throw NPE for null");
} catch (NullPointerException e) {}
try {
factory.createProvider(InvalidProvider.class);
fail("Factory.createProvider: Should error with non-void probes");
} catch (IllegalArgumentException e) {}
}
public static void testProvider() throws Exception {
// These just shouldn't throw any exeptions:
bp.plainProbe();
bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L));
bp.probeWithArgs(42, (float)3.14, null, null);
bp.probeWithName();
bp.overloadedProbe();
bp.overloadedProbe(42);
Method m = BasicProvider.class.getMethod("plainProbe");
Probe p = bp.getProbe(m);
if (p == null) {
fail("Provider.getProbe: Did not return probe");
}
Method m2 = BasicFunctionality.class.getMethod("testProvider");
p = bp.getProbe(m2);
if (p != null) {
fail("Provider.getProbe: Got probe with invalid spec");
}
bp.dispose();
// These just shouldn't throw any exeptions:
bp.plainProbe();
bp.probeWithArgs(42, (float)3.14, "spam", new Long(2L));
bp.probeWithArgs(42, (float)3.14, null, null);
bp.probeWithName();
bp.overloadedProbe();
bp.overloadedProbe(42);
if (bp.getProbe(m) != null) {
fail("Provider.getProbe: Should return null after dispose()");
}
bp.dispose(); // just to make sure nothing bad happens
}
static void testProbe() throws Exception {
Method m = BasicProvider.class.getMethod("plainProbe");
Probe p = bp.getProbe(m);
p.isEnabled(); // just make sure it doesn't do anything bad
p.trigger();
try {
p.trigger(0);
fail("Probe.trigger: too many arguments not caught");
} catch (IllegalArgumentException e) {}
p = bp.getProbe(BasicProvider.class.getMethod(
"probeWithArgs", int.class, float.class, String.class, Long.class));
try {
p.trigger();
fail("Probe.trigger: too few arguments not caught");
} catch (IllegalArgumentException e) {}
try {
p.trigger((float)3.14, (float)3.14, "", new Long(0L));
fail("Probe.trigger: wrong type primitive arguments not caught");
} catch (IllegalArgumentException e) {}
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6610094
* @summary Basic unit test of ManagementFactory.getPlatformMXBeans()
* and also PlatformManagedObject.getObjectName()
* @author Mandy Chung
*
* @run main GetPlatformMXBeans
*/
import java.lang.management.*;
import static java.lang.management.ManagementFactory.*;
import java.util.*;
import javax.management.*;
public class GetPlatformMXBeans {
private static MBeanServer platformMBeanServer =
getPlatformMBeanServer();
public static void main(String[] argv) throws Exception {
checkPlatformMXBean(getClassLoadingMXBean(),
ClassLoadingMXBean.class,
CLASS_LOADING_MXBEAN_NAME);
checkPlatformMXBean(getCompilationMXBean(),
CompilationMXBean.class,
COMPILATION_MXBEAN_NAME);
checkPlatformMXBean(getMemoryMXBean(),
MemoryMXBean.class,
MEMORY_MXBEAN_NAME);
checkPlatformMXBean(getOperatingSystemMXBean(),
OperatingSystemMXBean.class,
OPERATING_SYSTEM_MXBEAN_NAME);
checkPlatformMXBean(getRuntimeMXBean(),
RuntimeMXBean.class,
RUNTIME_MXBEAN_NAME);
checkPlatformMXBean(getThreadMXBean(),
ThreadMXBean.class,
THREAD_MXBEAN_NAME);
checkGarbageCollectorMXBeans(getGarbageCollectorMXBeans());
checkMemoryManagerMXBeans(getMemoryManagerMXBeans());
checkMemoryPoolMXBeans(getMemoryPoolMXBeans());
}
private static <T extends PlatformManagedObject>
void checkPlatformMXBean(T obj, Class<T> mxbeanInterface,
String mxbeanName) throws Exception
{
int numElements = (obj != null ? 1 : 0);
// verify local list of platform MXBeans
List<? extends PlatformManagedObject> mxbeans =
getPlatformMXBeans(mxbeanInterface);
if (mxbeans.size() != numElements) {
throw new RuntimeException("Unmatched number of platform MXBeans "
+ mxbeans.size() + ". Expected = " + numElements);
}
if (obj != null) {
PlatformManagedObject pmo = mxbeans.get(0);
if (obj != pmo) {
throw new RuntimeException("The list returned by getPlatformMXBeans"
+ " not matched");
}
ObjectName on = new ObjectName(mxbeanName);
if (!on.equals(pmo.getObjectName())) {
throw new RuntimeException("Unmatched ObjectName " +
pmo.getObjectName() + " Expected = " + on);
}
}
// verify platform MXBeans in the platform MBeanServer
mxbeans = getPlatformMXBeans(platformMBeanServer, mxbeanInterface);
if (mxbeans.size() != numElements) {
throw new RuntimeException("Unmatched number of platform MXBeans "
+ mxbeans.size() + ". Expected = " + numElements);
}
}
private static void checkMemoryManagerMXBeans(List<MemoryManagerMXBean> objs)
throws Exception
{
checkPlatformMXBeans(objs, MemoryManagerMXBean.class);
for (MemoryManagerMXBean mxbean : objs) {
String domainAndType;
if (mxbean instanceof GarbageCollectorMXBean) {
domainAndType = GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE;
} else {
domainAndType = MEMORY_MANAGER_MXBEAN_DOMAIN_TYPE;
}
ObjectName on = new ObjectName(domainAndType +
",name=" + mxbean.getName());
if (!on.equals(mxbean.getObjectName())) {
throw new RuntimeException("Unmatched ObjectName " +
mxbean.getObjectName() + " Expected = " + on);
}
}
}
private static void checkMemoryPoolMXBeans(List<MemoryPoolMXBean> objs)
throws Exception
{
checkPlatformMXBeans(objs, MemoryPoolMXBean.class);
for (MemoryPoolMXBean mxbean : objs) {
ObjectName on = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE +
",name=" + mxbean.getName());
if (!on.equals(mxbean.getObjectName())) {
throw new RuntimeException("Unmatched ObjectName " +
mxbean.getObjectName() + " Expected = " + on);
}
}
}
private static void checkGarbageCollectorMXBeans(List<GarbageCollectorMXBean> objs)
throws Exception
{
checkPlatformMXBeans(objs, GarbageCollectorMXBean.class);
for (GarbageCollectorMXBean mxbean : objs) {
ObjectName on = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE +
",name=" + mxbean.getName());
if (!on.equals(mxbean.getObjectName())) {
throw new RuntimeException("Unmatched ObjectName " +
mxbean.getObjectName() + " Expected = " + on);
}
}
}
private static <T extends PlatformManagedObject>
void checkPlatformMXBeans(List<T> objs, Class<T> mxbeanInterface)
throws Exception
{
// verify local list of platform MXBeans
List<? extends PlatformManagedObject> mxbeans =
getPlatformMXBeans(mxbeanInterface);
if (objs.size() != mxbeans.size()) {
throw new RuntimeException("Unmatched number of platform MXBeans "
+ mxbeans.size() + ". Expected = " + objs.size());
}
List<T> list = new ArrayList<T>(objs);
for (PlatformManagedObject pmo : mxbeans) {
if (list.contains(pmo)) {
list.remove(pmo);
} else {
throw new RuntimeException(pmo +
" not in the platform MXBean list");
}
}
if (!list.isEmpty()) {
throw new RuntimeException("The list returned by getPlatformMXBeans"
+ " not matched");
}
// verify platform MXBeans in the platform MBeanServer
mxbeans = getPlatformMXBeans(platformMBeanServer, mxbeanInterface);
if (objs.size() != mxbeans.size()) {
throw new RuntimeException("Unmatched number of platform MXBeans "
+ mxbeans.size() + ". Expected = " + objs.size());
}
}
}
/*
* Copyright 2008 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6610094
* @summary Test the OperatingSystemMXBean instance returned by
* ManagementFactory.getPlatformMXBeans()
* @author Mandy Chung
*
* @run main PlatformMXBeanTest
*/
import java.lang.management.*;
import java.util.List;
public class PlatformMXBeanTest {
public static void main(String[] argv) throws Exception {
OperatingSystemMXBean osMBean = getOSPlatformMXBean(OperatingSystemMXBean.class);
// There should have only one single MXBean for the OS MXBean interfaces:
// java.lang.management.OperatingSystemMXBean
// com.sun.management.OperatingSystemMXBean
// com.sun.management.UnixOperatingSystemMXBean
if (osMBean != getOSPlatformMXBean(com.sun.management.OperatingSystemMXBean.class)) {
throw new RuntimeException(
"Invalid com.sun.management.OperatingSystemMXBean instance");
}
if (!System.getProperty("os.name").startsWith("Windows") &&
osMBean != getOSPlatformMXBean(com.sun.management.UnixOperatingSystemMXBean.class)) {
throw new RuntimeException(
"Invalid com.sun.management.UnixOperatingSystemMXBean instance");
}
}
private static <T extends OperatingSystemMXBean>
T getOSPlatformMXBean(Class<T> c) {
List<T> result = ManagementFactory.getPlatformMXBeans(c);
if (result.isEmpty()) {
return null;
} else if (result.size() == 1) {
return result.get(0);
} else {
throw new RuntimeException(c.getName() + " has " +
result.size() + " number of instances");
}
}
}
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetClassInitializationTime { public class GetClassInitializationTime {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_TIME_FOR_PASS = 1; private static final long MIN_TIME_FOR_PASS = 1;
......
...@@ -39,7 +39,7 @@ import sun.management.*; ...@@ -39,7 +39,7 @@ import sun.management.*;
public class GetClassLoadingTime { public class GetClassLoadingTime {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_TIME_FOR_PASS = 1; private static final long MIN_TIME_FOR_PASS = 1;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetInitializedClassCount { public class GetInitializedClassCount {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_VALUE_FOR_PASS = 1; private static final long MIN_VALUE_FOR_PASS = 1;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetLoadedClassSize { public class GetLoadedClassSize {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_VALUE_FOR_PASS = 1; private static final long MIN_VALUE_FOR_PASS = 1;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetMethodDataSize { public class GetMethodDataSize {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_VALUE_FOR_PASS = 1; private static final long MIN_VALUE_FOR_PASS = 1;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetUnloadedClassSize { public class GetUnloadedClassSize {
private static HotspotClassLoadingMBean mbean = private static HotspotClassLoadingMBean mbean =
(HotspotClassLoadingMBean)ManagementFactory.getHotspotClassLoadingMBean(); (HotspotClassLoadingMBean)ManagementFactoryHelper.getHotspotClassLoadingMBean();
// Careful with these values. // Careful with these values.
private static final long MIN_VALUE_FOR_PASS = 0; private static final long MIN_VALUE_FOR_PASS = 0;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetSafepointCount { public class GetSafepointCount {
private static HotspotRuntimeMBean mbean = private static HotspotRuntimeMBean mbean =
(HotspotRuntimeMBean)ManagementFactory.getHotspotRuntimeMBean(); (HotspotRuntimeMBean)ManagementFactoryHelper.getHotspotRuntimeMBean();
private static final long NUM_THREAD_DUMPS = 5; private static final long NUM_THREAD_DUMPS = 5;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetSafepointSyncTime { public class GetSafepointSyncTime {
private static HotspotRuntimeMBean mbean = private static HotspotRuntimeMBean mbean =
(HotspotRuntimeMBean)ManagementFactory.getHotspotRuntimeMBean(); (HotspotRuntimeMBean)ManagementFactoryHelper.getHotspotRuntimeMBean();
private static final long NUM_THREAD_DUMPS = 300; private static final long NUM_THREAD_DUMPS = 300;
......
...@@ -37,7 +37,7 @@ import sun.management.*; ...@@ -37,7 +37,7 @@ import sun.management.*;
public class GetTotalSafepointTime { public class GetTotalSafepointTime {
private static HotspotRuntimeMBean mbean = private static HotspotRuntimeMBean mbean =
(HotspotRuntimeMBean)ManagementFactory.getHotspotRuntimeMBean(); (HotspotRuntimeMBean)ManagementFactoryHelper.getHotspotRuntimeMBean();
private static final long NUM_THREAD_DUMPS = 100; private static final long NUM_THREAD_DUMPS = 100;
......
...@@ -32,10 +32,11 @@ ...@@ -32,10 +32,11 @@
import sun.management.*; import sun.management.*;
import java.util.*; import java.util.*;
import java.lang.management.ThreadMXBean; import java.lang.management.ThreadMXBean;
import java.lang.management.ManagementFactory;
public class GetInternalThreads { public class GetInternalThreads {
private static HotspotThreadMBean mbean = private static HotspotThreadMBean mbean =
ManagementFactory.getHotspotThreadMBean(); ManagementFactoryHelper.getHotspotThreadMBean();
// Minimum number of VM internal threads // Minimum number of VM internal threads
// VM thread, watcher thread, Low memory detector, compiler thread // VM thread, watcher thread, Low memory detector, compiler thread
...@@ -55,7 +56,7 @@ public class GetInternalThreads { ...@@ -55,7 +56,7 @@ public class GetInternalThreads {
System.out.println("Internal Thread Count = " + value); System.out.println("Internal Thread Count = " + value);
ThreadMXBean thread = ThreadMXBean thread =
java.lang.management.ManagementFactory.getThreadMXBean(); ManagementFactory.getThreadMXBean();
if (!thread.isThreadCpuTimeSupported()) { if (!thread.isThreadCpuTimeSupported()) {
System.out.println("Thread Cpu Time is not supported."); System.out.println("Thread Cpu Time is not supported.");
return; return;
......
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
/* /*
* Copyright 2007 Sun Microsystems, Inc. All Rights Reserved. * Copyright 2007-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
...@@ -33,8 +21,19 @@ import java.util.StringTokenizer; ...@@ -33,8 +21,19 @@ import java.util.StringTokenizer;
* have any questions. * have any questions.
*/ */
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class Arrrghs{ public class Arrrghs {
/** /**
* A group of tests to ensure that arguments are passed correctly to * A group of tests to ensure that arguments are passed correctly to
...@@ -113,12 +112,10 @@ public class Arrrghs{ ...@@ -113,12 +112,10 @@ public class Arrrghs{
return retval; return retval;
} }
private static boolean doExec0(ProcessBuilder pb, String expectedArguments) { private static boolean doExec0(ProcessBuilder pb, String expectedArguments) {
boolean retval = false; boolean retval = false;
try { try {
pb.redirectErrorStream(_debug); pb.redirectErrorStream(true);
Process p = pb.start(); Process p = pb.start();
retval = detectCookie(p.getInputStream(), expectedArguments); retval = detectCookie(p.getInputStream(), expectedArguments);
p.waitFor(); p.waitFor();
...@@ -167,7 +164,6 @@ public class Arrrghs{ ...@@ -167,7 +164,6 @@ public class Arrrghs{
} }
} }
if (_debug) System.out.println("Starting Arrrghs tests"); if (_debug) System.out.println("Starting Arrrghs tests");
// Basic test // Basic test
if (!doExec("-a -b -c -d")) exitValue++; if (!doExec("-a -b -c -d")) exitValue++;
......
#!/bin/sh #!/bin/sh
# @test Arrrghs.sh # @test Arrrghs.sh
# @bug 5030233 6214916 6356475 6571029 # @bug 5030233 6214916 6356475 6571029 6684582
# @build Arrrghs # @build Arrrghs
# @run shell Arrrghs.sh # @run shell Arrrghs.sh
# @summary Argument parsing validation. # @summary Argument parsing validation.
# @author Joseph E. Kowalski # @author Joseph E. Kowalski
# #
# Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. # Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
# #
# This code is free software; you can redistribute it and/or modify it # This code is free software; you can redistribute it and/or modify it
...@@ -103,6 +103,44 @@ TestHelp() { ...@@ -103,6 +103,44 @@ TestHelp() {
fi fi
} }
#
# Test to ensure that a missing main class is indicated in the error message
#
TestMissingMainClass() {
# First create a small jar file with no main
printf "public class Foo {}\n" > Foo.java
$TESTJAVA/bin/javac Foo.java
if [ $? -ne 0 ]; then
printf "Error: compilation of Foo.java failed\n"
exit 1
fi
printf "Main-Class: Bar\n" > manifest
$TESTJAVA/bin/jar -cvfm some.jar manifest Foo.class
if [ ! -f some.jar ]; then
printf "Error: did not find some.jar\n"
exit 1
fi
# test a non-existence main-class using -jar
mess="`$TESTJAVA/bin/java -jar some.jar 2>&1 1>/dev/null`"
echo $mess | grep 'Bar' 2>&1 > /dev/null
if [ $? -ne 0 ]; then
printf "Error: did not find main class missing message\n"
exit 1
fi
# test a non-existent main-class using classpath
mess="`$TESTJAVA/bin/java -cp some.jar Bar 2>&1 1>/dev/null`"
echo $mess | grep 'Bar' 2>&1 > /dev/null
if [ $? -ne 0 ]; then
printf "Error: did not find main class missing message\n"
exit 1
fi
# cleanup
rm -f some.jar Foo.* manifest
}
# #
# Main processing: # Main processing:
# #
...@@ -117,6 +155,7 @@ TestCP javac -cp ...@@ -117,6 +155,7 @@ TestCP javac -cp
TestCP javac -classpath TestCP javac -classpath
TestXUsage TestXUsage
TestHelp TestHelp
TestMissingMainClass
# #
# Tests for 6214916 # Tests for 6214916
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册