This commit is contained in:
Chris Hegarty 2013-10-15 09:27:32 +01:00
commit 766e77499d
106 changed files with 2154 additions and 1655 deletions

View File

@ -130,11 +130,13 @@ $(CLASSDESTDIR)/%_Stub.class: $(CLASSDESTDIR)/%.class
$(RMIC) -classpath "$(CLASSDESTDIR)" \
-d $(CLASSDESTDIR) \
-iiop -v1.2 \
-emitPermissionCheck \
$(subst /,.,$(<:$(CLASSDESTDIR)/%.class=%))
$(RMIC) $(HOTSPOT_INTERPRETER_FLAG) -classpath "$(CLASSDESTDIR)" \
-d $(CLASSDESTDIR) \
-iiop -v1.2 \
-standardPackage \
-emitPermissionCheck \
$(subst /,.,$(<:$(CLASSDESTDIR)/%.class=%))
@$(java-vm-cleanup)

View File

@ -57,7 +57,7 @@ SUNWprivate_1.1 {
Java_sun_management_GcInfoBuilder_fillGcAttributeInfo;
Java_sun_management_GcInfoBuilder_getLastGcInfo0;
Java_sun_management_GcInfoBuilder_getNumGcExtAttributes;
Java_sun_management_HotSpotDiagnostic_dumpHeap;
Java_sun_management_HotSpotDiagnostic_dumpHeap0;
Java_sun_management_HotspotThread_getInternalThreadCount;
Java_sun_management_HotspotThread_getInternalThreadTimes0;
Java_sun_management_MemoryImpl_getMemoryManagers0;

View File

@ -1,28 +0,0 @@
#
# Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
FILES_AWT_objc = \
$(TARGDIR)MacOSXResourceBundle.m

View File

@ -1,29 +0,0 @@
#
# Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# FILES_export definitions for Mac OS X
FILES_export += \
com/apple/resources/MacOSXResourceBundle.java

View File

@ -145,8 +145,6 @@ ifeq ($(PLATFORM), macosx)
#
# Files
#
include FILES_c_macosx.gmk
include FILES_export_macosx.gmk
FILES_objc = $(FILES_AWT_objc)
OTHER_LDLIBS = -lmlib_image $(JVMLIB) $(LIBM) \

View File

@ -52,8 +52,7 @@ endif
ifeq ($(OPENJDK_TARGET_OS), macosx)
ORIGIN_ARG:=$(call SET_EXECUTABLE_ORIGIN)
else
ORIGIN_ARG:=$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/lib$(OPENJDK_TARGET_CPU_LIBDIR)/jli) \
$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/jre/lib$(OPENJDK_TARGET_CPU_LIBDIR)/jli)
ORIGIN_ARG:=$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/lib$(OPENJDK_TARGET_CPU_LIBDIR)/jli)
endif
#
@ -62,8 +61,7 @@ endif
# devloper documentation of JAWT and what worked with OpenJDK6.
#
ifneq ($(findstring $(OPENJDK_TARGET_OS), linux solaris),)
ORIGIN_ARG+=$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/lib$(OPENJDK_TARGET_CPU_LIBDIR)) \
$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/jre/lib$(OPENJDK_TARGET_CPU_LIBDIR))
ORIGIN_ARG+=$(call SET_EXECUTABLE_ORIGIN,$(ORIGIN_ROOT)/lib$(OPENJDK_TARGET_CPU_LIBDIR))
endif
define SetupLauncher

View File

@ -559,11 +559,7 @@ endif
ifeq ($(OPENJDK_TARGET_OS),macosx)
LIBAWT_FILES += awt_LoadLibrary.c img_colors.c
LIBAWT_DIRS += $(JDK_TOPDIR)/src/macosx/native/com/apple/resources
LIBAWT_FILES += awt_LoadLibrary.c MacOSXResourceBundle.m
LIBAWT_CFLAGS += -F/System/Library/Frameworks/JavaVM.framework/Frameworks
LIBAWT_MacOSXResourceBundle.m_CFLAGS:=-O0
endif
ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_ARCH), solaris-sparc)

View File

@ -238,6 +238,11 @@ ifeq ($(OPENJDK_TARGET_OS), linux)
JDK_LIB_FILES += jexec
endif
ifneq ($(findstring $(OPENJDK_TARGET_OS), linux solaris),) # If Linux or Solaris
JDK_LIB_FILES += $(LIBRARY_PREFIX)jli$(SHARED_LIBRARY_SUFFIX) \
$(LIBRARY_PREFIX)jawt$(SHARED_LIBRARY_SUFFIX)
endif
# Find all files to copy from $(JDK_OUTPUTDIR)/lib
# Jar files are not expected to be here
ALL_JDKOUT_LIB_LIST := $(call not-containing,_the.,$(filter-out %.jar,\

View File

@ -57,7 +57,7 @@ SUNWprivate_1.1 {
Java_sun_management_GcInfoBuilder_fillGcAttributeInfo;
Java_sun_management_GcInfoBuilder_getLastGcInfo0;
Java_sun_management_GcInfoBuilder_getNumGcExtAttributes;
Java_sun_management_HotSpotDiagnostic_dumpHeap;
Java_sun_management_HotSpotDiagnostic_dumpHeap0;
Java_sun_management_HotspotThread_getInternalThreadCount;
Java_sun_management_HotspotThread_getInternalThreadTimes0;
Java_sun_management_MemoryImpl_getMemoryManagers0;

View File

@ -37,8 +37,6 @@ import javax.swing.plaf.basic.BasicLookAndFeel;
import sun.swing.*;
import apple.laf.*;
import com.apple.resources.MacOSXResourceBundle;
public class AquaLookAndFeel extends BasicLookAndFeel {
static final String sOldPropertyPrefix = "com.apple.macos."; // old prefix for things like 'useScreenMenuBar'
static final String sPropertyPrefix = "apple.laf."; // new prefix for things like 'useScreenMenuBar'
@ -252,7 +250,7 @@ public class AquaLookAndFeel extends BasicLookAndFeel {
table.setDefaultLocale(Locale.getDefault());
table.addResourceBundle(PKG_PREFIX + "resources.aqua");
try {
final ResourceBundle aquaProperties = MacOSXResourceBundle.getMacResourceBundle(PKG_PREFIX + "resources.aqua");
final ResourceBundle aquaProperties = ResourceBundle.getBundle(PKG_PREFIX + "resources.aqua");
final Enumeration<String> propertyKeys = aquaProperties.getKeys();
while (propertyKeys.hasMoreElements()) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -29,6 +29,7 @@ import java.awt.*;
import java.awt.image.*;
import java.lang.ref.SoftReference;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
@ -41,56 +42,68 @@ import sun.awt.AppContext;
import sun.lwawt.macosx.CImage;
import sun.lwawt.macosx.CImage.Creator;
import sun.lwawt.macosx.CPlatformWindow;
import sun.misc.Launcher;
import sun.reflect.misc.ReflectUtil;
import sun.security.action.GetPropertyAction;
import sun.swing.SwingUtilities2;
import com.apple.laf.AquaImageFactory.SlicedImageControl;
public class AquaUtils {
final static String ANIMATIONS_SYSTEM_PROPERTY = "swing.enableAnimations";
final class AquaUtils {
/*
private static final String ANIMATIONS_PROPERTY = "swing.enableAnimations";
/**
* Suppresses default constructor, ensuring non-instantiability.
*/
private AquaUtils() {
}
/**
* Convenience function for determining ComponentOrientation. Helps us
* avoid having Munge directives throughout the code.
*/
public static boolean isLeftToRight(final Component c) {
static boolean isLeftToRight(final Component c) {
return c.getComponentOrientation().isLeftToRight();
}
public static void enforceComponentOrientation(Component c, ComponentOrientation orientation) {
static void enforceComponentOrientation(final Component c, final ComponentOrientation orientation) {
c.setComponentOrientation(orientation);
if (c instanceof Container) {
for (Component child : ((Container)c).getComponents()) {
for (final Component child : ((Container)c).getComponents()) {
enforceComponentOrientation(child, orientation);
}
}
}
private static CImage.Creator getCImageCreatorInternal() {
return java.security.AccessController.doPrivileged(new PrivilegedAction<CImage.Creator>() {
private static Creator getCImageCreatorInternal() {
return AccessController.doPrivileged(new PrivilegedAction<Creator>() {
@Override
public Creator run() {
try {
final Method getCreatorMethod = CImage.class.getDeclaredMethod("getCreator", new Class[] {});
getCreatorMethod.setAccessible(true);
return (CImage.Creator)getCreatorMethod.invoke(null, new Object[] {});
} catch (final Exception e) {
return (Creator)getCreatorMethod.invoke(null, new Object[] {});
} catch (final Exception ignored) {
return null;
}
}
});
}
private static final RecyclableSingleton<CImage.Creator> cImageCreator = new RecyclableSingleton<CImage.Creator>() {
private static final RecyclableSingleton<Creator> cImageCreator = new RecyclableSingleton<Creator>() {
@Override
protected Creator getInstance() {
return getCImageCreatorInternal();
}
};
static CImage.Creator getCImageCreator() {
static Creator getCImageCreator() {
return cImageCreator.get();
}
protected static Image generateSelectedDarkImage(final Image image) {
static Image generateSelectedDarkImage(final Image image) {
final ImageProducer prod = new FilteredImageSource(image.getSource(), new IconImageFilter() {
@Override
int getGreyFor(final int gray) {
return gray * 75 / 100;
}
@ -98,8 +111,9 @@ public class AquaUtils {
return Toolkit.getDefaultToolkit().createImage(prod);
}
protected static Image generateDisabledImage(final Image image) {
static Image generateDisabledImage(final Image image) {
final ImageProducer prod = new FilteredImageSource(image.getSource(), new IconImageFilter() {
@Override
int getGreyFor(final int gray) {
return 255 - ((255 - gray) * 65 / 100);
}
@ -107,19 +121,20 @@ public class AquaUtils {
return Toolkit.getDefaultToolkit().createImage(prod);
}
protected static Image generateLightenedImage(final Image image, final int percent) {
static Image generateLightenedImage(final Image image, final int percent) {
final GrayFilter filter = new GrayFilter(true, percent);
final ImageProducer prod = new FilteredImageSource(image.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(prod);
}
static abstract class IconImageFilter extends RGBImageFilter {
public IconImageFilter() {
private abstract static class IconImageFilter extends RGBImageFilter {
IconImageFilter() {
super();
canFilterIndexColorModel = true;
}
public int filterRGB(final int x, final int y, final int rgb) {
@Override
public final int filterRGB(final int x, final int y, final int rgb) {
final int red = (rgb >> 16) & 0xff;
final int green = (rgb >> 8) & 0xff;
final int blue = rgb & 0xff;
@ -135,14 +150,14 @@ public class AquaUtils {
return result;
}
abstract int getGreyFor(final int gray);
abstract int getGreyFor(int gray);
}
public abstract static class RecyclableObject<T> {
protected SoftReference<T> objectRef = null;
abstract static class RecyclableObject<T> {
private SoftReference<T> objectRef;
public T get() {
T referent = null;
T get() {
T referent;
if (objectRef != null && (referent = objectRef.get()) != null) return referent;
referent = create();
objectRef = new SoftReference<T>(referent);
@ -152,8 +167,8 @@ public class AquaUtils {
protected abstract T create();
}
public abstract static class RecyclableSingleton<T> {
public T get() {
abstract static class RecyclableSingleton<T> {
final T get() {
final AppContext appContext = AppContext.getAppContext();
SoftReference<T> ref = (SoftReference<T>) appContext.get(this);
if (ref != null) {
@ -166,38 +181,36 @@ public class AquaUtils {
return object;
}
public void reset() {
AppContext appContext = AppContext.getAppContext();
appContext.remove(this);
void reset() {
AppContext.getAppContext().remove(this);
}
protected abstract T getInstance();
abstract T getInstance();
}
public static class RecyclableSingletonFromDefaultConstructor<T> extends RecyclableSingleton<T> {
protected final Class<T> clazz;
static class RecyclableSingletonFromDefaultConstructor<T> extends RecyclableSingleton<T> {
private final Class<T> clazz;
public RecyclableSingletonFromDefaultConstructor(final Class<T> clazz) {
RecyclableSingletonFromDefaultConstructor(final Class<T> clazz) {
this.clazz = clazz;
}
protected T getInstance() {
@Override
T getInstance() {
try {
ReflectUtil.checkPackageAccess(clazz);
return clazz.newInstance();
} catch (final InstantiationException e) {
e.printStackTrace();
} catch (final IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException | IllegalAccessException ignored) {
}
return null;
}
}
public abstract static class LazyKeyedSingleton<K, V> {
protected Map<K, V> refs;
abstract static class LazyKeyedSingleton<K, V> {
private Map<K, V> refs;
public V get(final K key) {
if (refs == null) refs = new HashMap<K, V>();
V get(final K key) {
if (refs == null) refs = new HashMap<>();
final V cachedValue = refs.get(key);
if (cachedValue != null) return cachedValue;
@ -207,44 +220,45 @@ public class AquaUtils {
return value;
}
protected abstract V getInstance(final K key);
protected abstract V getInstance(K key);
}
static final RecyclableSingleton<Boolean> enableAnimations = new RecyclableSingleton<Boolean>() {
private static final RecyclableSingleton<Boolean> enableAnimations = new RecyclableSingleton<Boolean>() {
@Override
protected Boolean getInstance() {
final String sizeProperty = (String)java.security.AccessController.doPrivileged((PrivilegedAction<?>)new sun.security.action.GetPropertyAction(ANIMATIONS_SYSTEM_PROPERTY));
return new Boolean(!"false".equals(sizeProperty)); // should be true by default
final String sizeProperty = (String) AccessController.doPrivileged((PrivilegedAction<?>)new GetPropertyAction(
ANIMATIONS_PROPERTY));
return !"false".equals(sizeProperty); // should be true by default
}
};
static boolean animationsEnabled() {
private static boolean animationsEnabled() {
return enableAnimations.get();
}
static final int MENU_BLINK_DELAY = 50; // 50ms == 3/60 sec, according to the spec
protected static void blinkMenu(final Selectable selectable) {
private static final int MENU_BLINK_DELAY = 50; // 50ms == 3/60 sec, according to the spec
static void blinkMenu(final Selectable selectable) {
if (!animationsEnabled()) return;
try {
selectable.paintSelected(false);
Thread.sleep(MENU_BLINK_DELAY);
selectable.paintSelected(true);
Thread.sleep(MENU_BLINK_DELAY);
} catch (final InterruptedException e) { }
} catch (final InterruptedException ignored) { }
}
interface Selectable {
void paintSelected(final boolean selected);
void paintSelected(boolean selected);
}
interface JComponentPainter {
public void paint(JComponent c, Graphics g, int x, int y, int w, int h);
void paint(JComponent c, Graphics g, int x, int y, int w, int h);
}
interface Painter {
public void paint(final Graphics g, int x, int y, int w, int h);
void paint(Graphics g, int x, int y, int w, int h);
}
public static void paintDropShadowText(final Graphics g, final JComponent c, final Font font, final FontMetrics metrics, final int x, final int y, final int offsetX, final int offsetY, final Color textColor, final Color shadowColor, final String text) {
static void paintDropShadowText(final Graphics g, final JComponent c, final Font font, final FontMetrics metrics, final int x, final int y, final int offsetX, final int offsetY, final Color textColor, final Color shadowColor, final String text) {
g.setFont(font);
g.setColor(shadowColor);
SwingUtilities2.drawString(c, g, text, x + offsetX, y + offsetY + metrics.getAscent());
@ -252,22 +266,22 @@ public class AquaUtils {
SwingUtilities2.drawString(c, g, text, x, y + metrics.getAscent());
}
public static class ShadowBorder implements Border {
final Painter prePainter;
final Painter postPainter;
static class ShadowBorder implements Border {
private final Painter prePainter;
private final Painter postPainter;
final int offsetX;
final int offsetY;
final float distance;
final int blur;
final Insets insets;
final ConvolveOp blurOp;
private final int offsetX;
private final int offsetY;
private final float distance;
private final int blur;
private final Insets insets;
private final ConvolveOp blurOp;
public ShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur) {
ShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur) {
this.prePainter = prePainter; this.postPainter = postPainter;
this.offsetX = offsetX; this.offsetY = offsetY; this.distance = distance; this.blur = blur;
final int halfBlur = blur / 2;
this.insets = new Insets(halfBlur - offsetY, halfBlur - offsetX, halfBlur + offsetY, halfBlur + offsetX);
insets = new Insets(halfBlur - offsetY, halfBlur - offsetX, halfBlur + offsetY, halfBlur + offsetX);
final float blurry = intensity / (blur * blur);
final float[] blurKernel = new float[blur * blur];
@ -275,14 +289,17 @@ public class AquaUtils {
blurOp = new ConvolveOp(new Kernel(blur, blur, blurKernel));
}
public boolean isBorderOpaque() {
@Override
public final boolean isBorderOpaque() {
return false;
}
public Insets getBorderInsets(final Component c) {
@Override
public final Insets getBorderInsets(final Component c) {
return insets;
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
final BufferedImage img = new BufferedImage(width + blur * 2, height + blur * 2, BufferedImage.TYPE_INT_ARGB_PRE);
paintToImage(img, x, y, width, height);
@ -290,7 +307,7 @@ public class AquaUtils {
g.drawImage(img, -blur, -blur, null);
}
protected void paintToImage(final BufferedImage img, final int x, final int y, final int width, final int height) {
private void paintToImage(final BufferedImage img, final int x, final int y, final int width, final int height) {
// clear the prior image
Graphics2D imgG = (Graphics2D)img.getGraphics();
imgG.setComposite(AlphaComposite.Clear);
@ -319,10 +336,10 @@ public class AquaUtils {
}
}
public static class SlicedShadowBorder extends ShadowBorder {
final SlicedImageControl slices;
static class SlicedShadowBorder extends ShadowBorder {
private final SlicedImageControl slices;
public SlicedShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur, final int templateWidth, final int templateHeight, final int leftCut, final int topCut, final int rightCut, final int bottomCut) {
SlicedShadowBorder(final Painter prePainter, final Painter postPainter, final int offsetX, final int offsetY, final float distance, final float intensity, final int blur, final int templateWidth, final int templateHeight, final int leftCut, final int topCut, final int rightCut, final int bottomCut) {
super(prePainter, postPainter, offsetX, offsetY, distance, intensity, blur);
final BufferedImage i = new BufferedImage(templateWidth, templateHeight, BufferedImage.TYPE_INT_ARGB_PRE);
@ -331,15 +348,12 @@ public class AquaUtils {
slices = new SlicedImageControl(i, leftCut, topCut, rightCut, bottomCut, false);
}
@Override
public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
slices.paint(g, x, y, width, height);
}
}
public interface NineSliceMetricsProvider {
}
// static void debugFrame(String name, Image image) {
// JFrame f = new JFrame(name);
// f.setContentPane(new JLabel(new ImageIcon(image)));
@ -350,28 +364,30 @@ public class AquaUtils {
// special casing naughty applications, like InstallAnywhere
// <rdar://problem/4851533> REGR: JButton: Myst IV: the buttons of 1.0.3 updater have redraw issue
static boolean shouldUseOpaqueButtons() {
final ClassLoader launcherClassLoader = sun.misc.Launcher.getLauncher().getClassLoader();
final ClassLoader launcherClassLoader = Launcher.getLauncher().getClassLoader();
if (classExists(launcherClassLoader, "com.installshield.wizard.platform.macosx.MacOSXUtils")) return true;
return false;
}
static boolean classExists(final ClassLoader classLoader, final String clazzName) {
private static boolean classExists(final ClassLoader classLoader, final String clazzName) {
try {
return Class.forName(clazzName, false, classLoader) != null;
} catch (final Throwable e) { }
} catch (final Throwable ignored) { }
return false;
}
private static RecyclableSingleton<Method> getJComponentGetFlagMethod = new RecyclableSingleton<Method>() {
private static final RecyclableSingleton<Method> getJComponentGetFlagMethod = new RecyclableSingleton<Method>() {
@Override
protected Method getInstance() {
return java.security.AccessController.doPrivileged(
return AccessController.doPrivileged(
new PrivilegedAction<Method>() {
@Override
public Method run() {
try {
final Method method = JComponent.class.getDeclaredMethod("getFlag", new Class[] { int.class });
method.setAccessible(true);
return method;
} catch (final Throwable e) {
} catch (final Throwable ignored) {
return null;
}
}
@ -380,18 +396,18 @@ public class AquaUtils {
}
};
private static final Integer OPAQUE_SET_FLAG = new Integer(24); // private int JComponent.OPAQUE_SET
protected static boolean hasOpaqueBeenExplicitlySet(final JComponent c) {
private static final Integer OPAQUE_SET_FLAG = 24; // private int JComponent.OPAQUE_SET
static boolean hasOpaqueBeenExplicitlySet(final JComponent c) {
final Method method = getJComponentGetFlagMethod.get();
if (method == null) return false;
try {
return Boolean.TRUE.equals(method.invoke(c, OPAQUE_SET_FLAG));
} catch (final Throwable e) {
} catch (final Throwable ignored) {
return false;
}
}
protected static boolean isWindowTextured(final Component c) {
private static boolean isWindowTextured(final Component c) {
if (!(c instanceof JComponent)) {
return false;
}
@ -412,13 +428,12 @@ public class AquaUtils {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), 0);
}
protected static void fillRect(final Graphics g, final Component c) {
static void fillRect(final Graphics g, final Component c) {
fillRect(g, c, c.getBackground(), 0, 0, c.getWidth(), c.getHeight());
}
protected static void fillRect(final Graphics g, final Component c,
final Color color, final int x, final int y,
final int w, final int h) {
static void fillRect(final Graphics g, final Component c, final Color color,
final int x, final int y, final int w, final int h) {
if (!(g instanceof Graphics2D)) {
return;
}

View File

@ -36,7 +36,10 @@ import sun.awt.SunToolkit;
import sun.lwawt.LWToolkit;
import sun.lwawt.macosx.*;
class ScreenMenu extends Menu implements ContainerListener, ComponentListener, ScreenMenuPropertyHandler {
final class ScreenMenu extends Menu
implements ContainerListener, ComponentListener,
ScreenMenuPropertyHandler {
static {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
@ -48,20 +51,22 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
}
// screen menu stuff
public static native long addMenuListeners(ScreenMenu listener, long nativeMenu);
public static native void removeMenuListeners(long modelPtr);
private static native long addMenuListeners(ScreenMenu listener, long nativeMenu);
private static native void removeMenuListeners(long modelPtr);
long fModelPtr = 0;
private transient long fModelPtr;
Hashtable<Component, MenuItem> fItems;
JMenu fInvoker;
private final Hashtable<Component, MenuItem> fItems;
private final JMenu fInvoker;
Component fLastMouseEventTarget;
Rectangle fLastTargetRect;
private Component fLastMouseEventTarget;
private Rectangle fLastTargetRect;
private volatile Rectangle[] fItemBounds;
private ScreenMenuPropertyListener fPropertyListener;
// Array of child hashes used to see if we need to recreate the Menu.
int childHashArray[];
private int childHashArray[];
ScreenMenu(final JMenu invoker) {
super(invoker.getText());
@ -74,25 +79,12 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
updateItems();
}
// I'm always 'visible', but never on screen
static class ScreenMenuComponent extends Container {
public boolean isVisible() { return true; }
public boolean isShowing() { return true; }
public void setVisible(final boolean b) {}
public void show() {}
}
ScreenMenuComponent makeScreenMenuComponent() {
return new ScreenMenuComponent();
}
/**
* Determine if we need to tear down the Menu and re-create it, since the contents may have changed in the Menu opened listener and
* we do not get notified of it, because EDT is busy in our code. We only need to update if the menu contents have changed in some
* way, such as the number of menu items, the text of the menuitems, icon, shortcut etc.
*/
static boolean needsUpdate(final Component items[], final int childHashArray[]) {
private static boolean needsUpdate(final Component items[], final int childHashArray[]) {
if (items == null || childHashArray == null) {
return true;
}
@ -112,7 +104,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
* Used to recreate the AWT based Menu structure that implements the Screen Menu.
* Also computes hashcode and stores them so that we can compare them later in needsUpdate.
*/
void updateItems() {
private void updateItems() {
final int count = fInvoker.getMenuComponentCount();
final Component[] items = fInvoker.getMenuComponents();
if (needsUpdate(items, childHashArray)) {
@ -163,16 +155,14 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
LWCToolkit.invokeAndWait(new Runnable() {
public void run() {
invoker.setSelected(false);
// Null out the tracking rectangles and the array.
// Null out the tracking rectangles and the array.
if (fItemBounds != null) {
for (int i = 0; i < fItemBounds.length; i++) {
fItemBounds[i] = null;
}
for (int i = 0; i < fItemBounds.length; i++) {
fItemBounds[i] = null;
}
}
fItemBounds = null;
}
fItemBounds = null;
}
}, invoker);
} catch (final Exception e) {
e.printStackTrace();
@ -237,49 +227,56 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
});
}
ScreenMenuPropertyListener fPropertyListener;
@Override
public void addNotify() {
super.addNotify();
if (fModelPtr == 0) {
fInvoker.addContainerListener(this);
fInvoker.addComponentListener(this);
fPropertyListener = new ScreenMenuPropertyListener(this);
fInvoker.addPropertyChangeListener(fPropertyListener);
synchronized (getTreeLock()) {
super.addNotify();
if (fModelPtr == 0) {
fInvoker.addContainerListener(this);
fInvoker.addComponentListener(this);
fPropertyListener = new ScreenMenuPropertyListener(this);
fInvoker.addPropertyChangeListener(fPropertyListener);
final Icon icon = fInvoker.getIcon();
if (icon != null) {
this.setIcon(icon);
}
final Icon icon = fInvoker.getIcon();
if (icon != null) {
setIcon(icon);
}
final String tooltipText = fInvoker.getToolTipText();
if (tooltipText != null) {
this.setToolTipText(tooltipText);
}
final MenuComponentPeer peer = getPeer();
if (peer instanceof CMenu) {
final CMenu menu = (CMenu)peer;
final long nativeMenu = menu.getNativeMenu();
fModelPtr = addMenuListeners(this, nativeMenu);
final String tooltipText = fInvoker.getToolTipText();
if (tooltipText != null) {
setToolTipText(tooltipText);
}
final MenuComponentPeer peer = getPeer();
if (peer instanceof CMenu) {
final CMenu menu = (CMenu) peer;
final long nativeMenu = menu.getNativeMenu();
fModelPtr = addMenuListeners(this, nativeMenu);
}
}
}
}
@Override
public void removeNotify() {
// Call super so that the NSMenu has been removed, before we release the delegate in removeMenuListeners
super.removeNotify();
fItems.clear();
if (fModelPtr != 0) {
removeMenuListeners(fModelPtr);
fModelPtr = 0;
fInvoker.removeContainerListener(this);
fInvoker.removeComponentListener(this);
fInvoker.removePropertyChangeListener(fPropertyListener);
synchronized (getTreeLock()) {
// Call super so that the NSMenu has been removed, before we release
// the delegate in removeMenuListeners
super.removeNotify();
fItems.clear();
if (fModelPtr != 0) {
removeMenuListeners(fModelPtr);
fModelPtr = 0;
fInvoker.removeContainerListener(this);
fInvoker.removeComponentListener(this);
fInvoker.removePropertyChangeListener(fPropertyListener);
}
}
}
/**
* Invoked when a component has been added to the container.
*/
@Override
public void componentAdded(final ContainerEvent e) {
addItem(e.getChild());
}
@ -287,23 +284,26 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
/**
* Invoked when a component has been removed from the container.
*/
@Override
public void componentRemoved(final ContainerEvent e) {
final Component child = e.getChild();
final MenuItem sm = fItems.get(child);
if (sm == null) return;
remove(sm);
fItems.remove(sm);
}
remove(sm);
fItems.remove(sm);
}
/**
* Invoked when the component's size changes.
*/
@Override
public void componentResized(final ComponentEvent e) {}
/**
* Invoked when the component's position changes.
*/
@Override
public void componentMoved(final ComponentEvent e) {}
/**
@ -311,6 +311,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
* See componentHidden - we should still have a MenuItem
* it just isn't inserted
*/
@Override
public void componentShown(final ComponentEvent e) {
setVisible(true);
}
@ -321,11 +322,12 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
* so we remove the ScreenMenuItem from the ScreenMenu
* but leave it in fItems
*/
@Override
public void componentHidden(final ComponentEvent e) {
setVisible(false);
}
public void setVisible(final boolean b) {
private void setVisible(final boolean b) {
// Tell our parent to add/remove us
final MenuContainer parent = getParent();
@ -333,20 +335,24 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
if (parent instanceof ScreenMenu) {
final ScreenMenu sm = (ScreenMenu)parent;
sm.setChildVisible(fInvoker, b);
}
}
}
}
@Override
public void setChildVisible(final JMenuItem child, final boolean b) {
fItems.remove(child);
updateItems();
}
@Override
public void setAccelerator(final KeyStroke ks) {}
// only check and radio items can be indeterminate
@Override
public void setIndeterminate(boolean indeterminate) { }
@Override
public void setToolTipText(final String text) {
final MenuComponentPeer peer = getPeer();
if (!(peer instanceof CMenuItem)) return;
@ -355,6 +361,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
cmi.setToolTipText(text);
}
@Override
public void setIcon(final Icon i) {
final MenuComponentPeer peer = getPeer();
if (!(peer instanceof CMenuItem)) return;
@ -374,9 +381,8 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
/**
* Gets a hashCode for a JMenu or JMenuItem or subclass so that we can compare for
* changes in the Menu.
*
*/
static int getHashCode(final Component m) {
private static int getHashCode(final Component m) {
int hashCode = m.hashCode();
if (m instanceof JMenuItem) {
@ -408,7 +414,7 @@ class ScreenMenu extends Menu implements ContainerListener, ComponentListener, S
return hashCode;
}
void addItem(final Component m) {
private void addItem(final Component m) {
if (!m.isVisible()) return;
MenuItem sm = fItems.get(m);

View File

@ -1,110 +0,0 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.apple.resources;
import java.security.*;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.io.*;
public class MacOSXResourceBundle extends PropertyResourceBundle {
MacOSXResourceBundle(InputStream stream) throws IOException {
super(stream);
}
void setItsParent(ResourceBundle rb) {
setParent(rb);
}
public static ResourceBundle getMacResourceBundle(String baseJavaBundle) throws Exception {
return getMacResourceBundle(baseJavaBundle, null);
}
public static ResourceBundle getMacResourceBundle(String baseJavaBundle, String filename) throws Exception {
LoadNativeBundleAction lnba = new LoadNativeBundleAction(baseJavaBundle, filename);
return (ResourceBundle)java.security.AccessController.doPrivileged(lnba);
}
}
class LoadNativeBundleAction implements PrivilegedExceptionAction {
String mBaseJavaBundle;
String mFilenameOverride;
LoadNativeBundleAction(String baseJavaBundle, String filenameOverride) {
mBaseJavaBundle = baseJavaBundle;
mFilenameOverride = filenameOverride;
}
public Object run() {
java.util.ResourceBundle returnValue = null;
MacOSXResourceBundle macOSrb = null;
// Load the Mac OS X resources.
// Use a base filename if we were given one. Otherwise, we will look for the last piece of the bundle path
// with '.properties' appended. Either way, the native method will take care of the extension.
String filename = mFilenameOverride;
if (filename == null) {
filename = mBaseJavaBundle.substring(mBaseJavaBundle.lastIndexOf('.') + 1);
}
File propsFile = null;
String propertyFileName = getPathToBundleFile(filename);
InputStream stream = null;
try {
propsFile = new File(propertyFileName);
stream = new FileInputStream(propsFile);
stream = new java.io.BufferedInputStream(stream);
macOSrb = new MacOSXResourceBundle(stream);
} catch (Exception e) {
//e.printStackTrace();
//System.out.println("Failed to create resources from application bundle. Using Java-based resources.");
} finally {
try {
if (stream != null) stream.close();
stream = null;
} catch (Exception e) {
e.printStackTrace();
}
}
returnValue = ResourceBundle.getBundle(mBaseJavaBundle);
// If we have a platform-specific bundle, make it the parent of the generic bundle, so failures propagate up to the parent.
if (returnValue != null) {
if (macOSrb != null) {
macOSrb.setItsParent(returnValue);
returnValue = macOSrb;
}
}
return returnValue;
}
private static native String getPathToBundleFile(String filename);
}

View File

@ -1,110 +0,0 @@
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#import <dlfcn.h>
#import <Cocoa/Cocoa.h>
#import <JavaNativeFoundation/JavaNativeFoundation.h>
#ifndef MAXPATHLEN
#define MAXPATHLEN PATH_MAX
#endif
static jboolean
GetPathFromCurrentBinary(char *buf, jint bufsize)
{
Dl_info dlinfo;
dladdr((void *)GetPathFromCurrentBinary, &dlinfo);
if (realpath(dlinfo.dli_fname, buf) == NULL) {
// fprintf(stderr, "Error: realpath(`%s') failed.\n", dlinfo.dli_fname);
return JNI_FALSE;
}
const char *libawt = "lib/libawt.dylib";
int strLen, libawtLen;
strLen = strlen(buf);
libawtLen = strlen(libawt);
if (strLen < libawtLen ||
strcmp(buf + strLen - libawtLen, libawt) != 0) {
return JNI_FALSE;
}
buf[strLen - libawtLen] = '\0';
return JNI_TRUE;
}
#define JAVA_DLL "libjava.dylib"
static jboolean
GetJREPath(char *buf, jint bufsize)
{
/* try to get the path from the current binary, if not, bail to the framework */
if (GetPathFromCurrentBinary(buf, bufsize) == JNI_TRUE) {
/* does the rest of the JRE exist? */
char libjava[MAXPATHLEN];
snprintf(libjava, MAXPATHLEN, "%s/lib/" JAVA_DLL, buf);
if (access(libjava, F_OK) == 0) {
return JNI_TRUE;
}
}
return JNI_FALSE;
}
static NSString *getRunningJavaBundle()
{
char path[MAXPATHLEN];
GetJREPath(path, MAXPATHLEN);
return [[NSString alloc] initWithFormat:@"%@/bundle", [NSString stringWithUTF8String:path]];
}
/*
* Class: com_apple_resources_LoadNativeBundleAction
* Method: getPathToBundleFile
* Signature: (Ljava/lang/String)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_com_apple_resources_LoadNativeBundleAction_getPathToBundleFile
(JNIEnv *env, jclass klass, jstring filename)
{
jstring returnVal = NULL;
if (filename == NULL) {
return NULL;
}
JNF_COCOA_ENTER(env);
NSBundle *javaBundle = [NSBundle bundleWithPath:getRunningJavaBundle()];
NSString *baseFilename = JNFJavaToNSString(env, filename);
NSString *propertyFilePath = [javaBundle pathForResource:baseFilename ofType:@"properties"];
if (propertyFilePath != nil) {
returnVal = JNFNSToJavaString(env, propertyFilePath);
}
JNF_COCOA_EXIT(env);
return returnVal;
}

View File

@ -271,22 +271,6 @@ javax.crypto.interfaces.DHPrivateKey, Serializable {
}
}
public String toString() {
String LINE_SEP = System.getProperty("line.separator");
StringBuffer strbuf
= new StringBuffer("SunJCE Diffie-Hellman Private Key:"
+ LINE_SEP + "x:" + LINE_SEP
+ Debug.toHexString(this.x)
+ LINE_SEP + "p:" + LINE_SEP
+ Debug.toHexString(this.p)
+ LINE_SEP + "g:" + LINE_SEP
+ Debug.toHexString(this.g));
if (this.l != 0)
strbuf.append(LINE_SEP + "l:" + LINE_SEP + " " + this.l);
return strbuf.toString();
}
private void parseKeyBits() throws InvalidKeyException {
try {
DerInputStream in = new DerInputStream(this.key);

View File

@ -53,7 +53,10 @@ public class Tracker {
public static void ObjectInit(Object obj)
{
if ( engaged != 0 ) {
if ( engaged != 0) {
if (obj == null) {
throw new IllegalArgumentException("Null object.");
}
nativeObjectInit(Thread.currentThread(), obj);
}
}
@ -66,7 +69,10 @@ public class Tracker {
public static void NewArray(Object obj)
{
if ( engaged != 0 ) {
if ( engaged != 0) {
if (obj == null) {
throw new IllegalArgumentException("Null object.");
}
nativeNewArray(Thread.currentThread(), obj);
}
}
@ -82,6 +88,14 @@ public class Tracker {
public static void CallSite(int cnum, int mnum)
{
if ( engaged != 0 ) {
if (cnum < 0) {
throw new IllegalArgumentException("Negative class index");
}
if (mnum < 0) {
throw new IllegalArgumentException("Negative method index");
}
nativeCallSite(Thread.currentThread(), cnum, mnum);
}
}
@ -95,6 +109,14 @@ public class Tracker {
public static void ReturnSite(int cnum, int mnum)
{
if ( engaged != 0 ) {
if (cnum < 0) {
throw new IllegalArgumentException("Negative class index");
}
if (mnum < 0) {
throw new IllegalArgumentException("Negative method index");
}
nativeReturnSite(Thread.currentThread(), cnum, mnum);
}
}

View File

@ -1165,6 +1165,11 @@ public class JPEGImageReader extends ImageReader {
target = imRas;
}
int [] bandSizes = target.getSampleModel().getSampleSize();
for (int i = 0; i < bandSizes.length; i++) {
if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
throw new IIOException("Illegal band size: should be 0 < size <= 8");
}
}
/*
* If the process is sequential, and we have restart markers,

View File

@ -495,8 +495,8 @@ public class JPEGImageWriter extends ImageWriter {
// handle <= 8-bit samples. We now check the band sizes and throw
// an exception for images, such as USHORT_GRAY, with > 8 bits
// per sample.
if (bandSizes[i] > 8) {
throw new IIOException("Sample size must be <= 8");
if (bandSizes[i] <= 0 || bandSizes[i] > 8) {
throw new IIOException("Illegal band size: should be 0 < size <= 8");
}
// 4450894 part 2: We expand IndexColorModel images to full 24-
// or 32-bit in grabPixels() for each scanline. For indexed

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009,2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -36,13 +36,34 @@ import java.rmi.RemoteException;
import java.rmi.NoSuchObjectException;
import com.sun.jmx.remote.internal.IIOPProxy;
import java.io.SerializablePermission;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
/**
* An implementatin of IIOPProxy that simply delegates to the appropriate
* An implementation of IIOPProxy that simply delegates to the appropriate
* RMI-IIOP and CORBA APIs.
*/
public class IIOPProxyImpl implements IIOPProxy {
// special ACC used to initialize the IIOP stub
// the only allowed privilege is SerializablePermission("enableSubclassImplementation")
private static final AccessControlContext STUB_ACC;
static {
Permissions p = new Permissions();
p.add(new SerializablePermission("enableSubclassImplementation"));
STUB_ACC = new AccessControlContext(
new ProtectionDomain[]{
new ProtectionDomain(null, p)
}
);
}
public IIOPProxyImpl() { }
@Override
@ -113,7 +134,24 @@ public class IIOPProxyImpl implements IIOPProxy {
}
@Override
public Remote toStub(Remote obj) throws NoSuchObjectException {
return PortableRemoteObject.toStub(obj);
public Remote toStub(final Remote obj) throws NoSuchObjectException {
if (System.getSecurityManager() == null) {
return PortableRemoteObject.toStub(obj);
} else {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Remote>() {
@Override
public Remote run() throws Exception {
return PortableRemoteObject.toStub(obj);
}
}, STUB_ACC);
} catch (PrivilegedActionException e) {
if (e.getException() instanceof NoSuchObjectException) {
throw (NoSuchObjectException)e.getException();
}
throw new RuntimeException("Unexpected exception type", e.getException());
}
}
}
}

View File

@ -25,11 +25,12 @@
package com.sun.jndi.ldap;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.misc.SharedSecrets;
final class VersionHelper12 extends VersionHelper {
@ -82,12 +83,16 @@ final class VersionHelper12 extends VersionHelper {
}
Thread createThread(final Runnable r) {
final AccessControlContext acc = AccessController.getContext();
// 4290486: doPrivileged is needed to create a thread in
// an environment that restricts "modifyThreadGroup".
return AccessController.doPrivileged(
new PrivilegedAction<Thread>() {
public Thread run() {
return new Thread(r);
new PrivilegedAction<Thread>() {
public Thread run() {
return SharedSecrets.getJavaLangAccess()
.newThreadWithAcc(r, acc);
}
}
}
);
}
}

View File

@ -67,6 +67,11 @@ public interface HotSpotDiagnosticMXBean extends PlatformManagedObject {
* cannot be created, opened, or written to.
* @throws UnsupportedOperationException if this operation is not supported.
* @throws NullPointerException if <tt>outputFile</tt> is <tt>null</tt>.
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the named file
* or the caller does not have ManagmentPermission("control").
*/
public void dumpHeap(String outputFile, boolean live) throws java.io.IOException;

View File

@ -84,7 +84,7 @@ class AllClassesQuery extends QueryHandler {
lastPackage = pkg;
printClass(clazz);
if (clazz.getId() != -1) {
out.print(" [" + clazz.getIdString() + "]");
print(" [" + clazz.getIdString() + "]");
}
out.println("<br>");
}

View File

@ -112,12 +112,12 @@ class ClassQuery extends QueryHandler {
out.println("<h2>Instances</h2>");
printAnchorStart();
out.print("instances/" + encodeForURL(clazz));
print("instances/" + encodeForURL(clazz));
out.print("\">");
out.println("Exclude subclasses</a><br>");
printAnchorStart();
out.print("allInstances/" + encodeForURL(clazz));
print("allInstances/" + encodeForURL(clazz));
out.print("\">");
out.println("Include subclasses</a><br>");
@ -126,19 +126,19 @@ class ClassQuery extends QueryHandler {
out.println("<h2>New Instances</h2>");
printAnchorStart();
out.print("newInstances/" + encodeForURL(clazz));
print("newInstances/" + encodeForURL(clazz));
out.print("\">");
out.println("Exclude subclasses</a><br>");
printAnchorStart();
out.print("allNewInstances/" + encodeForURL(clazz));
print("allNewInstances/" + encodeForURL(clazz));
out.print("\">");
out.println("Include subclasses</a><br>");
}
out.println("<h2>References summary by Type</h2>");
printAnchorStart();
out.print("refsByType/" + encodeForURL(clazz));
print("refsByType/" + encodeForURL(clazz));
out.print("\">");
out.println("References summary by type</a>");

View File

@ -41,21 +41,17 @@ package com.sun.tools.hat.internal.server;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.Writer;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedOutputStream;
import com.sun.tools.hat.internal.model.Snapshot;
import com.sun.tools.hat.internal.oql.OQLEngine;
import com.sun.tools.hat.internal.util.Misc;
public class HttpReader implements Runnable {
@ -87,7 +83,7 @@ public class HttpReader implements Runnable {
outputError("Protocol error");
}
int data;
StringBuffer queryBuf = new StringBuffer();
StringBuilder queryBuf = new StringBuilder();
while ((data = in.read()) != -1 && data != ' ') {
char ch = (char) data;
queryBuf.append(ch);
@ -217,7 +213,7 @@ public class HttpReader implements Runnable {
private void outputError(String msg) {
out.println();
out.println("<html><body bgcolor=\"#ffffff\">");
out.println(msg);
out.println(Misc.encodeHtml(msg));
out.println("</body></html>");
}

View File

@ -102,7 +102,7 @@ class InstancesCountQuery extends QueryHandler {
int count = clazz.getInstancesCount(false);
print("" + count);
printAnchorStart();
out.print("instances/" + encodeForURL(classes[i]));
print("instances/" + encodeForURL(classes[i]));
out.print("\"> ");
if (count == 1) {
print("instance");
@ -121,7 +121,7 @@ class InstancesCountQuery extends QueryHandler {
}
print("(");
printAnchorStart();
out.print("newInstances/" + encodeForURL(classes[i]));
print("newInstances/" + encodeForURL(classes[i]));
out.print("\">");
print("" + newInst + " new");
out.print("</a>) ");

View File

@ -54,10 +54,7 @@ class OQLHelp extends QueryHandler {
out.print((char)ch);
}
} catch (Exception exp) {
out.println(exp.getMessage());
out.println("<pre>");
exp.printStackTrace(out);
out.println("</pre>");
printException(exp);
}
}
}

View File

@ -32,10 +32,7 @@
package com.sun.tools.hat.internal.server;
import com.sun.tools.hat.internal.model.*;
import com.sun.tools.hat.internal.oql.*;
import com.sun.tools.hat.internal.util.ArraySorter;
import com.sun.tools.hat.internal.util.Comparer;
/**
* This handles Object Query Language (OQL) queries.
@ -68,7 +65,7 @@ class OQLQuery extends QueryHandler {
out.println("<p align='center'>");
out.println("<textarea name='query' cols=80 rows=10>");
if (oql != null) {
out.println(oql);
println(oql);
}
out.println("</textarea>");
out.println("</p>");
@ -91,10 +88,7 @@ class OQLQuery extends QueryHandler {
try {
out.println(engine.toHtml(o));
} catch (Exception e) {
out.println(e.getMessage());
out.println("<pre>");
e.printStackTrace(out);
out.println("</pre>");
printException(e);
}
out.println("</td></tr>");
return false;
@ -102,10 +96,7 @@ class OQLQuery extends QueryHandler {
});
out.println("</table>");
} catch (OQLException exp) {
out.println(exp.getMessage());
out.println("<pre>");
exp.printStackTrace(out);
out.println("</pre>");
printException(exp);
}
}

View File

@ -36,6 +36,7 @@ import java.io.PrintWriter;
import com.sun.tools.hat.internal.model.*;
import com.sun.tools.hat.internal.util.Misc;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
@ -96,7 +97,7 @@ abstract class QueryHandler {
}
protected void error(String msg) {
out.println(msg);
println(msg);
}
protected void printAnchorStart() {
@ -160,7 +161,6 @@ abstract class QueryHandler {
out.println("null");
return;
}
String name = clazz.getName();
printAnchorStart();
out.print("class/");
print(encodeForURL(clazz));
@ -208,6 +208,15 @@ abstract class QueryHandler {
}
}
protected void printException(Throwable t) {
println(t.getMessage());
out.println("<pre>");
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
print(sw.toString());
out.println("</pre>");
}
protected void printHex(long addr) {
if (snapshot.getIdentifierSize() == 4) {
out.print(Misc.toHex((int)addr));
@ -223,4 +232,8 @@ abstract class QueryHandler {
protected void print(String str) {
out.print(Misc.encodeHtml(str));
}
protected void println(String str) {
out.println(Misc.encodeHtml(str));
}
}

View File

@ -89,7 +89,7 @@ public class RefsByTypeQuery extends QueryHandler {
out.println("<p align='center'>");
printClass(clazz);
if (clazz.getId() != -1) {
out.println("[" + clazz.getIdString() + "]");
println("[" + clazz.getIdString() + "]");
}
out.println("</p>");
@ -125,9 +125,9 @@ public class RefsByTypeQuery extends QueryHandler {
JavaClass clazz = classes[i];
out.println("<tr><td>");
out.print("<a href='/refsByType/");
out.print(clazz.getIdString());
print(clazz.getIdString());
out.print("'>");
out.print(clazz.getName());
print(clazz.getName());
out.println("</a>");
out.println("</td><td>");
out.println(map.get(clazz));

View File

@ -30,6 +30,9 @@ import java.nio.*;
import java.util.*;
import sun.awt.datatransfer.DataTransferer;
import sun.reflect.misc.ReflectUtil;
import static sun.security.util.SecurityConstants.GET_CLASSLOADER_PERMISSION;
/**
* A {@code DataFlavor} provides meta information about data. {@code DataFlavor}
@ -116,27 +119,33 @@ public class DataFlavor implements Externalizable, Cloneable {
ClassLoader fallback)
throws ClassNotFoundException
{
ClassLoader systemClassLoader = (ClassLoader)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
ClassLoader cl = Thread.currentThread().
getContextClassLoader();
return (cl != null)
? cl
: ClassLoader.getSystemClassLoader();
}
});
ReflectUtil.checkPackageAccess(className);
try {
return Class.forName(className, true, systemClassLoader);
} catch (ClassNotFoundException e2) {
if (fallback != null) {
return Class.forName(className, true, fallback);
} else {
throw new ClassNotFoundException(className);
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(GET_CLASSLOADER_PERMISSION);
}
ClassLoader loader = ClassLoader.getSystemClassLoader();
try {
// bootstrap class loader and system class loader if present
return Class.forName(className, true, loader);
}
catch (ClassNotFoundException exception) {
// thread context class loader if and only if present
loader = Thread.currentThread().getContextClassLoader();
if (loader != null) {
try {
return Class.forName(className, true, loader);
}
catch (ClassNotFoundException e) {
// fallback to user's class loader
}
}
}
} catch (SecurityException exception) {
// ignore secured class loaders
}
return Class.forName(className, true, fallback);
}
/*

View File

@ -42,6 +42,8 @@ import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.StreamCorruptedException;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.security.AccessController;
@ -224,6 +226,10 @@ public class Beans {
throw ex;
}
if (!Modifier.isPublic(cl.getModifiers())) {
throw new ClassNotFoundException("" + cl + " : no public access");
}
/*
* Try to instantiate the class.
*/

View File

@ -222,6 +222,9 @@ public class DefaultPersistenceDelegate extends PersistenceDelegate {
// Write out the properties of this instance.
private void initBean(Class<?> type, Object oldInstance, Object newInstance, Encoder out) {
for (Field field : type.getFields()) {
if (!ReflectUtil.isPackageAccessible(field.getDeclaringClass())) {
continue;
}
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod) || Modifier.isTransient(mod)) {
continue;

View File

@ -42,6 +42,7 @@ import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
@ -56,7 +57,7 @@ import javax.swing.plaf.ColorUIResource;
import sun.swing.PrintColorUIResource;
import java.util.Objects;
import static sun.reflect.misc.ReflectUtil.isPackageAccessible;
/*
* Like the <code>Intropector</code>, the <code>MetaData</code> class
@ -850,13 +851,15 @@ static final class java_awt_AWTKeyStroke_PersistenceDelegate extends Persistence
static class StaticFieldsPersistenceDelegate extends PersistenceDelegate {
protected void installFields(Encoder out, Class<?> cls) {
Field fields[] = cls.getFields();
for(int i = 0; i < fields.length; i++) {
Field field = fields[i];
// Don't install primitives, their identity will not be preserved
// by wrapping.
if (Object.class.isAssignableFrom(field.getType())) {
out.writeExpression(new Expression(field, "get", new Object[]{null}));
if (Modifier.isPublic(cls.getModifiers()) && isPackageAccessible(cls)) {
Field fields[] = cls.getFields();
for(int i = 0; i < fields.length; i++) {
Field field = fields[i];
// Don't install primitives, their identity will not be preserved
// by wrapping.
if (Object.class.isAssignableFrom(field.getType())) {
out.writeExpression(new Expression(field, "get", new Object[]{null}));
}
}
}
}

View File

@ -491,11 +491,12 @@ public class ObjectInputStream
public void defaultReadObject()
throws IOException, ClassNotFoundException
{
if (curContext == null) {
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to readObject");
}
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
bin.setBlockDataMode(false);
defaultReadFields(curObj, curDesc);
bin.setBlockDataMode(true);
@ -529,11 +530,12 @@ public class ObjectInputStream
public ObjectInputStream.GetField readFields()
throws IOException, ClassNotFoundException
{
if (curContext == null) {
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to readObject");
}
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
bin.setBlockDataMode(false);
GetFieldImpl getField = new GetFieldImpl(curDesc);
getField.readFields();
@ -1968,7 +1970,6 @@ public class ObjectInputStream
private void defaultReadFields(Object obj, ObjectStreamClass desc)
throws IOException
{
// REMIND: is isInstance check necessary?
Class<?> cl = desc.forClass();
if (cl != null && obj != null && !cl.isInstance(obj)) {
throw new ClassCastException();

View File

@ -431,11 +431,12 @@ public class ObjectOutputStream
* <code>OutputStream</code>
*/
public void defaultWriteObject() throws IOException {
if ( curContext == null ) {
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to writeObject");
}
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
bout.setBlockDataMode(false);
defaultWriteFields(curObj, curDesc);
bout.setBlockDataMode(true);
@ -453,11 +454,12 @@ public class ObjectOutputStream
*/
public ObjectOutputStream.PutField putFields() throws IOException {
if (curPut == null) {
if (curContext == null) {
SerialCallbackContext ctx = curContext;
if (ctx == null) {
throw new NotActiveException("not in call to writeObject");
}
Object curObj = curContext.getObj();
ObjectStreamClass curDesc = curContext.getDesc();
Object curObj = ctx.getObj();
ObjectStreamClass curDesc = ctx.getDesc();
curPut = new PutFieldImpl(curDesc);
}
return curPut;
@ -1517,7 +1519,11 @@ public class ObjectOutputStream
private void defaultWriteFields(Object obj, ObjectStreamClass desc)
throws IOException
{
// REMIND: perform conservative isInstance check here?
Class<?> cl = desc.forClass();
if (cl != null && obj != null && !cl.isInstance(obj)) {
throw new ClassCastException();
}
desc.checkDefaultSerialize();
int primDataSize = desc.getPrimDataSize();

View File

@ -1209,9 +1209,25 @@ public final class Class<T> implements java.io.Serializable,
* type, or void,then this method returns null.
*
* @return the declaring class for this class
* @throws SecurityException
* If a security manager, <i>s</i>, is present and the caller's
* class loader is not the same as or an ancestor of the class
* loader for the declaring class and invocation of {@link
* SecurityManager#checkPackageAccess s.checkPackageAccess()}
* denies access to the package of the declaring class
* @since JDK1.1
*/
public native Class<?> getDeclaringClass();
@CallerSensitive
public Class<?> getDeclaringClass() throws SecurityException {
final Class<?> candidate = getDeclaringClass0();
if (candidate != null)
candidate.checkPackageAccess(
ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
return candidate;
}
private native Class<?> getDeclaringClass0();
/**

View File

@ -57,6 +57,7 @@ import sun.misc.URLClassPath;
import sun.misc.VM;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
import sun.reflect.misc.ReflectUtil;
import sun.security.util.SecurityConstants;
/**
@ -486,6 +487,13 @@ public abstract class ClassLoader {
private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
if (ReflectUtil.isNonPublicProxyClass(cls)) {
for (Class intf: cls.getInterfaces()) {
checkPackageAccess(intf, pd);
}
return;
}
final String name = cls.getName();
final int i = name.lastIndexOf('.');
if (i != -1) {

View File

@ -26,6 +26,7 @@ package java.lang;
import java.io.*;
import java.lang.reflect.Executable;
import java.security.AccessControlContext;
import java.util.Properties;
import java.util.PropertyPermission;
import java.util.StringTokenizer;
@ -1254,6 +1255,9 @@ public final class System {
public String newStringUnsafe(char[] chars) {
return new String(chars, true);
}
public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {
return new Thread(target, acc);
}
});
}
}

View File

@ -340,6 +340,15 @@ class Thread implements Runnable {
sleep(millis);
}
/**
* Initializes a Thread with the current AccessControlContext.
* @see #init(ThreadGroup,Runnable,String,long,AccessControlContext)
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null);
}
/**
* Initializes a Thread.
*
@ -348,9 +357,11 @@ class Thread implements Runnable {
* @param name the name of the new Thread
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
* @param acc the AccessControlContext to inherit, or
* AccessController.getContext() if null
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
long stackSize, AccessControlContext acc) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
@ -396,7 +407,8 @@ class Thread implements Runnable {
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext = AccessController.getContext();
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (parent.inheritableThreadLocals != null)
@ -448,6 +460,14 @@ class Thread implements Runnable {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
/**
* Creates a new Thread that inherits the given AccessControlContext.
* This is not a public constructor.
*/
Thread(Runnable target, AccessControlContext acc) {
init(null, target, "Thread-" + nextThreadNum(), 0, acc);
}
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}

View File

@ -597,7 +597,7 @@ public class MethodHandles {
Lookup(Class<?> lookupClass) {
this(lookupClass, ALL_MODES);
// make sure we haven't accidentally picked up a privileged class:
checkUnprivilegedlookupClass(lookupClass);
checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
}
private Lookup(Class<?> lookupClass, int allowedModes) {
@ -651,7 +651,7 @@ public class MethodHandles {
// No permissions.
newModes = 0;
}
checkUnprivilegedlookupClass(requestedLookupClass);
checkUnprivilegedlookupClass(requestedLookupClass, newModes);
return new Lookup(requestedLookupClass, newModes);
}
@ -667,10 +667,19 @@ public class MethodHandles {
/** Package-private version of lookup which is trusted. */
static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
private static void checkUnprivilegedlookupClass(Class<?> lookupClass) {
private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
String name = lookupClass.getName();
if (name.startsWith("java.lang.invoke."))
throw newIllegalArgumentException("illegal lookupClass: "+lookupClass);
// For caller-sensitive MethodHandles.lookup()
// disallow lookup more restricted packages
if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
if (name.startsWith("java.") ||
(name.startsWith("sun.") && !name.startsWith("sun.invoke."))) {
throw newIllegalArgumentException("illegal lookupClass: " + lookupClass);
}
}
}
/**
@ -1759,6 +1768,12 @@ return mh1;
if (MethodHandleNatives.refKindIsField(refKind)) {
return getDirectFieldNoSecurityManager(refKind, defc, member);
} else if (MethodHandleNatives.refKindIsMethod(refKind)) {
if (defc == MethodHandle.class && refKind == REF_invokeVirtual) {
MethodHandle mh = findVirtualForMH(member.getName(), member.getMethodType());
if (mh != null) {
return mh;
}
}
return getDirectMethodNoSecurityManager(refKind, defc, member, lookupClass);
} else if (refKind == REF_newInvokeSpecial) {
return getDirectConstructorNoSecurityManager(defc, member);

View File

@ -347,11 +347,11 @@ public class Proxy implements java.io.Serializable {
* s.checkPermission} with
* {@code RuntimePermission("getClassLoader")} permission
* denies access.</li>
* <li> the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* <li> for each proxy interface, {@code intf},
* the caller's class loader is not the same as or an
* ancestor of the class loader for {@code intf} and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to any one of the
* given proxy interfaces.</li>
* s.checkPackageAccess()} denies access to {@code intf}.</li>
* </ul>
* @throws NullPointerException if the {@code interfaces} array
@ -680,11 +680,11 @@ public class Proxy implements java.io.Serializable {
* s.checkPermission} with
* {@code RuntimePermission("getClassLoader")} permission
* denies access;</li>
* <li> the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* <li> for each proxy interface, {@code intf},
* the caller's class loader is not the same as or an
* ancestor of the class loader for {@code intf} and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to any one of the
* given proxy interfaces.</li>
* s.checkPackageAccess()} denies access to {@code intf};</li>
* <li> any of the given proxy interfaces is non-public and the
* caller class is not in the same {@linkplain Package runtime package}
* as the non-public interface and the invocation of
@ -795,7 +795,14 @@ public class Proxy implements java.io.Serializable {
* @return the invocation handler for the proxy instance
* @throws IllegalArgumentException if the argument is not a
* proxy instance
* @throws SecurityException if a security manager, <em>s</em>, is present
* and the caller's class loader is not the same as or an
* ancestor of the class loader for the invocation handler
* and invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to the invocation
* handler's class.
*/
@CallerSensitive
public static InvocationHandler getInvocationHandler(Object proxy)
throws IllegalArgumentException
{
@ -806,8 +813,19 @@ public class Proxy implements java.io.Serializable {
throw new IllegalArgumentException("not a proxy instance");
}
Proxy p = (Proxy) proxy;
return p.h;
final Proxy p = (Proxy) proxy;
final InvocationHandler ih = p.h;
if (System.getSecurityManager() != null) {
Class<?> ihClass = ih.getClass();
Class<?> caller = Reflection.getCallerClass();
if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(),
ihClass.getClassLoader()))
{
ReflectUtil.checkPackageAccess(ihClass);
}
}
return ih;
}
private static native Class<?> defineClass0(ClassLoader loader, String name,

View File

@ -28,7 +28,10 @@ package java.net;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.Enumeration;
import java.util.Arrays;
/**
* This class represents an Internet Protocol version 6 (IPv6) address.
@ -177,37 +180,192 @@ class Inet6Address extends InetAddress {
*/
private transient int cached_scope_id; // 0
/**
* Holds a 128-bit (16 bytes) IPv6 address.
*
* @serial
*/
byte[] ipaddress;
private class Inet6AddressHolder {
/**
* scope_id. The scope specified when the object is created. If the object
* is created with an interface name, then the scope_id is not determined
* until the time it is needed.
*/
private int scope_id; // 0
private Inet6AddressHolder() {
ipaddress = new byte[INADDRSZ];
}
/**
* This will be set to true when the scope_id field contains a valid
* integer scope_id.
*/
private boolean scope_id_set; // false
private Inet6AddressHolder(
byte[] ipaddress, int scope_id, boolean scope_id_set,
NetworkInterface ifname, boolean scope_ifname_set)
{
this.ipaddress = ipaddress;
this.scope_id = scope_id;
this.scope_id_set = scope_id_set;
this.scope_ifname_set = scope_ifname_set;
this.scope_ifname = ifname;
}
/**
* scoped interface. scope_id is derived from this as the scope_id of the first
* address whose scope is the same as this address for the named interface.
*/
private transient NetworkInterface scope_ifname; // null
/**
* Holds a 128-bit (16 bytes) IPv6 address.
*/
byte[] ipaddress;
/**
* set if the object is constructed with a scoped
* interface instead of a numeric scope id.
*/
private boolean scope_ifname_set; // false;
/**
* scope_id. The scope specified when the object is created. If the object
* is created with an interface name, then the scope_id is not determined
* until the time it is needed.
*/
int scope_id; // 0
/**
* This will be set to true when the scope_id field contains a valid
* integer scope_id.
*/
boolean scope_id_set; // false
/**
* scoped interface. scope_id is derived from this as the scope_id of the first
* address whose scope is the same as this address for the named interface.
*/
NetworkInterface scope_ifname; // null
/**
* set if the object is constructed with a scoped
* interface instead of a numeric scope id.
*/
boolean scope_ifname_set; // false;
void setAddr(byte addr[]) {
if (addr.length == INADDRSZ) { // normal IPv6 address
System.arraycopy(addr, 0, ipaddress, 0, INADDRSZ);
}
}
void init(byte addr[], int scope_id) {
setAddr(addr);
if (scope_id >= 0) {
this.scope_id = scope_id;
this.scope_id_set = true;
}
}
void init(byte addr[], NetworkInterface nif)
throws UnknownHostException
{
setAddr(addr);
if (nif != null) {
this.scope_id = deriveNumericScope(ipaddress, nif);
this.scope_id_set = true;
this.scope_ifname = nif;
this.scope_ifname_set = true;
}
}
String getHostAddress() {
String s = numericToTextFormat(ipaddress);
if (scope_ifname != null) { /* must check this first */
s = s + "%" + scope_ifname.getName();
} else if (scope_id_set) {
s = s + "%" + scope_id;
}
return s;
}
public boolean equals(Object o) {
if (! (o instanceof Inet6AddressHolder)) {
return false;
}
Inet6AddressHolder that = (Inet6AddressHolder)o;
return Arrays.equals(this.ipaddress, that.ipaddress);
}
public int hashCode() {
if (ipaddress != null) {
int hash = 0;
int i=0;
while (i<INADDRSZ) {
int j=0;
int component=0;
while (j<4 && i<INADDRSZ) {
component = (component << 8) + ipaddress[i];
j++;
i++;
}
hash += component;
}
return hash;
} else {
return 0;
}
}
boolean isIPv4CompatibleAddress() {
if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
(ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
(ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
(ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
(ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
(ipaddress[10] == 0x00) && (ipaddress[11] == 0x00)) {
return true;
}
return false;
}
boolean isMulticastAddress() {
return ((ipaddress[0] & 0xff) == 0xff);
}
boolean isAnyLocalAddress() {
byte test = 0x00;
for (int i = 0; i < INADDRSZ; i++) {
test |= ipaddress[i];
}
return (test == 0x00);
}
boolean isLoopbackAddress() {
byte test = 0x00;
for (int i = 0; i < 15; i++) {
test |= ipaddress[i];
}
return (test == 0x00) && (ipaddress[15] == 0x01);
}
boolean isLinkLocalAddress() {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0x80);
}
boolean isSiteLocalAddress() {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0xc0);
}
boolean isMCGlobal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x0e);
}
boolean isMCNodeLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x01);
}
boolean isMCLinkLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x02);
}
boolean isMCSiteLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x05);
}
boolean isMCOrgLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x08);
}
}
private final transient Inet6AddressHolder holder6;
private static final long serialVersionUID = 6880410070516793377L;
@ -216,27 +374,21 @@ class Inet6Address extends InetAddress {
Inet6Address() {
super();
holder().hostName = null;
ipaddress = new byte[INADDRSZ];
holder().family = IPv6;
holder.init(null, IPv6);
holder6 = new Inet6AddressHolder();
}
/* checking of value for scope_id should be done by caller
* scope_id must be >= 0, or -1 to indicate not being set
*/
Inet6Address(String hostName, byte addr[], int scope_id) {
holder().hostName = hostName;
if (addr.length == INADDRSZ) { // normal IPv6 address
holder().family = IPv6;
ipaddress = addr.clone();
}
if (scope_id >= 0) {
this.scope_id = scope_id;
scope_id_set = true;
}
holder.init(hostName, IPv6);
holder6 = new Inet6AddressHolder();
holder6.init(addr, scope_id);
}
Inet6Address(String hostName, byte addr[]) {
holder6 = new Inet6AddressHolder();
try {
initif (hostName, addr, null);
} catch (UnknownHostException e) {} /* cant happen if ifname is null */
@ -245,12 +397,14 @@ class Inet6Address extends InetAddress {
Inet6Address (String hostName, byte addr[], NetworkInterface nif)
throws UnknownHostException
{
holder6 = new Inet6AddressHolder();
initif (hostName, addr, nif);
}
Inet6Address (String hostName, byte addr[], String ifname)
throws UnknownHostException
{
holder6 = new Inet6AddressHolder();
initstr (hostName, addr, ifname);
}
@ -341,17 +495,13 @@ class Inet6Address extends InetAddress {
private void initif(String hostName, byte addr[], NetworkInterface nif)
throws UnknownHostException
{
holder().hostName = hostName;
int family = -1;
holder6.init(addr, nif);
if (addr.length == INADDRSZ) { // normal IPv6 address
holder().family = IPv6;
ipaddress = addr.clone();
}
if (nif != null) {
scope_ifname = nif;
scope_id = deriveNumericScope(nif);
scope_id_set = true;
scope_ifname_set = true; // for consistency
family = IPv6;
}
holder.init(hostName, family);
}
/* check the two Ipv6 addresses and return false if they are both
@ -359,17 +509,22 @@ class Inet6Address extends InetAddress {
* (ie. one is sitelocal and the other linklocal)
* return true otherwise.
*/
private boolean differentLocalAddressTypes(Inet6Address other) {
if (isLinkLocalAddress() && !other.isLinkLocalAddress())
private static boolean isDifferentLocalAddressType(
byte[] thisAddr, byte[] otherAddr) {
if (Inet6Address.isLinkLocalAddress(thisAddr) &&
!Inet6Address.isLinkLocalAddress(otherAddr)) {
return false;
if (isSiteLocalAddress() && !other.isSiteLocalAddress())
}
if (Inet6Address.isSiteLocalAddress(thisAddr) &&
!Inet6Address.isSiteLocalAddress(otherAddr)) {
return false;
}
return true;
}
private int deriveNumericScope(NetworkInterface ifc)
throws UnknownHostException
{
private static int deriveNumericScope (byte[] thisAddr, NetworkInterface ifc) throws UnknownHostException {
Enumeration<InetAddress> addresses = ifc.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
@ -378,46 +533,60 @@ class Inet6Address extends InetAddress {
}
Inet6Address ia6_addr = (Inet6Address)addr;
/* check if site or link local prefixes match */
if (!differentLocalAddressTypes(ia6_addr)){
if (!isDifferentLocalAddressType(thisAddr, ia6_addr.getAddress())){
/* type not the same, so carry on searching */
continue;
}
/* found a matching address - return its scope_id */
return ia6_addr.scope_id;
return ia6_addr.getScopeId();
}
throw new UnknownHostException ("no scope_id found");
}
private int deriveNumericScope(String ifname) throws UnknownHostException {
private int deriveNumericScope (String ifname) throws UnknownHostException {
Enumeration<NetworkInterface> en;
try {
en = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new UnknownHostException(
"could not enumerate local network interfaces");
throw new UnknownHostException ("could not enumerate local network interfaces");
}
while (en.hasMoreElements()) {
NetworkInterface ifc = en.nextElement();
if (ifc.getName().equals(ifname)) {
Enumeration<InetAddress> addresses = ifc.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if (!(addr instanceof Inet6Address)) {
continue;
}
Inet6Address ia6_addr = (Inet6Address)addr;
/* check if site or link local prefixes match */
if (!differentLocalAddressTypes(ia6_addr)){
/* type not the same, so carry on searching */
continue;
}
/* found a matching address - return its scope_id */
return ia6_addr.scope_id;
}
if (ifc.getName().equals (ifname)) {
return deriveNumericScope(holder6.ipaddress, ifc);
}
}
throw new UnknownHostException(
"No matching address found for interface : " +ifname);
throw new UnknownHostException ("No matching address found for interface : " +ifname);
}
/**
* @serialField ipaddress byte[]
* @serialField scope_id int
* @serialField scope_id_set boolean
* @serialField scope_ifname_set boolean
* @serialField ifname String
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("ipaddress", byte[].class),
new ObjectStreamField("scope_id", int.class),
new ObjectStreamField("scope_id_set", boolean.class),
new ObjectStreamField("scope_ifname_set", boolean.class),
new ObjectStreamField("ifname", String.class)
};
private static final long FIELDS_OFFSET;
private static final sun.misc.Unsafe UNSAFE;
static {
try {
sun.misc.Unsafe unsafe = sun.misc.Unsafe.getUnsafe();
FIELDS_OFFSET = unsafe.objectFieldOffset(
Inet6Address.class.getDeclaredField("holder6"));
UNSAFE = unsafe;
} catch (ReflectiveOperationException e) {
throw new Error(e);
}
}
/**
@ -427,35 +596,41 @@ class Inet6Address extends InetAddress {
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException {
NetworkInterface scope_ifname = null;
if (getClass().getClassLoader() != null) {
throw new SecurityException ("invalid address type");
}
s.defaultReadObject();
ObjectInputStream.GetField gf = s.readFields();
byte[] ipaddress = (byte[])gf.get("ipaddress", null);
int scope_id = (int)gf.get("scope_id", -1);
boolean scope_id_set = (boolean)gf.get("scope_id_set", false);
boolean scope_ifname_set = (boolean)gf.get("scope_ifname_set", false);
String ifname = (String)gf.get("ifname", null);
if (ifname != null && !ifname.equals("")) {
if (ifname != null && !"".equals (ifname)) {
try {
scope_ifname = NetworkInterface.getByName(ifname);
if (scope_ifname != null) {
scope_ifname_set = true;
try {
scope_id = deriveNumericScope(scope_ifname);
} catch (UnknownHostException e) {
// typically should not happen, but it may be that
// the machine being used for deserialization has
// the same interface name but without IPv6 configured.
}
} else {
if (scope_ifname == null) {
/* the interface does not exist on this system, so we clear
* the scope information completely */
scope_id_set = false;
scope_ifname_set = false;
scope_id = 0;
} else {
scope_ifname_set = true;
try {
scope_id = deriveNumericScope (ipaddress, scope_ifname);
} catch (UnknownHostException e) {
// typically should not happen, but it may be that
// the machine being used for deserialization has
// the same interface name but without IPv6 configured.
}
}
} catch (SocketException e) {}
}
/* if ifname was not supplied, then the numeric info is used */
ipaddress = ipaddress.clone();
@ -466,9 +641,38 @@ class Inet6Address extends InetAddress {
ipaddress.length);
}
if (holder().getFamily() != IPv6) {
if (holder.getFamily() != IPv6) {
throw new InvalidObjectException("invalid address family type");
}
Inet6AddressHolder h = new Inet6AddressHolder(
ipaddress, scope_id, scope_id_set, scope_ifname, scope_ifname_set
);
UNSAFE.putObject(this, FIELDS_OFFSET, h);
}
/**
* default behavior is overridden in order to write the
* scope_ifname field as a String, rather than a NetworkInterface
* which is not serializable
*/
private synchronized void writeObject(ObjectOutputStream s)
throws IOException
{
String ifname = null;
if (holder6.scope_ifname != null) {
ifname = holder6.scope_ifname.getName();
holder6.scope_ifname_set = true;
}
ObjectOutputStream.PutField pfields = s.putFields();
pfields.put("ipaddress", holder6.ipaddress);
pfields.put("scope_id", holder6.scope_id);
pfields.put("scope_id_set", holder6.scope_id_set);
pfields.put("scope_ifname_set", holder6.scope_ifname_set);
pfields.put("ifname", ifname);
s.writeFields();
}
/**
@ -483,7 +687,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMulticastAddress() {
return ((ipaddress[0] & 0xff) == 0xff);
return holder6.isMulticastAddress();
}
/**
@ -496,11 +700,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isAnyLocalAddress() {
byte test = 0x00;
for (int i = 0; i < INADDRSZ; i++) {
test |= ipaddress[i];
}
return (test == 0x00);
return holder6.isAnyLocalAddress();
}
/**
@ -513,11 +713,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isLoopbackAddress() {
byte test = 0x00;
for (int i = 0; i < 15; i++) {
test |= ipaddress[i];
}
return (test == 0x00) && (ipaddress[15] == 0x01);
return holder6.isLoopbackAddress();
}
/**
@ -530,6 +726,11 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isLinkLocalAddress() {
return holder6.isLinkLocalAddress();
}
/* static version of above */
static boolean isLinkLocalAddress(byte[] ipaddress) {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0x80);
}
@ -544,6 +745,11 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isSiteLocalAddress() {
return holder6.isSiteLocalAddress();
}
/* static version of above */
static boolean isSiteLocalAddress(byte[] ipaddress) {
return ((ipaddress[0] & 0xff) == 0xfe
&& (ipaddress[1] & 0xc0) == 0xc0);
}
@ -559,8 +765,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMCGlobal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x0e);
return holder6.isMCGlobal();
}
/**
@ -574,8 +779,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMCNodeLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x01);
return holder6.isMCNodeLocal();
}
/**
@ -589,8 +793,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMCLinkLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x02);
return holder6.isMCLinkLocal();
}
/**
@ -604,8 +807,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMCSiteLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x05);
return holder6.isMCSiteLocal();
}
/**
@ -619,10 +821,8 @@ class Inet6Address extends InetAddress {
*/
@Override
public boolean isMCOrgLocal() {
return ((ipaddress[0] & 0xff) == 0xff
&& (ipaddress[1] & 0x0f) == 0x08);
return holder6.isMCOrgLocal();
}
/**
* Returns the raw IP address of this {@code InetAddress} object. The result
* is in network byte order: the highest order byte of the address is in
@ -632,7 +832,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public byte[] getAddress() {
return ipaddress.clone();
return holder6.ipaddress.clone();
}
/**
@ -644,7 +844,7 @@ class Inet6Address extends InetAddress {
* @since 1.5
*/
public int getScopeId() {
return scope_id;
return holder6.scope_id;
}
/**
@ -655,7 +855,7 @@ class Inet6Address extends InetAddress {
* @since 1.5
*/
public NetworkInterface getScopedInterface() {
return scope_ifname;
return holder6.scope_ifname;
}
/**
@ -669,13 +869,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public String getHostAddress() {
String s = numericToTextFormat(ipaddress);
if (scope_ifname != null) { /* must check this first */
s = s + "%" + scope_ifname.getName();
} else if (scope_id_set) {
s = s + "%" + scope_id;
}
return s;
return holder6.getHostAddress();
}
/**
@ -685,25 +879,7 @@ class Inet6Address extends InetAddress {
*/
@Override
public int hashCode() {
if (ipaddress != null) {
int hash = 0;
int i=0;
while (i<INADDRSZ) {
int j=0;
int component=0;
while (j<4 && i<INADDRSZ) {
component = (component << 8) + ipaddress[i];
j++;
i++;
}
hash += component;
}
return hash;
} else {
return 0;
}
return holder6.hashCode();
}
/**
@ -728,12 +904,8 @@ class Inet6Address extends InetAddress {
return false;
Inet6Address inetAddr = (Inet6Address)obj;
for (int i = 0; i < INADDRSZ; i++) {
if (ipaddress[i] != inetAddr.ipaddress[i])
return false;
}
return true;
return holder6.equals(inetAddr.holder6);
}
/**
@ -746,15 +918,7 @@ class Inet6Address extends InetAddress {
* @since 1.4
*/
public boolean isIPv4CompatibleAddress() {
if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
(ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
(ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
(ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
(ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
(ipaddress[10] == 0x00) && (ipaddress[11] == 0x00)) {
return true;
}
return false;
return holder6.isIPv4CompatibleAddress();
}
// Utilities
@ -784,24 +948,4 @@ class Inet6Address extends InetAddress {
* Perform class load-time initializations.
*/
private static native void init();
/**
* Following field is only used during (de)/serialization
*/
private String ifname;
/**
* default behavior is overridden in order to write the
* scope_ifname field as a String, rather than a NetworkInterface
* which is not serializable
*/
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
if (scope_ifname != null) {
ifname = scope_ifname.getName();
scope_ifname_set = true;
}
s.defaultWriteObject();
}
}

View File

@ -212,6 +212,13 @@ class InetAddress implements java.io.Serializable {
this.family = family;
}
void init(String hostName, int family) {
this.hostName = hostName;
if (family != -1) {
this.family = family;
}
}
String hostName;
String getHostName() {
@ -239,7 +246,7 @@ class InetAddress implements java.io.Serializable {
}
/* Used to store the serializable fields of InetAddress */
private final transient InetAddressHolder holder;
final transient InetAddressHolder holder;
InetAddressHolder holder() {
return holder;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -39,13 +39,9 @@
package java.util;
import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.time.ZoneId;
import java.util.concurrent.ConcurrentHashMap;
import sun.misc.JavaAWTAccess;
import sun.misc.SharedSecrets;
import sun.security.action.GetPropertyAction;
import sun.util.calendar.ZoneInfo;
import sun.util.calendar.ZoneInfoFile;
@ -596,11 +592,26 @@ abstract public class TimeZone implements Serializable, Cloneable {
private static native String getSystemGMTOffsetID();
/**
* Gets the default <code>TimeZone</code> for this host.
* The source of the default <code>TimeZone</code>
* may vary with implementation.
* @return a default <code>TimeZone</code>.
* @see #setDefault
* Gets the default {@code TimeZone} of the Java virtual machine. If the
* cached default {@code TimeZone} is available, its clone is returned.
* Otherwise, the method takes the following steps to determine the default
* time zone.
*
* <p><ul>
* <li>Use the {@code user.timezone} property value as the default
* time zone ID if it's available.</li>
* <li>Detect the platform time zone ID. The source of the
* platform time zone and ID mapping may vary with implementation.</li>
* <li>Use {@code GMT} as the last resort if the given or detected
* time zone ID is unknown.</li>
* </ul>
*
* <p>The default {@code TimeZone} created from the ID is cached,
* and its clone is returned. The {@code user.timezone} property
* value is set to the ID upon return.
*
* @return the default {@code TimeZone}
* @see #setDefault(TimeZone)
*/
public static TimeZone getDefault() {
return (TimeZone) getDefaultRef().clone();
@ -611,14 +622,11 @@ abstract public class TimeZone implements Serializable, Cloneable {
* method doesn't create a clone.
*/
static TimeZone getDefaultRef() {
TimeZone defaultZone = getDefaultInAppContext();
TimeZone defaultZone = defaultTimeZone;
if (defaultZone == null) {
defaultZone = defaultTimeZone;
if (defaultZone == null) {
// Need to initialize the default time zone.
defaultZone = setDefaultZone();
assert defaultZone != null;
}
// Need to initialize the default time zone.
defaultZone = setDefaultZone();
assert defaultZone != null;
}
// Don't clone here.
return defaultZone;
@ -676,95 +684,27 @@ abstract public class TimeZone implements Serializable, Cloneable {
return tz;
}
private static boolean hasPermission() {
boolean hasPermission = true;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
try {
sm.checkPermission(new PropertyPermission
("user.timezone", "write"));
} catch (SecurityException e) {
hasPermission = false;
}
}
return hasPermission;
}
/**
* Sets the <code>TimeZone</code> that is
* returned by the <code>getDefault</code> method. If <code>zone</code>
* is null, reset the default to the value it had originally when the
* VM first started.
* @param zone the new default time zone
* Sets the {@code TimeZone} that is returned by the {@code getDefault}
* method. {@code zone} is cached. If {@code zone} is null, the cached
* default {@code TimeZone} is cleared. This method doesn't change the value
* of the {@code user.timezone} property.
*
* @param zone the new default {@code TimeZone}, or null
* @throws SecurityException if the security manager's {@code checkPermission}
* denies {@code PropertyPermission("user.timezone",
* "write")}
* @see #getDefault
* @see PropertyPermission
*/
public static void setDefault(TimeZone zone)
{
if (hasPermission()) {
synchronized (TimeZone.class) {
defaultTimeZone = zone;
setDefaultInAppContext(null);
}
} else {
setDefaultInAppContext(zone);
}
}
/**
* Returns the default TimeZone in an AppContext if any AppContext
* has ever used. null is returned if any AppContext hasn't been
* used or if the AppContext doesn't have the default TimeZone.
*
* Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
* been loaded. If so, it implies that AWTSecurityManager is not our
* SecurityManager and we can use a local static variable.
* This works around a build time issue.
*/
private static TimeZone getDefaultInAppContext() {
// JavaAWTAccess provides access implementation-private methods without using reflection.
JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
if (javaAWTAccess == null) {
return mainAppContextDefault;
} else {
if (!javaAWTAccess.isDisposed()) {
TimeZone tz = (TimeZone)
javaAWTAccess.get(TimeZone.class);
if (tz == null && javaAWTAccess.isMainAppContext()) {
return mainAppContextDefault;
} else {
return tz;
}
}
}
return null;
}
/**
* Sets the default TimeZone in the AppContext to the given
* tz. null is handled special: do nothing if any AppContext
* hasn't been used, remove the default TimeZone in the
* AppContext otherwise.
*
* Note that javaAWTAccess may be null if sun.awt.AppContext class hasn't
* been loaded. If so, it implies that AWTSecurityManager is not our
* SecurityManager and we can use a local static variable.
* This works around a build time issue.
*/
private static void setDefaultInAppContext(TimeZone tz) {
// JavaAWTAccess provides access implementation-private methods without using reflection.
JavaAWTAccess javaAWTAccess = SharedSecrets.getJavaAWTAccess();
if (javaAWTAccess == null) {
mainAppContextDefault = tz;
} else {
if (!javaAWTAccess.isDisposed()) {
javaAWTAccess.put(TimeZone.class, tz);
if (javaAWTAccess.isMainAppContext()) {
mainAppContextDefault = null;
}
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new PropertyPermission
("user.timezone", "write"));
}
defaultTimeZone = zone;
}
/**

View File

@ -25,6 +25,9 @@
package javax.management;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* Thrown when an invalid MBean attribute is passed to a query
@ -41,17 +44,19 @@ public class BadAttributeValueExpException extends Exception {
private static final long serialVersionUID = -3105272988410493376L;
/**
* @serial The attribute value that originated this exception
* @serial A string representation of the attribute that originated this exception.
* for example, the string value can be the return of {@code attribute.toString()}
*/
private Object val;
/**
* Constructs an <CODE>BadAttributeValueExpException</CODE> with the specified Object.
* Constructs a BadAttributeValueExpException using the specified Object to
* create the toString() value.
*
* @param val the inappropriate value.
*/
public BadAttributeValueExpException (Object val) {
this.val = val;
this.val = val == null ? null : val.toString();
}
@ -62,4 +67,25 @@ public class BadAttributeValueExpException extends Exception {
return "BadAttributeValueException: " + val;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = ois.readFields();
Object valObj = gf.get("val", null);
if (valObj == null) {
val = null;
} else if (valObj instanceof String) {
val= valObj;
} else if (System.getSecurityManager() == null
|| valObj instanceof Long
|| valObj instanceof Integer
|| valObj instanceof Float
|| valObj instanceof Double
|| valObj instanceof Byte
|| valObj instanceof Short
|| valObj instanceof Boolean) {
val = valObj.toString();
} else { // the serialized object is from a version without JDK-8019292 fix
val = System.identityHashCode(valObj) + "@" + valObj.getClass().getName();
}
}
}

View File

@ -25,6 +25,9 @@
package javax.management;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.util.Arrays;
import java.util.Objects;
@ -68,7 +71,7 @@ public class MBeanNotificationInfo extends MBeanFeatureInfo implements Cloneable
/**
* @serial The different types of the notification.
*/
private final String[] types;
private String[] types;
/** @see MBeanInfo#arrayGettersSafe */
private final transient boolean arrayGettersSafe;
@ -115,9 +118,8 @@ public class MBeanNotificationInfo extends MBeanFeatureInfo implements Cloneable
notifType, though it doesn't explicitly allow it
either. */
if (notifTypes == null)
notifTypes = NO_TYPES;
this.types = notifTypes;
this.types = (notifTypes != null && notifTypes.length > 0) ?
notifTypes.clone() : NO_TYPES;
this.arrayGettersSafe =
MBeanInfo.arrayGettersSafe(this.getClass(),
MBeanNotificationInfo.class);
@ -204,4 +206,11 @@ public class MBeanNotificationInfo extends MBeanFeatureInfo implements Cloneable
hash ^= types[i].hashCode();
return hash;
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = ois.readFields();
String[] t = (String[])gf.get("types", null);
types = (t != null && t.length != 0) ? t.clone() : NO_TYPES;
}
}

View File

@ -26,6 +26,9 @@
package javax.management;
import java.security.BasicPermission;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
/**
* This permission represents "trust" in a signer or codebase.
@ -75,15 +78,31 @@ public class MBeanTrustPermission extends BasicPermission {
*/
public MBeanTrustPermission(String name, String actions) {
super(name, actions);
/* Check that actions is a null empty string */
if (actions != null && actions.length() > 0)
throw new IllegalArgumentException("MBeanTrustPermission " +
"actions must be null: " +
actions);
validate(name,actions);
}
if (!name.equals("register") && !name.equals("*"))
throw new IllegalArgumentException("MBeanTrustPermission: " +
"Unknown target name " +
private static void validate(String name, String actions) {
/* Check that actions is a null empty string */
if (actions != null && actions.length() > 0) {
throw new IllegalArgumentException("MBeanTrustPermission actions must be null: " +
actions);
}
if (!name.equals("register") && !name.equals("*")) {
throw new IllegalArgumentException("MBeanTrustPermission: Unknown target name " +
"[" + name + "]");
}
}
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// Reading private fields of base class
in.defaultReadObject();
try {
validate(super.getName(),super.getActions());
} catch (IllegalArgumentException e) {
throw new InvalidObjectException(e.getMessage());
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -298,11 +298,15 @@ public class RequiredModelMBean
RequiredModelMBean.class.getName(),
"setModelMBeanInfo(ModelMBeanInfo)",
"Setting ModelMBeanInfo to " + printModelMBeanInfo(mbi));
int noOfNotifications = 0;
if (mbi.getNotifications() != null) {
noOfNotifications = mbi.getNotifications().length;
}
MODELMBEAN_LOGGER.logp(Level.FINER,
RequiredModelMBean.class.getName(),
"setModelMBeanInfo(ModelMBeanInfo)",
"ModelMBeanInfo notifications has " +
(mbi.getNotifications()).length + " elements");
noOfNotifications + " elements");
}
modelMBeanInfo = (ModelMBeanInfo)mbi.clone();

View File

@ -26,6 +26,9 @@
package javax.management.remote;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.security.Principal;
@ -64,9 +67,7 @@ public class JMXPrincipal implements Principal, Serializable {
* <code>null</code>.
*/
public JMXPrincipal(String name) {
if (name == null)
throw new NullPointerException("illegal null input");
validate(name);
this.name = name;
}
@ -130,4 +131,20 @@ public class JMXPrincipal implements Principal, Serializable {
public int hashCode() {
return name.hashCode();
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = ois.readFields();
String principalName = (String)gf.get("name", null);
try {
validate(principalName);
this.name = principalName;
} catch (NullPointerException e) {
throw new InvalidObjectException(e.getMessage());
}
}
private static void validate(String name) throws NullPointerException {
if (name == null)
throw new NullPointerException("illegal null input");
}
}

View File

@ -29,6 +29,9 @@ package javax.management.remote;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.InetAddress;
@ -297,7 +300,7 @@ public class JMXServiceURL implements Serializable {
If we're given an explicit host name that is illegal we
have to reject it. (Bug 5057532.) */
try {
validateHost(host);
validateHost(host, port);
} catch (MalformedURLException e) {
if (logger.fineOn()) {
logger.fine("JMXServiceURL",
@ -336,36 +339,82 @@ public class JMXServiceURL implements Serializable {
validate();
}
private void validate() throws MalformedURLException {
private static final String INVALID_INSTANCE_MSG =
"Trying to deserialize an invalid instance of JMXServiceURL";
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField gf = inputStream.readFields();
String h = (String)gf.get("host", null);
int p = (int)gf.get("port", -1);
String proto = (String)gf.get("protocol", null);
String url = (String)gf.get("urlPath", null);
if (proto == null || url == null || h == null) {
StringBuilder sb = new StringBuilder(INVALID_INSTANCE_MSG).append('[');
boolean empty = true;
if (proto == null) {
sb.append("protocol=null");
empty = false;
}
if (h == null) {
sb.append(empty ? "" : ",").append("host=null");
empty = false;
}
if (url == null) {
sb.append(empty ? "" : ",").append("urlPath=null");
}
sb.append(']');
throw new InvalidObjectException(sb.toString());
}
if (h.contains("[") || h.contains("]")) {
throw new InvalidObjectException("Invalid host name: " + h);
}
try {
validate(proto, h, p, url);
this.protocol = proto;
this.host = h;
this.port = p;
this.urlPath = url;
} catch (MalformedURLException e) {
throw new InvalidObjectException(INVALID_INSTANCE_MSG + ": " +
e.getMessage());
}
}
private void validate(String proto, String h, int p, String url)
throws MalformedURLException {
// Check protocol
final int protoEnd = indexOfFirstNotInSet(protocol, protocolBitSet, 0);
if (protoEnd == 0 || protoEnd < protocol.length()
|| !alphaBitSet.get(protocol.charAt(0))) {
final int protoEnd = indexOfFirstNotInSet(proto, protocolBitSet, 0);
if (protoEnd == 0 || protoEnd < proto.length()
|| !alphaBitSet.get(proto.charAt(0))) {
throw new MalformedURLException("Missing or invalid protocol " +
"name: \"" + protocol + "\"");
"name: \"" + proto + "\"");
}
// Check host
validateHost();
validateHost(h, p);
// Check port
if (port < 0)
throw new MalformedURLException("Bad port: " + port);
if (p < 0)
throw new MalformedURLException("Bad port: " + p);
// Check URL path
if (urlPath.length() > 0) {
if (!urlPath.startsWith("/") && !urlPath.startsWith(";"))
throw new MalformedURLException("Bad URL path: " + urlPath);
if (url.length() > 0) {
if (!url.startsWith("/") && !url.startsWith(";"))
throw new MalformedURLException("Bad URL path: " + url);
}
}
private void validateHost() throws MalformedURLException {
if (host.length() == 0) {
private void validate() throws MalformedURLException {
validate(this.protocol, this.host, this.port, this.urlPath);
}
private static void validateHost(String h, int port)
throws MalformedURLException {
if (h.length() == 0) {
if (port != 0) {
throw new MalformedURLException("Cannot give port number " +
"without host name");
@ -373,12 +422,6 @@ public class JMXServiceURL implements Serializable {
return;
}
validateHost(host);
}
private static void validateHost(String h)
throws MalformedURLException {
if (isNumericIPv6Address(h)) {
/* We assume J2SE >= 1.4 here. Otherwise you can't
use the address anyway. We can't call
@ -663,22 +706,22 @@ public class JMXServiceURL implements Serializable {
/**
* The value returned by {@link #getProtocol()}.
*/
private final String protocol;
private String protocol;
/**
* The value returned by {@link #getHost()}.
*/
private final String host;
private String host;
/**
* The value returned by {@link #getPort()}.
*/
private final int port;
private int port;
/**
* The value returned by {@link #getURLPath()}.
*/
private final String urlPath;
private String urlPath;
/**
* Cached result of {@link #toString()}.

View File

@ -25,6 +25,9 @@
package javax.management.remote;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
/**
@ -76,17 +79,7 @@ public class NotificationResult implements Serializable {
public NotificationResult(long earliestSequenceNumber,
long nextSequenceNumber,
TargetedNotification[] targetedNotifications) {
if (targetedNotifications == null) {
final String msg = "Notifications null";
throw new IllegalArgumentException(msg);
}
if (earliestSequenceNumber < 0 || nextSequenceNumber < 0)
throw new IllegalArgumentException("Bad sequence numbers");
/* We used to check nextSequenceNumber >= earliestSequenceNumber
here. But in fact the opposite can legitimately be true if
notifications have been lost. */
validate(targetedNotifications, earliestSequenceNumber, nextSequenceNumber);
this.earliestSequenceNumber = earliestSequenceNumber;
this.nextSequenceNumber = nextSequenceNumber;
this.targetedNotifications = (targetedNotifications.length == 0 ? targetedNotifications : targetedNotifications.clone());
@ -138,7 +131,40 @@ public class NotificationResult implements Serializable {
getTargetedNotifications().length;
}
private final long earliestSequenceNumber;
private final long nextSequenceNumber;
private final TargetedNotification[] targetedNotifications;
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
try {
validate(
this.targetedNotifications,
this.earliestSequenceNumber,
this.nextSequenceNumber
);
this.targetedNotifications = this.targetedNotifications.length == 0 ?
this.targetedNotifications :
this.targetedNotifications.clone();
} catch (IllegalArgumentException e) {
throw new InvalidObjectException(e.getMessage());
}
}
private long earliestSequenceNumber;
private long nextSequenceNumber;
private TargetedNotification[] targetedNotifications;
private static void validate(TargetedNotification[] targetedNotifications,
long earliestSequenceNumber,
long nextSequenceNumber)
throws IllegalArgumentException {
if (targetedNotifications == null) {
final String msg = "Notifications null";
throw new IllegalArgumentException(msg);
}
if (earliestSequenceNumber < 0 || nextSequenceNumber < 0)
throw new IllegalArgumentException("Bad sequence numbers");
/* We used to check nextSequenceNumber >= earliestSequenceNumber
here. But in fact the opposite can legitimately be true if
notifications have been lost. */
}
}

View File

@ -26,6 +26,9 @@
package javax.management.remote;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import javax.management.Notification;
@ -73,12 +76,9 @@ public class TargetedNotification implements Serializable {
*/
public TargetedNotification(Notification notification,
Integer listenerID) {
validate(notification, listenerID);
// If we replace integer with int...
// this(notification,intValue(listenerID));
if (notification == null) throw new
IllegalArgumentException("Invalid notification: null");
if (listenerID == null) throw new
IllegalArgumentException("Invalid listener ID: null");
this.notif = notification;
this.id = listenerID;
}
@ -115,13 +115,13 @@ public class TargetedNotification implements Serializable {
* @serial A notification to transmit to the other side.
* @see #getNotification()
**/
private final Notification notif;
private Notification notif;
/**
* @serial The ID of the listener to which the notification is
* targeted.
* @see #getListenerID()
**/
private final Integer id;
private Integer id;
//private final int id;
// Needed if we use int instead of Integer...
@ -130,4 +130,22 @@ public class TargetedNotification implements Serializable {
// IllegalArgumentException("Invalid listener ID: null");
// return id.intValue();
// }
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
try {
validate(this.notif, this.id);
} catch (IllegalArgumentException e) {
throw new InvalidObjectException(e.getMessage());
}
}
private static void validate(Notification notif, Integer id) throws IllegalArgumentException {
if (notif == null) {
throw new IllegalArgumentException("Invalid notification: null");
}
if (id == null) {
throw new IllegalArgumentException("Invalid listener ID: null");
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -61,6 +61,7 @@ import java.rmi.server.RemoteRef;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collections;
@ -128,7 +129,6 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable
Map<String, ?> environment) {
if (rmiServer == null && address == null) throw new
IllegalArgumentException("rmiServer and jmxServiceURL both null");
initTransients();
this.rmiServer = rmiServer;
@ -2382,13 +2382,21 @@ public class RMIConnector implements JMXConnector, Serializable, JMXAddressable
}
}
private static RMIConnection shadowIiopStub(Object stub)
private static RMIConnection shadowIiopStub(Object stub)
throws InstantiationException, IllegalAccessException {
Object proxyStub = proxyStubClass.newInstance();
Object proxyStub = null;
try {
proxyStub = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return proxyStubClass.newInstance();
}
});
} catch (PrivilegedActionException e) {
throw new InternalError();
}
IIOPHelper.setDelegate(proxyStub, IIOPHelper.getDelegate(stub));
return (RMIConnection) proxyStub;
}
private static RMIConnection getConnection(RMIServer server,
Object credentials,
boolean checkStub)

View File

@ -1315,8 +1315,14 @@ public final class Subject implements java.io.Serializable {
{
ObjectInputStream.GetField fields = ois.readFields();
subject = (Subject) fields.get("this$0", null);
elements = (LinkedList<E>) fields.get("elements", null);
which = fields.get("which", 0);
LinkedList<E> tmp = (LinkedList<E>) fields.get("elements", null);
if (tmp.getClass() != LinkedList.class) {
elements = new LinkedList<E>(tmp);
} else {
elements = tmp;
}
}
}

View File

@ -26,6 +26,7 @@
package javax.security.auth.kerberos;
import java.io.File;
import java.security.AccessControlException;
import java.util.Objects;
import sun.security.krb5.EncryptionKey;
import sun.security.krb5.KerberosSecrets;
@ -214,9 +215,22 @@ public final class KeyTab {
return new KeyTab(princ, null, true);
}
//Takes a snapshot of the keytab content
// Takes a snapshot of the keytab content. This method is called by
// JavaxSecurityAuthKerberosAccessImpl so no more private
sun.security.krb5.internal.ktab.KeyTab takeSnapshot() {
return sun.security.krb5.internal.ktab.KeyTab.getInstance(file);
try {
return sun.security.krb5.internal.ktab.KeyTab.getInstance(file);
} catch (AccessControlException ace) {
if (file != null) {
// It's OK to show the name if caller specified it
throw ace;
} else {
AccessControlException ace2 = new AccessControlException(
"Access to default keytab denied (modified exception)");
ace2.setStackTrace(ace.getStackTrace());
throw ace2;
}
}
}
/**

View File

@ -52,6 +52,7 @@ import java.text.MessageFormat;
import javax.print.attribute.*;
import javax.print.PrintService;
import sun.reflect.misc.ReflectUtil;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
@ -5462,14 +5463,15 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
// they have the option to replace the value with
// null or use escape to restore the original.
// For Strings, return "" for backward compatibility.
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
return super.stopCellEditing();
}
try {
if ("".equals(s)) {
if (constructor.getDeclaringClass() == String.class) {
value = s;
}
return super.stopCellEditing();
}
SwingUtilities2.checkAccess(constructor.getModifiers());
value = constructor.newInstance(new Object[]{s});
}
catch (Exception e) {
@ -5493,6 +5495,8 @@ public class JTable extends JComponent implements TableModelListener, Scrollable
if (type == Object.class) {
type = String.class;
}
ReflectUtil.checkPackageAccess(type);
SwingUtilities2.checkAccess(type.getModifiers());
constructor = type.getConstructor(argTypes);
}
catch (Exception e) {

View File

@ -53,6 +53,7 @@ import java.security.PrivilegedAction;
import sun.reflect.misc.MethodUtil;
import sun.reflect.misc.ReflectUtil;
import sun.swing.SwingUtilities2;
import sun.util.CoreResourceBundleControl;
/**
@ -1101,7 +1102,7 @@ public class UIDefaults extends Hashtable<Object,Object>
}
ReflectUtil.checkPackageAccess(className);
c = Class.forName(className, true, (ClassLoader)cl);
checkAccess(c.getModifiers());
SwingUtilities2.checkAccess(c.getModifiers());
if (methodName != null) {
Class[] types = getClassArray(args);
Method m = c.getMethod(methodName, types);
@ -1109,7 +1110,7 @@ public class UIDefaults extends Hashtable<Object,Object>
} else {
Class[] types = getClassArray(args);
Constructor constructor = c.getConstructor(types);
checkAccess(constructor.getModifiers());
SwingUtilities2.checkAccess(constructor.getModifiers());
return constructor.newInstance(args);
}
} catch(Exception e) {
@ -1124,13 +1125,6 @@ public class UIDefaults extends Hashtable<Object,Object>
}, acc);
}
private void checkAccess(int modifiers) {
if(System.getSecurityManager() != null &&
!Modifier.isPublic(modifiers)) {
throw new SecurityException("Resource is not accessible");
}
}
/*
* Coerce the array of class types provided into one which
* looks the way the Reflection APIs expect. This is done

View File

@ -24,7 +24,8 @@
*/
package javax.swing.text;
import sun.reflect.misc.ConstructorUtil;
import sun.reflect.misc.ReflectUtil;
import sun.swing.SwingUtilities2;
import java.io.Serializable;
import java.lang.reflect.*;
@ -247,7 +248,9 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter
Constructor cons;
try {
cons = ConstructorUtil.getConstructor(vc, new Class[]{String.class});
ReflectUtil.checkPackageAccess(vc);
SwingUtilities2.checkAccess(vc.getModifiers());
cons = vc.getConstructor(new Class[]{String.class});
} catch (NoSuchMethodException nsme) {
cons = null;
@ -255,6 +258,7 @@ public class DefaultFormatter extends JFormattedTextField.AbstractFormatter
if (cons != null) {
try {
SwingUtilities2.checkAccess(cons.getModifiers());
return cons.newInstance(new Object[] { string });
} catch (Throwable ex) {
throw new ParseException("Error creating instance", 0);

View File

@ -27,6 +27,8 @@ package javax.swing.text;
import java.lang.reflect.*;
import java.text.*;
import java.util.*;
import sun.reflect.misc.ReflectUtil;
import sun.swing.SwingUtilities2;
/**
* <code>NumberFormatter</code> subclasses <code>InternationalFormatter</code>
@ -427,10 +429,12 @@ public class NumberFormatter extends InternationalFormatter {
valueClass = value.getClass();
}
try {
ReflectUtil.checkPackageAccess(valueClass);
SwingUtilities2.checkAccess(valueClass.getModifiers());
Constructor cons = valueClass.getConstructor(
new Class[] { String.class });
if (cons != null) {
SwingUtilities2.checkAccess(cons.getModifiers());
return cons.newInstance(new Object[]{string});
}
} catch (Throwable ex) { }

View File

@ -31,6 +31,9 @@ import javax.swing.text.*;
import java.beans.*;
import java.lang.reflect.*;
import sun.reflect.misc.MethodUtil;
import sun.reflect.misc.ReflectUtil;
/**
* Component decorator that implements the view interface
* for &lt;object&gt; elements.
@ -87,6 +90,7 @@ public class ObjectView extends ComponentView {
AttributeSet attr = getElement().getAttributes();
String classname = (String) attr.getAttribute(HTML.Attribute.CLASSID);
try {
ReflectUtil.checkPackageAccess(classname);
Class c = Class.forName(classname, true,Thread.currentThread().
getContextClassLoader());
Object o = c.newInstance();
@ -115,28 +119,6 @@ public class ObjectView extends ComponentView {
return comp;
}
/**
* Get a Class object to use for loading the
* classid. If possible, the Classloader
* used to load the associated Document is used.
* This would typically be the same as the ClassLoader
* used to load the EditorKit. If the documents
* ClassLoader is null,
* <code>Class.forName</code> is used.
*/
private Class getClass(String classname) throws ClassNotFoundException {
Class klass;
Class docClass = getDocument().getClass();
ClassLoader loader = docClass.getClassLoader();
if (loader != null) {
klass = loader.loadClass(classname);
} else {
klass = Class.forName(classname);
}
return klass;
}
/**
* Initialize this component according the KEY/VALUEs passed in
* via the &lt;param&gt; elements in the corresponding
@ -170,7 +152,7 @@ public class ObjectView extends ComponentView {
}
Object [] args = { value };
try {
writer.invoke(comp, args);
MethodUtil.invoke(writer, comp, args);
} catch (Exception ex) {
System.err.println("Invocation failed");
// invocation code

View File

@ -468,9 +468,10 @@ public final class GlyphLayout {
_gvdata.grow();
}
}
if (_gvdata._count < 0) {
break;
}
}
// Break out of the outer for loop if layout fails.
if (_gvdata._count < 0) {
break;
}
}

View File

@ -155,8 +155,7 @@ public class Disposer implements Runnable {
rec = null;
clearDeferredRecords();
} catch (Exception e) {
System.out.println("Exception while removing reference: " + e);
e.printStackTrace();
System.out.println("Exception while removing reference.");
}
}
}
@ -182,7 +181,6 @@ public class Disposer implements Runnable {
rec.dispose();
} catch (Exception e) {
System.out.println("Exception while disposing deferred rec.");
e.printStackTrace();
}
}
deferredRecords.clear();
@ -233,8 +231,7 @@ public class Disposer implements Runnable {
}
}
} catch (Exception e) {
System.out.println("Exception while removing reference: " + e);
e.printStackTrace();
System.out.println("Exception while removing reference.");
} finally {
pollingQueue = false;
}

View File

@ -40,7 +40,17 @@ public class HotSpotDiagnostic implements HotSpotDiagnosticMXBean {
public HotSpotDiagnostic() {
}
public native void dumpHeap(String outputFile, boolean live) throws IOException;
public void dumpHeap(String outputFile, boolean live) throws IOException {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(outputFile);
Util.checkControlAccess();
}
dumpHeap0(outputFile, live);
}
private native void dumpHeap0(String outputFile, boolean live) throws IOException;
public List<VMOption> getDiagnosticOptions() {
List<Flag> allFlags = Flag.getAllFlags();

View File

@ -27,6 +27,8 @@ package sun.misc;
import java.lang.annotation.Annotation;
import java.lang.reflect.Executable;
import java.security.AccessControlContext;
import sun.reflect.ConstantPool;
import sun.reflect.annotation.AnnotationType;
import sun.nio.ch.Interruptible;
@ -113,4 +115,10 @@ public interface JavaLangAccess {
* @return a newly created string whose content is the character array
*/
String newStringUnsafe(char[] chars);
/**
* Returns a new Thread with the given Runnable and an
* inherited AccessControlContext.
*/
Thread newThreadWithAcc(Runnable target, AccessControlContext acc);
}

View File

@ -26,8 +26,10 @@
package sun.reflect.misc;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import sun.reflect.Reflection;
public final class ReflectUtil {
@ -250,4 +252,50 @@ public final class ReflectUtil {
String pkg = (i != -1) ? name.substring(0, i) : "";
return Proxy.isProxyClass(cls) && !pkg.equals(PROXY_PACKAGE);
}
/**
* Check if the given method is a method declared in the proxy interface
* implemented by the given proxy instance.
*
* @param proxy a proxy instance
* @param method an interface method dispatched to a InvocationHandler
*
* @throws IllegalArgumentException if the given proxy or method is invalid.
*/
public static void checkProxyMethod(Object proxy, Method method) {
// check if it is a valid proxy instance
if (proxy == null || !Proxy.isProxyClass(proxy.getClass())) {
throw new IllegalArgumentException("Not a Proxy instance");
}
if (Modifier.isStatic(method.getModifiers())) {
throw new IllegalArgumentException("Can't handle static method");
}
Class<?> c = method.getDeclaringClass();
if (c == Object.class) {
String name = method.getName();
if (name.equals("hashCode") || name.equals("equals") || name.equals("toString")) {
return;
}
}
if (isSuperInterface(proxy.getClass(), c)) {
return;
}
// disallow any method not declared in one of the proxy intefaces
throw new IllegalArgumentException("Can't handle: " + method);
}
private static boolean isSuperInterface(Class<?> c, Class<?> intf) {
for (Class<?> i : c.getInterfaces()) {
if (i == intf) {
return true;
}
if (isSuperInterface(i, intf)) {
return true;
}
}
return false;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -152,12 +152,4 @@ public final class ECPrivateKeyImpl extends PKCS8Key implements ECPrivateKey {
throw new InvalidKeyException("Invalid EC private key", e);
}
}
// return a string representation of this key for debugging
public String toString() {
return "Sun EC private key, " + params.getCurve().getField().getFieldSize()
+ " bits\n private value: "
+ s + "\n parameters: " + params;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -651,7 +651,7 @@ public class GSSCredentialImpl implements ExtendedGSSCredential {
buffer.append(element.isAcceptorCredential() ?
" Accept" : "");
buffer.append(" [");
buffer.append(element.toString());
buffer.append(element.getClass());
buffer.append(']');
} catch (GSSException e) {
// skip to next element

View File

@ -223,16 +223,24 @@ public final class KdcComm {
if (!tempKdc.hasNext()) {
throw new KrbException("Cannot get kdc for realm " + realm);
}
byte[] ibuf = null;
try {
return sendIfPossible(obuf, tempKdc.next(), useTCP);
ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
} catch(Exception first) {
boolean ok = false;
while(tempKdc.hasNext()) {
try {
return sendIfPossible(obuf, tempKdc.next(), useTCP);
ibuf = sendIfPossible(obuf, tempKdc.next(), useTCP);
ok = true;
break;
} catch(Exception ignore) {}
}
throw first;
if (!ok) throw first;
}
if (ibuf == null) {
throw new IOException("Cannot get a KDC reply");
}
return ibuf;
}
// send the AS Request to the specified KDC

View File

@ -31,6 +31,8 @@
package sun.security.krb5.internal;
import sun.misc.IOUtils;
import java.io.*;
import java.net.*;
@ -100,17 +102,15 @@ class TCPClient extends NetClient {
return null;
}
byte data[] = new byte[len];
count = readFully(data, len);
if (count != len) {
try {
return IOUtils.readFully(in, len, true);
} catch (IOException ioe) {
if (Krb5.DEBUG) {
System.out.println(
">>>DEBUG: TCPClient could not read complete packet (" +
len + "/" + count + ")");
}
return null;
} else {
return data;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -304,17 +304,6 @@ public class PKCS8Key implements PrivateKey {
return encodedKey.clone();
}
/*
* Returns a printable representation of the key
*/
public String toString ()
{
HexDumpEncoder encoder = new HexDumpEncoder ();
return "algorithm = " + algid.toString ()
+ ", unparsed keybits = \n" + encoder.encodeBuffer (key);
}
/**
* Initialize an PKCS8Key object from an input stream. The data
* on that input stream must be encoded using DER, obeying the

View File

@ -554,27 +554,6 @@ abstract class P11Key implements Key, Length {
fetchValues();
return coeff;
}
public String toString() {
fetchValues();
StringBuilder sb = new StringBuilder(super.toString());
sb.append("\n modulus: ");
sb.append(n);
sb.append("\n public exponent: ");
sb.append(e);
sb.append("\n private exponent: ");
sb.append(d);
sb.append("\n prime p: ");
sb.append(p);
sb.append("\n prime q: ");
sb.append(q);
sb.append("\n prime exponent p: ");
sb.append(pe);
sb.append("\n prime exponent q: ");
sb.append(qe);
sb.append("\n crt coefficient: ");
sb.append(coeff);
return sb.toString();
}
}
// RSA non-CRT private key
@ -630,15 +609,6 @@ abstract class P11Key implements Key, Length {
fetchValues();
return d;
}
public String toString() {
fetchValues();
StringBuilder sb = new StringBuilder(super.toString());
sb.append("\n modulus: ");
sb.append(n);
sb.append("\n private exponent: ");
sb.append(d);
return sb.toString();
}
}
private static final class P11RSAPublicKey extends P11Key
@ -814,11 +784,6 @@ abstract class P11Key implements Key, Length {
fetchValues();
return params;
}
public String toString() {
fetchValues();
return super.toString() + "\n x: " + x + "\n p: " + params.getP()
+ "\n q: " + params.getQ() + "\n g: " + params.getG();
}
}
private static final class P11DHPrivateKey extends P11Key
@ -878,11 +843,6 @@ abstract class P11Key implements Key, Length {
fetchValues();
return params;
}
public String toString() {
fetchValues();
return super.toString() + "\n x: " + x + "\n p: " + params.getP()
+ "\n g: " + params.getG();
}
public int hashCode() {
if (token.isValid() == false) {
return 0;
@ -1049,12 +1009,6 @@ abstract class P11Key implements Key, Length {
fetchValues();
return params;
}
public String toString() {
fetchValues();
return super.toString()
+ "\n private value: " + s
+ "\n parameters: " + params;
}
}
private static final class P11ECPublicKey extends P11Key

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 1996, 2002, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -142,11 +142,6 @@ implements java.security.interfaces.DSAPrivateKey, Serializable {
}
}
public String toString() {
return "Sun DSA Private Key \nparameters:" + algid + "\nx: " +
Debug.toHexString(x) + "\n";
}
protected void parseKeyBits() throws InvalidKeyException {
try {
DerInputStream in = new DerInputStream(key);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -225,29 +225,4 @@ public final class RSAPrivateCrtKeyImpl
}
return b;
}
// return a string representation of this key for debugging
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Sun RSA private CRT key, ");
sb.append(n.bitLength());
sb.append(" bits\n modulus: ");
sb.append(n);
sb.append("\n public exponent: ");
sb.append(e);
sb.append("\n private exponent: ");
sb.append(d);
sb.append("\n prime p: ");
sb.append(p);
sb.append("\n prime q: ");
sb.append(q);
sb.append("\n prime exponent p: ");
sb.append(pe);
sb.append("\n prime exponent q: ");
sb.append(qe);
sb.append("\n crt coefficient: ");
sb.append(coeff);
return sb.toString();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -98,11 +98,4 @@ public final class RSAPrivateKeyImpl extends PKCS8Key implements RSAPrivateKey {
public BigInteger getPrivateExponent() {
return d;
}
// return a string representation of this key for debugging
public String toString() {
return "Sun RSA private key, " + n.bitLength() + " bits\n modulus: "
+ n + "\n private exponent: " + d;
}
}

View File

@ -30,6 +30,7 @@ import java.lang.reflect.AccessibleObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.UIDefaults;
import sun.reflect.misc.ReflectUtil;
/**
* SwingLazyValue is a copy of ProxyLazyValue that does not snapshot the
@ -63,7 +64,7 @@ public class SwingLazyValue implements UIDefaults.LazyValue {
public Object createValue(final UIDefaults table) {
try {
Object cl;
ReflectUtil.checkPackageAccess(className);
Class<?> c = Class.forName(className, true, null);
if (methodName != null) {
Class[] types = getClassArray(args);

View File

@ -1360,6 +1360,19 @@ public class SwingUtilities2 {
}
}
/**
* Utility method that throws SecurityException if SecurityManager is set
* and modifiers are not public
*
* @param modifiers a set of modifiers
*/
public static void checkAccess(int modifiers) {
if (System.getSecurityManager() != null
&& !Modifier.isPublic(modifiers)) {
throw new SecurityException("Resource is not accessible");
}
}
/**
* Returns true if EventQueue.getCurrentEvent() has the permissions to
* access the system clipboard and if it is allowed gesture (if

View File

@ -527,7 +527,12 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum)
jmethodID method;
info = get_info(index);
HPROF_ASSERT(mnum < info->method_count);
if (mnum >= info->method_count) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
(*env)->ThrowNew(env, newExcCls, "Illegal mnum");
return NULL;
}
method = info->method[mnum].method_id;
if ( method == NULL ) {
char * name;
@ -535,7 +540,12 @@ class_get_methodID(JNIEnv *env, ClassIndex index, MethodIndex mnum)
jclass clazz;
name = (char *)string_get(info->method[mnum].name_index);
HPROF_ASSERT(name!=NULL);
if (name==NULL) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
(*env)->ThrowNew(env, newExcCls, "Name not found");
return NULL;
}
sig = (char *)string_get(info->method[mnum].sig_index);
HPROF_ASSERT(sig!=NULL);
clazz = class_get_class(env, index);

View File

@ -195,7 +195,12 @@ event_call(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
HPROF_ASSERT(env!=NULL);
HPROF_ASSERT(thread!=NULL);
HPROF_ASSERT(cnum!=0 && cnum!=gdata->tracker_cnum);
if (cnum == 0 || cnum == gdata->tracker_cnum) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
(*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
return;
}
/* Prevent recursion into any BCI function for this thread (pstatus). */
if ( tls_get_tracker_status(env, thread, JNI_FALSE,
@ -204,8 +209,10 @@ event_call(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
(*pstatus) = 1;
method = class_get_methodID(env, cnum, mnum);
HPROF_ASSERT(method!=NULL);
tls_push_method(tls_index, method);
if (method != NULL) {
tls_push_method(tls_index, method);
}
(*pstatus) = 0;
}
}
@ -248,7 +255,13 @@ event_return(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
HPROF_ASSERT(env!=NULL);
HPROF_ASSERT(thread!=NULL);
HPROF_ASSERT(cnum!=0 && cnum!=gdata->tracker_cnum);
if (cnum == 0 || cnum == gdata->tracker_cnum) {
jclass newExcCls = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
(*env)->ThrowNew(env, newExcCls, "Illegal cnum.");
return;
}
/* Prevent recursion into any BCI function for this thread (pstatus). */
if ( tls_get_tracker_status(env, thread, JNI_FALSE,
@ -257,8 +270,10 @@ event_return(JNIEnv *env, jthread thread, ClassIndex cnum, MethodIndex mnum)
(*pstatus) = 1;
method = class_get_methodID(env, cnum, mnum);
HPROF_ASSERT(method!=NULL);
tls_pop_method(tls_index, thread, method);
if (method != NULL) {
tls_pop_method(tls_index, thread, method);
}
(*pstatus) = 0;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -340,6 +340,10 @@ uLong jar::get_dostime(int modtime) {
struct tm sbuf;
(void)memset((void*)&sbuf,0, sizeof(sbuf));
struct tm* s = gmtime_r(&t, &sbuf);
if (s == NULL) {
fprintf(u->errstrm, "Error: gmtime failure, invalid input archive\n");
exit(2);
}
modtime_cache = modtime;
dostime_cache = dostime(s->tm_year + 1900, s->tm_mon + 1, s->tm_mday,
s->tm_hour, s->tm_min, s->tm_sec);
@ -384,7 +388,7 @@ bool jar::deflate_bytes(bytes& head, bytes& tail) {
}
deflated.empty();
zs.next_out = (uchar*) deflated.grow(len + (len/2));
zs.next_out = (uchar*) deflated.grow(add_size(len, (len/2)));
zs.avail_out = (int)deflated.size();
zs.next_in = (uchar*)head.ptr;

View File

@ -69,7 +69,7 @@ static JNINativeMethod methods[] = {
{"getDeclaredConstructors0","(Z)[" CTR, (void *)&JVM_GetClassDeclaredConstructors},
{"getProtectionDomain0", "()" PD, (void *)&JVM_GetProtectionDomain},
{"getDeclaredClasses0", "()[" CLS, (void *)&JVM_GetDeclaredClasses},
{"getDeclaringClass", "()" CLS, (void *)&JVM_GetDeclaringClass},
{"getDeclaringClass0", "()" CLS, (void *)&JVM_GetDeclaringClass},
{"getGenericSignature0", "()" STR, (void *)&JVM_GetClassSignature},
{"getRawAnnotations", "()" BA, (void *)&JVM_GetClassAnnotations},
{"getConstantPool", "()" CPL, (void *)&JVM_GetClassConstantPool},

View File

@ -33,6 +33,8 @@
*/
jclass ia6_class;
jfieldID ia6_holder6ID;
jfieldID ia6_ipaddressID;
jfieldID ia6_scopeidID;
jfieldID ia6_cachedscopeidID;
@ -47,19 +49,24 @@ jmethodID ia6_ctrID;
*/
JNIEXPORT void JNICALL
Java_java_net_Inet6Address_init(JNIEnv *env, jclass cls) {
jclass ia6h_class;
jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
CHECK_NULL(c);
ia6_class = (*env)->NewGlobalRef(env, c);
CHECK_NULL(ia6_class);
ia6_ipaddressID = (*env)->GetFieldID(env, ia6_class, "ipaddress", "[B");
ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
CHECK_NULL(ia6h_class);
ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
CHECK_NULL(ia6_holder6ID);
ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
CHECK_NULL(ia6_ipaddressID);
ia6_scopeidID = (*env)->GetFieldID(env, ia6_class, "scope_id", "I");
ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
CHECK_NULL(ia6_scopeidID);
ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
CHECK_NULL(ia6_cachedscopeidID);
ia6_scopeidsetID = (*env)->GetFieldID(env, ia6_class, "scope_id_set", "Z");
ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
CHECK_NULL(ia6_scopeidID);
ia6_scopeifnameID = (*env)->GetFieldID(env, ia6_class, "scope_ifname", "Ljava/net/NetworkInterface;");
ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
CHECK_NULL(ia6_scopeifnameID);
ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
CHECK_NULL(ia6_ctrID);

View File

@ -94,6 +94,92 @@ extern jfieldID ia_holderID;
extern jfieldID iac_addressID;
extern jfieldID iac_familyID;
/**
* set_ methods return JNI_TRUE on success JNI_FALSE on error
* get_ methods that return +ve int return -1 on error
* get_ methods that return objects return NULL on error.
*/
jobject getInet6Address_scopeifname(JNIEnv *env, jobject iaObj) {
jobject holder;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, NULL);
return (*env)->GetObjectField(env, holder, ia6_scopeifnameID);
}
int setInet6Address_scopeifname(JNIEnv *env, jobject iaObj, jobject scopeifname) {
jobject holder;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, JNI_FALSE);
(*env)->SetObjectField(env, holder, ia6_scopeifnameID, scopeifname);
return JNI_TRUE;
}
int getInet6Address_scopeid_set(JNIEnv *env, jobject iaObj) {
jobject holder;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, -1);
return (*env)->GetBooleanField(env, holder, ia6_scopeidsetID);
}
int getInet6Address_scopeid(JNIEnv *env, jobject iaObj) {
jobject holder;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, -1);
return (*env)->GetIntField(env, holder, ia6_scopeidID);
}
int setInet6Address_scopeid(JNIEnv *env, jobject iaObj, int scopeid) {
jobject holder;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, JNI_FALSE);
(*env)->SetIntField(env, holder, ia6_scopeidID, scopeid);
if (scopeid > 0) {
(*env)->SetBooleanField(env, holder, ia6_scopeidsetID, JNI_TRUE);
}
return JNI_TRUE;
}
int getInet6Address_ipaddress(JNIEnv *env, jobject iaObj, char *dest) {
jobject holder, addr;
jbyteArray barr;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, JNI_FALSE);
addr = (*env)->GetObjectField(env, holder, ia6_ipaddressID);
CHECK_NULL_RETURN(addr, JNI_FALSE);
(*env)->GetByteArrayRegion(env, addr, 0, 16, (jbyte *)dest);
return JNI_TRUE;
}
int setInet6Address_ipaddress(JNIEnv *env, jobject iaObj, char *address) {
jobject holder;
jbyteArray addr;
initInetAddrs(env);
holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
CHECK_NULL_RETURN(holder, JNI_FALSE);
addr = (jbyteArray)(*env)->GetObjectField(env, holder, ia6_ipaddressID);
if (addr == NULL) {
addr = (*env)->NewByteArray(env, 16);
CHECK_NULL_RETURN(addr, JNI_FALSE);
(*env)->SetObjectField(env, holder, ia6_ipaddressID, addr);
}
(*env)->SetByteArrayRegion(env, addr, 0, 16, (jbyte *)address);
return JNI_TRUE;
}
void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address) {
jobject holder;
initInetAddrs(env);
@ -168,6 +254,7 @@ NET_SockaddrToInetAddress(JNIEnv *env, struct sockaddr *him, int *port) {
} else {
static jclass inet6Cls = 0;
jint scope;
int ret;
if (inet6Cls == 0) {
jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
CHECK_NULL_RETURN(c, NULL);
@ -177,18 +264,11 @@ NET_SockaddrToInetAddress(JNIEnv *env, struct sockaddr *him, int *port) {
}
iaObj = (*env)->NewObject(env, inet6Cls, ia6_ctrID);
CHECK_NULL_RETURN(iaObj, NULL);
ipaddress = (*env)->NewByteArray(env, 16);
CHECK_NULL_RETURN(ipaddress, NULL);
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(him6->sin6_addr));
(*env)->SetObjectField(env, iaObj, ia6_ipaddressID, ipaddress);
ret = setInet6Address_ipaddress(env, iaObj, (char *)&(him6->sin6_addr));
CHECK_NULL_RETURN(ret, NULL);
setInetAddress_family(env, iaObj, IPv6);
scope = getScopeID(him);
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
if (scope > 0)
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
setInet6Address_scopeid(env, iaObj, scope);
}
*port = ntohs(him6->sin6_port);
} else
@ -248,9 +328,8 @@ NET_SockaddrEqualsInetAddress(JNIEnv *env, struct sockaddr *him, jobject iaObj)
if (family == AF_INET) {
return JNI_FALSE;
}
ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
scope = (*env)->GetIntField(env, iaObj, ia6_scopeidID);
(*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddrCur);
scope = getInet6Address_scopeid(env, iaObj);
getInet6Address_ipaddress(env, iaObj, (char *)caddrCur);
if (NET_IsEqual(caddrNew, caddrCur) && cmpScopeID(scope, him)) {
return JNI_TRUE;
} else {

View File

@ -58,6 +58,19 @@ extern jfieldID iac_familyID;
extern jfieldID iac_hostNameID;
extern jfieldID ia_preferIPv6AddressID;
/** (Inet6Address accessors)
* set_ methods return JNI_TRUE on success JNI_FALSE on error
* get_ methods that return int/boolean, return -1 on error
* get_ methods that return objects return NULL on error.
*/
extern jobject getInet6Address_scopeifname(JNIEnv *env, jobject ia6Obj);
extern int setInet6Address_scopeifname(JNIEnv *env, jobject ia6Obj, jobject scopeifname);
extern int getInet6Address_scopeid_set(JNIEnv *env, jobject ia6Obj);
extern int getInet6Address_scopeid(JNIEnv *env, jobject ia6Obj);
extern int setInet6Address_scopeid(JNIEnv *env, jobject ia6Obj, int scopeid);
extern int getInet6Address_ipaddress(JNIEnv *env, jobject ia6Obj, char *dest);
extern int setInet6Address_ipaddress(JNIEnv *env, jobject ia6Obj, char *address);
extern void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address);
extern void setInetAddress_family(JNIEnv *env, jobject iaObj, int family);
extern void setInetAddress_hostName(JNIEnv *env, jobject iaObj, jobject h);
@ -93,12 +106,12 @@ extern jfieldID dp_bufLengthID;
/* Inet6Address fields */
extern jclass ia6_class;
extern jfieldID ia6_holder6ID;
extern jfieldID ia6_ipaddressID;
extern jfieldID ia6_scopeidID;
extern jfieldID ia6_cachedscopeidID;
extern jfieldID ia6_scopeidsetID;
extern jfieldID ia6_scopeifnameID;
extern jfieldID ia6_scopeifnamesetID;
extern jmethodID ia6_ctrID;
/************************************************************************

View File

@ -873,363 +873,204 @@ setHints(JNIEnv *env, BufImageS_t *imageP) {
return 1;
}
/*
* This routine will fill in a buffer of data for either 1 band or all
* bands (if band == -1).
*/
#define MAX_TO_GRAB (10240)
int awt_getPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned char *bufferP) {
int w = rasterP->width;
int h = rasterP->height;
int numBands = rasterP->numBands;
typedef union {
void *pv;
unsigned char *pb;
unsigned short *ps;
} PixelData_t;
int awt_getPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
const int w = rasterP->width;
const int h = rasterP->height;
const int numBands = rasterP->numBands;
int y;
int i;
int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
int maxLines;
jobject jsm;
int off;
int off = 0;
jarray jdata = NULL;
jobject jdatabuffer;
int *dataP;
int maxBytes = w;
int maxSamples;
PixelData_t p;
if (bufferP == NULL) {
return -1;
}
if (rasterP->dataType != BYTE_DATA_TYPE &&
rasterP->dataType != SHORT_DATA_TYPE)
{
return -1;
}
p.pv = bufferP;
if (!SAFE_TO_MULT(w, numBands)) {
return -1;
}
maxSamples = w * numBands;
maxLines = maxSamples > MAX_TO_GRAB ? 1 : (MAX_TO_GRAB / maxSamples);
if (maxLines > h) {
maxLines = h;
}
if (!SAFE_TO_MULT(maxSamples, maxLines)) {
return -1;
}
maxSamples *= maxLines;
jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
g_RasterDataBufferID);
jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
jdata = (*env)->NewIntArray(env, maxSamples);
if (JNU_IsNull(env, jdata)) {
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
/* Here is the generic code */
if (band >= 0) {
int dOff;
if (band >= numBands) {
for (y = 0; y < h; y += maxLines) {
if (y + maxLines > h) {
maxLines = h - y;
maxSamples = w * numBands * maxLines;
}
(*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
if ((*env)->ExceptionOccurred(env)) {
(*env)->DeleteLocalRef(env, jdata);
JNU_ThrowInternalError(env, "Band out of range.");
return -1;
}
off = 0;
for (y=0; y < h; ) {
(*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
dOff = band;
for (i=0; i < maxBytes; i++, dOff += numBands) {
bufferP[off++] = (unsigned char) dataP[dOff];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
if (y+maxLines < h) {
y += maxLines;
}
else {
y++;
maxBytes = w;
}
}
}
else {
off = 0;
maxBytes *= numBands;
for (y=0; y < h; ) {
(*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
for (i=0; i < maxBytes; i++) {
bufferP[off++] = (unsigned char) dataP[i];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
if (y+maxLines < h) {
y += maxLines;
}
else {
y++;
maxBytes = w*numBands;
}
}
}
(*env)->DeleteLocalRef(env, jdata);
return 0;
}
int awt_setPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned char *bufferP) {
int w = rasterP->width;
int h = rasterP->height;
int numBands = rasterP->numBands;
int y;
int i;
int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
jobject jsm;
int off;
jarray jdata = NULL;
jobject jdatabuffer;
int *dataP;
int maxBytes = w;
jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
g_RasterDataBufferID);
/* Here is the generic code */
jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
if (JNU_IsNull(env, jdata)) {
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
if (band >= 0) {
int dOff;
if (band >= numBands) {
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
JNU_ThrowInternalError(env, "Band out of range.");
return -1;
}
off = 0;
for (y=0; y < h; y+=maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
}
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
dOff = band;
for (i=0; i < maxBytes; i++, dOff += numBands) {
dataP[dOff] = bufferP[off++];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
(*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
}
}
else {
off = 0;
maxBytes *= numBands;
for (y=0; y < h; y+=maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
switch (rasterP->dataType) {
case BYTE_DATA_TYPE:
for (i = 0; i < maxSamples; i ++) {
p.pb[off++] = (unsigned char) dataP[i];
}
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
break;
case SHORT_DATA_TYPE:
for (i = 0; i < maxSamples; i ++) {
p.ps[off++] = (unsigned short) dataP[i];
}
for (i=0; i < maxBytes; i++) {
dataP[i] = bufferP[off++];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
(*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
break;
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
}
(*env)->DeleteLocalRef(env, jdata);
return 0;
return 1;
}
int awt_getPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned short *bufferP) {
int w = rasterP->width;
int h = rasterP->height;
int numBands = rasterP->numBands;
int awt_setPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP) {
const int w = rasterP->width;
const int h = rasterP->height;
const int numBands = rasterP->numBands;
int y;
int i;
int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
int maxLines;
jobject jsm;
int off;
int off = 0;
jarray jdata = NULL;
jobject jdatabuffer;
int *dataP;
int maxBytes = w*maxLines;
int maxSamples;
PixelData_t p;
if (bufferP == NULL) {
return -1;
}
if (rasterP->dataType != BYTE_DATA_TYPE &&
rasterP->dataType != SHORT_DATA_TYPE)
{
return -1;
}
p.pv = bufferP;
if (!SAFE_TO_MULT(w, numBands)) {
return -1;
}
maxSamples = w * numBands;
maxLines = maxSamples > MAX_TO_GRAB ? 1 : (MAX_TO_GRAB / maxSamples);
if (maxLines > h) {
maxLines = h;
}
if (!SAFE_TO_MULT(maxSamples, maxLines)) {
return -1;
}
maxSamples *= maxLines;
jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
g_RasterDataBufferID);
jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
jdata = (*env)->NewIntArray(env, maxSamples);
if (JNU_IsNull(env, jdata)) {
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
/* Here is the generic code */
if (band >= 0) {
int dOff;
if (band >= numBands) {
for (y = 0; y < h; y += maxLines) {
if (y + maxLines > h) {
maxLines = h - y;
maxSamples = w * numBands * maxLines;
}
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
JNU_ThrowInternalError(env, "Band out of range.");
return -1;
}
off = 0;
for (y=0; y < h; y += maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
}
(*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
dOff = band;
for (i=0; i < maxBytes; i++, dOff += numBands) {
bufferP[off++] = (unsigned short) dataP[dOff];
switch (rasterP->dataType) {
case BYTE_DATA_TYPE:
for (i = 0; i < maxSamples; i ++) {
dataP[i] = p.pb[off++];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
}
}
else {
off = 0;
maxBytes *= numBands;
for (y=0; y < h; y+=maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
break;
case SHORT_DATA_TYPE:
for (i = 0; i < maxSamples; i ++) {
dataP[i] = p.ps[off++];
}
(*env)->CallObjectMethod(env, jsm, g_SMGetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
for (i=0; i < maxBytes; i++) {
bufferP[off++] = (unsigned short) dataP[i];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
break;
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
(*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
if ((*env)->ExceptionOccurred(env)) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
}
(*env)->DeleteLocalRef(env, jdata);
return 0;
}
int awt_setPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned short *bufferP) {
int w = rasterP->width;
int h = rasterP->height;
int numBands = rasterP->numBands;
int y;
int i;
int maxLines = (h < MAX_TO_GRAB/w ? h : MAX_TO_GRAB/w);
jobject jsm;
int off;
jarray jdata = NULL;
jobject jdatabuffer;
int *dataP;
int maxBytes = w;
jsm = (*env)->GetObjectField(env, rasterP->jraster, g_RasterSampleModelID);
jdatabuffer = (*env)->GetObjectField(env, rasterP->jraster,
g_RasterDataBufferID);
if (band >= numBands) {
JNU_ThrowInternalError(env, "Band out of range.");
return -1;
}
/* Here is the generic code */
jdata = (*env)->NewIntArray(env, maxBytes*rasterP->numBands*maxLines);
if (JNU_IsNull(env, jdata)) {
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
if (band >= 0) {
int dOff;
off = 0;
for (y=0; y < h; y+=maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
}
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
dOff = band;
for (i=0; i < maxBytes; i++, dOff += numBands) {
dataP[dOff] = bufferP[off++];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
(*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
}
}
else {
off = 0;
maxBytes *= numBands;
for (y=0; y < h; y+=maxLines) {
if (y+maxLines > h) {
maxBytes = w*numBands;
maxLines = h - y;
}
dataP = (int *) (*env)->GetPrimitiveArrayCritical(env, jdata,
NULL);
if (dataP == NULL) {
(*env)->DeleteLocalRef(env, jdata);
return -1;
}
for (i=0; i < maxBytes; i++) {
dataP[i] = bufferP[off++];
}
(*env)->ReleasePrimitiveArrayCritical(env, jdata, dataP,
JNI_ABORT);
(*env)->CallVoidMethod(env, jsm, g_SMSetPixelsMID,
0, y, w,
maxLines, jdata, jdatabuffer);
}
}
(*env)->DeleteLocalRef(env, jdata);
return 0;
return 1;
}

View File

@ -188,13 +188,8 @@ void awt_freeParsedRaster(RasterS_t *rasterP, int freeRasterP);
void awt_freeParsedImage(BufImageS_t *imageP, int freeImageP);
int awt_getPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned char *bufferP);
int awt_setPixelByte(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned char *bufferP);
int awt_getPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned short *bufferP);
int awt_setPixelShort(JNIEnv *env, int band, RasterS_t *rasterP,
unsigned short *bufferP);
int awt_getPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP);
int awt_setPixels(JNIEnv *env, RasterS_t *rasterP, void *bufferP);
#endif /* AWT_PARSE_IMAGE_H */

View File

@ -2705,6 +2705,15 @@ Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
bandSize = (*env)->GetIntArrayElements(env, bandSizes, NULL);
for (i = 0; i < numBands; i++) {
if (bandSize[i] <= 0 || bandSize[i] > JPEG_BAND_SIZE) {
(*env)->ReleaseIntArrayElements(env, bandSizes,
bandSize, JNI_ABORT);
JNU_ThrowByName(env, "javax/imageio/IIOException", "Invalid Image");
return JNI_FALSE;;
}
}
for (i = 0; i < numBands; i++) {
if (bandSize[i] != JPEG_BAND_SIZE) {
if (scale == NULL) {

View File

@ -700,22 +700,7 @@ Java_sun_awt_image_ImagingLib_convolveRaster(JNIEnv *env, jobject this,
/* Means that we couldn't write directly into the destination buffer */
if (ddata == NULL) {
unsigned char *bdataP;
unsigned short *sdataP;
/* Punt for now */
switch (dstRasterP->dataType) {
case BYTE_DATA_TYPE:
bdataP = (unsigned char *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
break;
case SHORT_DATA_TYPE:
sdataP = (unsigned short *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
break;
default:
retStatus = 0;
}
retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
}
/* Release the pinned memory */
@ -1119,24 +1104,9 @@ fprintf(stderr,"Flags : %d\n",dst->flags);
/* Means that we couldn't write directly into the destination buffer */
if (ddata == NULL) {
unsigned char *bdataP;
unsigned short *sdataP;
/* Need to store it back into the array */
if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
/* Punt for now */
switch (dst->type) {
case MLIB_BYTE:
bdataP = (unsigned char *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
break;
case MLIB_SHORT:
sdataP = (unsigned short *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
break;
default:
retStatus = 0;
}
retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
}
}
@ -1704,21 +1674,7 @@ Java_sun_awt_image_ImagingLib_lookupByteRaster(JNIEnv *env,
* the destination buffer
*/
if (ddata == NULL) {
unsigned char* bdataP;
unsigned short* sdataP;
switch (dstRasterP->dataType) {
case BYTE_DATA_TYPE:
bdataP = (unsigned char *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelByte(env, -1, dstRasterP, bdataP) >= 0) ;
break;
case SHORT_DATA_TYPE:
sdataP = (unsigned short *) mlib_ImageGetData(dst);
retStatus = (awt_setPixelShort(env, -1, dstRasterP, sdataP) >= 0) ;
break;
default:
retStatus = 0;
}
retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
}
/* Release the LUT */
@ -2029,21 +1985,25 @@ expandPacked(JNIEnv *env, BufImageS_t *img, ColorModelS_t *cmP,
return 0;
}
#define NUM_LINES 10
static int
cvtCustomToDefault(JNIEnv *env, BufImageS_t *imageP, int component,
unsigned char *dataP) {
ColorModelS_t *cmP = &imageP->cmodel;
RasterS_t *rasterP = &imageP->raster;
const RasterS_t *rasterP = &imageP->raster;
const int w = rasterP->width;
const int h = rasterP->height;
int y;
jobject jpixels = NULL;
jintArray jpixels = NULL;
jint *pixels;
unsigned char *dP = dataP;
#define NUM_LINES 10
int numLines = NUM_LINES;
int numLines = h > NUM_LINES ? NUM_LINES : h;
/* it is safe to calculate the scan length, because width has been verified
* on creation of the mlib image
*/
int scanLength = rasterP->width * 4;
const int scanLength = w * 4;
int nbytes = 0;
if (!SAFE_TO_MULT(numLines, scanLength)) {
@ -2052,42 +2012,70 @@ cvtCustomToDefault(JNIEnv *env, BufImageS_t *imageP, int component,
nbytes = numLines * scanLength;
for (y=0; y < rasterP->height; y+=numLines) {
/* getData, one scanline at a time */
if (y+numLines > rasterP->height) {
numLines = rasterP->height - y;
jpixels = (*env)->NewIntArray(env, nbytes);
if (JNU_IsNull(env, jpixels)) {
JNU_ThrowOutOfMemoryError(env, "Out of Memory");
return -1;
}
for (y = 0; y < h; y += numLines) {
if (y + numLines > h) {
numLines = h - y;
nbytes = numLines * scanLength;
}
jpixels = (*env)->CallObjectMethod(env, imageP->jimage,
g_BImgGetRGBMID, 0, y,
rasterP->width, numLines,
jpixels,0, rasterP->width);
if (jpixels == NULL) {
JNU_ThrowInternalError(env, "Can't retrieve pixels.");
(*env)->CallObjectMethod(env, imageP->jimage,
g_BImgGetRGBMID, 0, y,
w, numLines,
jpixels, 0, w);
if ((*env)->ExceptionOccurred(env)) {
(*env)->DeleteLocalRef(env, jpixels);
return -1;
}
pixels = (*env)->GetPrimitiveArrayCritical(env, jpixels, NULL);
if (pixels == NULL) {
(*env)->DeleteLocalRef(env, jpixels);
return -1;
}
memcpy(dP, pixels, nbytes);
dP += nbytes;
(*env)->ReleasePrimitiveArrayCritical(env, jpixels, pixels,
JNI_ABORT);
}
/* Need to release the array */
(*env)->DeleteLocalRef(env, jpixels);
return 0;
}
static int
cvtDefaultToCustom(JNIEnv *env, BufImageS_t *imageP, int component,
unsigned char *dataP) {
ColorModelS_t *cmP = &imageP->cmodel;
RasterS_t *rasterP = &imageP->raster;
const RasterS_t *rasterP = &imageP->raster;
const int w = rasterP->width;
const int h = rasterP->height;
int y;
jintArray jpixels = NULL;
jint *pixels;
unsigned char *dP = dataP;
#define NUM_LINES 10
int numLines = NUM_LINES;
int nbytes = rasterP->width*4*NUM_LINES;
jintArray jpixels;
int numLines = h > NUM_LINES ? NUM_LINES : h;
/* it is safe to calculate the scan length, because width has been verified
* on creation of the mlib image
*/
const int scanLength = w * 4;
int nbytes = 0;
if (!SAFE_TO_MULT(numLines, scanLength)) {
return -1;
}
nbytes = numLines * scanLength;
jpixels = (*env)->NewIntArray(env, nbytes);
if (JNU_IsNull(env, jpixels)) {
@ -2095,14 +2083,15 @@ cvtDefaultToCustom(JNIEnv *env, BufImageS_t *imageP, int component,
return -1;
}
for (y=0; y < rasterP->height; y+=NUM_LINES) {
if (y+numLines > rasterP->height) {
numLines = rasterP->height - y;
nbytes = rasterP->width*4*numLines;
for (y = 0; y < h; y += numLines) {
if (y + numLines > h) {
numLines = h - y;
nbytes = numLines * scanLength;
}
pixels = (*env)->GetPrimitiveArrayCritical(env, jpixels, NULL);
if (pixels == NULL) {
/* JNI error */
(*env)->DeleteLocalRef(env, jpixels);
return -1;
}
@ -2111,12 +2100,11 @@ cvtDefaultToCustom(JNIEnv *env, BufImageS_t *imageP, int component,
(*env)->ReleasePrimitiveArrayCritical(env, jpixels, pixels, 0);
/* setData, one scanline at a time */
/* Fix 4223648, 4184283 */
(*env)->CallVoidMethod(env, imageP->jimage, g_BImgSetRGBMID, 0, y,
rasterP->width, numLines, jpixels, 0,
rasterP->width);
w, numLines, jpixels,
0, w);
if ((*env)->ExceptionOccurred(env)) {
(*env)->DeleteLocalRef(env, jpixels);
return -1;
}
}
@ -2298,7 +2286,6 @@ allocateRasterArray(JNIEnv *env, RasterS_t *rasterP,
mlib_image **mlibImagePP, void **dataPP, int isSrc) {
void *dataP;
unsigned char *cDataP;
unsigned short *sdataP;
int dataType = BYTE_DATA_TYPE;
int width;
int height;
@ -2484,8 +2471,7 @@ allocateRasterArray(JNIEnv *env, RasterS_t *rasterP,
return -1;
}
if (isSrc) {
cDataP = (unsigned char *) mlib_ImageGetData(*mlibImagePP);
if (awt_getPixelByte(env, -1, rasterP, cDataP) < 0) {
if (awt_getPixels(env, rasterP, mlib_ImageGetData(*mlibImagePP)) < 0) {
(*sMlibSysFns.deleteImageFP)(*mlibImagePP);
return -1;
}
@ -2499,8 +2485,7 @@ allocateRasterArray(JNIEnv *env, RasterS_t *rasterP,
return -1;
}
if (isSrc) {
sdataP = (unsigned short *) mlib_ImageGetData(*mlibImagePP);
if (awt_getPixelShort(env, -1, rasterP, sdataP) < 0) {
if (awt_getPixels(env, rasterP, mlib_ImageGetData(*mlibImagePP)) < 0) {
(*sMlibSysFns.deleteImageFP)(*mlibImagePP);
return -1;
}
@ -2550,60 +2535,6 @@ freeDataArray(JNIEnv *env, jobject srcJdata, mlib_image *srcmlibImP,
}
}
static int
storeDstArray(JNIEnv *env, BufImageS_t *srcP, BufImageS_t *dstP,
mlibHintS_t *hintP, mlib_image *mlibImP, void *ddata) {
RasterS_t *rasterP = &dstP->raster;
/* Nothing to do since it is the same image type */
if (srcP->imageType == dstP->imageType
&& srcP->imageType != java_awt_image_BufferedImage_TYPE_CUSTOM
&& srcP->imageType != java_awt_image_BufferedImage_TYPE_BYTE_INDEXED
&& srcP->imageType != java_awt_image_BufferedImage_TYPE_BYTE_BINARY) {
/* REMIND: Should check the ICM LUTS to see if it is the same */
return 0;
}
/* These types are compatible with TYPE_INT_RGB */
if (srcP->imageType == java_awt_image_BufferedImage_TYPE_INT_RGB
&& (dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB ||
dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_ARGB_PRE)){
return 0;
}
if (hintP->cvtSrcToDefault &&
(srcP->cmodel.isAlphaPre == dstP->cmodel.isAlphaPre)) {
if (srcP->cmodel.isAlphaPre) {
if (dstP->imageType ==
java_awt_image_BufferedImage_TYPE_INT_ARGB_PRE)
{
return 0;
}
if (!srcP->cmodel.supportsAlpha &&
dstP->imageType == java_awt_image_BufferedImage_TYPE_INT_RGB){
return 0;
}
}
else {
/* REMIND: */
}
}
if (dstP->cmodel.cmType == DIRECT_CM_TYPE) {
/* Just need to move bits */
if (mlibImP->type == MLIB_BYTE) {
return awt_setPixelByte(env, -1, &dstP->raster,
(unsigned char *) mlibImP->data);
}
else if (mlibImP->type == MLIB_SHORT) {
return awt_setPixelByte(env, -1, &dstP->raster,
(unsigned char *) mlibImP->data);
}
}
return 0;
}
#define ERR_BAD_IMAGE_LAYOUT (-2)
#define CHECK_DST_ARRAY(start_offset, elements_per_scan, elements_per_pixel) \
@ -2709,8 +2640,7 @@ storeImageArray(JNIEnv *env, BufImageS_t *srcP, BufImageS_t *dstP,
}
}
else if (mlibImP->type == MLIB_SHORT) {
return awt_setPixelShort(env, -1, rasterP,
(unsigned short *) mlibImP->data);
return awt_setPixels(env, rasterP, mlibImP->data);
}
}
else {

View File

@ -104,6 +104,10 @@ Java_sun_font_SunLayoutEngine_initGVIDs
int putGV(JNIEnv* env, jint gmask, jint baseIndex, jobject gvdata, const LayoutEngine* engine, int glyphCount) {
int count = env->GetIntField(gvdata, gvdCountFID);
if (count < 0) {
JNU_ThrowInternalError(env, "count negative");
return 0;
}
jarray glyphArray = (jarray)env->GetObjectField(gvdata, gvdGlyphsFID);
if (IS_NULL(glyphArray)) {

View File

@ -1074,6 +1074,27 @@ cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number
}
static
cmsBool SanityCheck(_cmsICCPROFILE* profile)
{
cmsIOHANDLER* io = profile->IOhandler;
if (!io) {
return FALSE;
}
if (!io->Seek ||
!(io->Seek==NULLSeek || io->Seek==MemorySeek || io->Seek==FileSeek))
{
return FALSE;
}
if (!io->Read ||
!(io->Read==NULLRead || io->Read==MemoryRead || io->Read==FileRead))
{
return FALSE;
}
return TRUE;
}
// Dump tag contents. If the profile is being modified, untouched tags are copied from FileOrig
static
@ -1087,6 +1108,7 @@ cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
cmsTagTypeSignature TypeBase;
cmsTagTypeHandler* TypeHandler;
if (!SanityCheck(FileOrig)) return FALSE;
for (i=0; i < Icc -> TagCount; i++) {
@ -1292,8 +1314,8 @@ cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUIn
// Should we just calculate the needed space?
if (MemPtr == NULL) {
*BytesNeeded = cmsSaveProfileToIOhandler(hProfile, NULL);
return TRUE;
*BytesNeeded = cmsSaveProfileToIOhandler(hProfile, NULL);
return (*BytesNeeded == 0 ? FALSE : TRUE);
}
// That is a real write operation

View File

@ -29,7 +29,7 @@
#include "sun_management_HotSpotDiagnostic.h"
JNIEXPORT void JNICALL
Java_sun_management_HotSpotDiagnostic_dumpHeap
Java_sun_management_HotSpotDiagnostic_dumpHeap0
(JNIEnv *env, jobject dummy, jstring outputfile, jboolean live)
{
jmm_interface->DumpHeap0(env, outputfile, live);

View File

@ -957,9 +957,27 @@ static void* hSplashLib = NULL;
void* SplashProcAddress(const char* name) {
if (!hSplashLib) {
const char * splashLibPath;
splashLibPath = SPLASHSCREEN_SO;
hSplashLib = dlopen(splashLibPath, RTLD_LAZY | RTLD_GLOBAL);
int ret;
char jrePath[MAXPATHLEN];
char splashPath[MAXPATHLEN];
if (!GetJREPath(jrePath, sizeof(jrePath), GetArch(), JNI_FALSE)) {
JLI_ReportErrorMessage(JRE_ERROR1);
return NULL;
}
ret = JLI_Snprintf(splashPath, sizeof(splashPath), "%s/lib/%s/%s",
jrePath, GetArch(), SPLASHSCREEN_SO);
if (ret >= (int) sizeof(splashPath)) {
JLI_ReportErrorMessage(JRE_ERROR11);
return NULL;
}
if (ret < 0) {
JLI_ReportErrorMessage(JRE_ERROR13);
return NULL;
}
hSplashLib = dlopen(splashPath, RTLD_LAZY | RTLD_GLOBAL);
JLI_TraceLauncher("Info: loaded %s\n", splashPath);
}
if (hSplashLib) {
void* sym = dlsym(hSplashLib, name);

View File

@ -122,7 +122,6 @@ static jclass ni_ia4cls;
static jclass ni_ia6cls;
static jmethodID ni_ia4ctrID;
static jmethodID ni_ia6ctrID;
static jfieldID ni_ia6ipaddressID;
static void initializeInetClasses(JNIEnv *env)
{
@ -136,7 +135,6 @@ static void initializeInetClasses(JNIEnv *env)
ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
initialized = 1;
}
}
@ -447,6 +445,7 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
}
while (iterator != NULL) {
int ret1;
if (iterator->ai_family == AF_INET) {
jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
if (IS_NULL(iaObj)) {
@ -459,26 +458,22 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
inetIndex++;
} else if (iterator->ai_family == AF_INET6) {
jint scope = 0;
jbyteArray ipaddress;
jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
if (IS_NULL(iaObj)) {
ret = NULL;
goto cleanupAndReturn;
}
ipaddress = (*env)->NewByteArray(env, 16);
if (IS_NULL(ipaddress)) {
ret1 = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
if (!ret1) {
ret = NULL;
goto cleanupAndReturn;
}
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
if (scope != 0) { /* zero is default value, no need to set */
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
setInet6Address_scopeid(env, iaObj, scope);
}
(*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
inet6Index++;

View File

@ -118,7 +118,6 @@ static jclass ni_ibcls;
static jmethodID ni_ia4ctrID;
static jmethodID ni_ia6ctrID;
static jmethodID ni_ibctrID;
static jfieldID ni_ia6ipaddressID;
static jfieldID ni_ibaddressID;
static jfieldID ni_ib4broadcastID;
static jfieldID ni_ib4maskID;
@ -193,7 +192,6 @@ Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls) {
ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
@ -332,11 +330,9 @@ JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
#ifdef AF_INET6
if (family == AF_INET6) {
jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
jbyteArray ipaddress = (*env)->GetObjectField(env, iaObj, ni_ia6ipaddressID);
jbyte caddr[16];
int i;
(*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
getInet6Address_ipaddress(env, iaObj, (char *)caddr);
i = 0;
while (i < 16) {
if (caddr[i] != bytes[i]) {
@ -668,21 +664,17 @@ jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
int scope=0;
iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
if (iaObj) {
jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
if (ipaddress == NULL) {
int ret = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
if (ret == JNI_FALSE) {
return NULL;
}
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
scope = ((struct sockaddr_in6*)addrP->addr)->sin6_scope_id;
if (scope != 0) { /* zero is default value, no need to set */
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
(*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
setInet6Address_scopeid(env, iaObj, scope);
setInet6Address_scopeifname(env, iaObj, netifObj);
}
(*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
}
ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
if (ibObj) {

View File

@ -2148,8 +2148,7 @@ static void mcast_join_leave(JNIEnv *env, jobject this,
caddr[14] = ((address >> 8) & 0xff);
caddr[15] = (address & 0xff);
} else {
ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
(*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
getInet6Address_ipaddress(env, iaObj, caddr);
}
memcpy((void *)&(mname6.ipv6mr_multiaddr), caddr, sizeof(struct in6_addr));

View File

@ -782,7 +782,6 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
/* needs work. 1. family 2. clean up him6 etc deallocate memory */
if (ipv6_available() && !(family == IPv4 && v4MappedAddress == JNI_FALSE)) {
struct sockaddr_in6 *him6 = (struct sockaddr_in6 *)him;
jbyteArray ipaddress;
jbyte caddr[16];
jint address;
@ -803,8 +802,7 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
caddr[15] = (address & 0xff);
}
} else {
ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
(*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
getInet6Address_ipaddress(env, iaObj, (char *)caddr);
}
memset((char *)him6, 0, sizeof(struct sockaddr_in6));
him6->sin6_port = htons(port);
@ -840,7 +838,7 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
*/
if (!cached_scope_id) {
if (ia6_scopeidID) {
scope_id = (int)(*env)->GetIntField(env,iaObj,ia6_scopeidID);
scope_id = getInet6Address_scopeid(env, iaObj);
}
if (scope_id != 0) {
/* check user-specified value for loopback case
@ -884,7 +882,7 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
if (family != IPv4) {
if (ia6_scopeidID) {
him6->sin6_scope_id = (int)(*env)->GetIntField(env, iaObj, ia6_scopeidID);
him6->sin6_scope_id = getInet6Address_scopeid(env, iaObj);
}
}
#endif

View File

@ -77,7 +77,6 @@ static jclass ni_ia4cls;
static jclass ni_ia6cls;
static jmethodID ni_ia4ctrID;
static jmethodID ni_ia6ctrID;
static jfieldID ni_ia6ipaddressID;
static int initialized = 0;
JNIEXPORT jobjectArray JNICALL
@ -101,7 +100,6 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
initialized = 1;
}
if (IS_NULL(host)) {
@ -242,26 +240,22 @@ Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
(*env)->SetObjectArrayElement(env, ret, inetIndex, iaObj);
inetIndex ++;
} else if (iterator->ai_family == AF_INET6) {
jint scope = 0;
jbyteArray ipaddress;
jint scope = 0, ret1;
jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
if (IS_NULL(iaObj)) {
ret = NULL;
goto cleanupAndReturn;
}
ipaddress = (*env)->NewByteArray(env, 16);
if (IS_NULL(ipaddress)) {
ret1 = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
if (ret1 == JNI_FALSE) {
ret = NULL;
goto cleanupAndReturn;
}
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
if (scope != 0) { /* zero is default value, no need to set */
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
setInet6Address_scopeid(env, iaObj, scope);
}
(*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
setInetAddress_hostName(env, iaObj, host);
(*env)->SetObjectArrayElement(env, ret, inet6Index, iaObj);
inet6Index ++;

View File

@ -72,8 +72,6 @@ jmethodID ni_ia4Ctor; /* Inet4Address() */
jclass ni_ia6cls; /* Inet6Address */
jmethodID ni_ia6ctrID; /* Inet6Address() */
jfieldID ni_ia6ipaddressID;
jfieldID ni_ia6ipaddressID;
jclass ni_ibcls; /* InterfaceAddress */
jmethodID ni_ibctrID; /* InterfaceAddress() */
@ -520,7 +518,6 @@ Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls)
ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
ni_ia6ipaddressID = (*env)->GetFieldID(env, ni_ia6cls, "ipaddress", "[B");
ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
@ -621,19 +618,16 @@ jobject createNetworkInterface
int scope;
iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
if (iaObj) {
jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
if (ipaddress == NULL) {
int ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
if (ret == JNI_FALSE) {
return NULL;
}
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
scope = addrs->addr.him6.sin6_scope_id;
if (scope != 0) { /* zero is default value, no need to set */
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
(*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
setInet6Address_scopeid(env, iaObj, scope);
setInet6Address_scopeifname(env, iaObj, netifObj);
}
(*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
if (ibObj == NULL) {
free_netaddr(netaddrP);

View File

@ -549,19 +549,15 @@ static jobject createNetworkInterfaceXP(JNIEnv *env, netif *ifs)
int scope;
iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
if (iaObj) {
jbyteArray ipaddress = (*env)->NewByteArray(env, 16);
if (ipaddress == NULL) {
int ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
if (ret == JNI_FALSE) {
return NULL;
}
(*env)->SetByteArrayRegion(env, ipaddress, 0, 16,
(jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
scope = addrs->addr.him6.sin6_scope_id;
if (scope != 0) { /* zero is default value, no need to set */
(*env)->SetIntField(env, iaObj, ia6_scopeidID, scope);
(*env)->SetBooleanField(env, iaObj, ia6_scopeidsetID, JNI_TRUE);
(*env)->SetObjectField(env, iaObj, ia6_scopeifnameID, netifObj);
setInet6Address_scopeid(env, iaObj, scope);
setInet6Address_scopeifname(env, iaObj, netifObj);
}
(*env)->SetObjectField(env, iaObj, ni_ia6ipaddressID, ipaddress);
ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
if (ibObj == NULL) {
free_netaddr(netaddrP);

View File

@ -728,7 +728,6 @@ Java_java_net_TwoStacksPlainSocketImpl_socketAccept(JNIEnv *env, jobject this,
setInetAddress_family(env, socketAddressObj, IPv4);
(*env)->SetObjectField(env, socket, psi_addressID, socketAddressObj);
} else {
jbyteArray addr;
/* AF_INET6 -> Inet6Address */
if (inet6Cls == 0) {
jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
@ -751,14 +750,10 @@ Java_java_net_TwoStacksPlainSocketImpl_socketAccept(JNIEnv *env, jobject this,
NET_SocketClose(fd);
return;
}
addr = (*env)->GetObjectField (env, socketAddressObj, ia6_ipaddressID);
(*env)->SetByteArrayRegion (env, addr, 0, 16, (const char *)&him.him6.sin6_addr);
setInet6Address_ipaddress(env, socketAddressObj, (const char *)&him.him6.sin6_addr);
setInetAddress_family(env, socketAddressObj, IPv6);
scope = him.him6.sin6_scope_id;
(*env)->SetIntField(env, socketAddressObj, ia6_scopeidID, scope);
if(scope>0) {
(*env)->SetBooleanField(env, socketAddressObj, ia6_scopeidsetID, JNI_TRUE);
}
setInet6Address_scopeid(env, socketAddressObj, him.him6.sin6_scope_id);
}
/* fields common to AF_INET and AF_INET6 */

View File

@ -851,7 +851,6 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
family = (iafam == IPv4)? AF_INET : AF_INET6;
if (ipv6_available() && !(family == AF_INET && v4MappedAddress == JNI_FALSE)) {
struct SOCKADDR_IN6 *him6 = (struct SOCKADDR_IN6 *)him;
jbyteArray ipaddress;
jbyte caddr[16];
jint address, scopeid = 0;
jint cached_scope_id = 0;
@ -872,10 +871,9 @@ NET_InetAddressToSockaddr(JNIEnv *env, jobject iaObj, int port, struct sockaddr
caddr[15] = (address & 0xff);
}
} else {
ipaddress = (*env)->GetObjectField(env, iaObj, ia6_ipaddressID);
scopeid = (jint)(*env)->GetIntField(env, iaObj, ia6_scopeidID);
getInet6Address_ipaddress(env, iaObj, (char *)caddr);
scopeid = getInet6Address_scopeid(env, iaObj);
cached_scope_id = (jint)(*env)->GetIntField(env, iaObj, ia6_cachedscopeidID);
(*env)->GetByteArrayRegion(env, ipaddress, 0, 16, caddr);
}
memset((char *)him6, 0, sizeof(struct SOCKADDR_IN6));

Some files were not shown because too many files have changed in this diff Show More