提交 445da0f2 编写于 作者: L lana

Merge

......@@ -176,3 +176,5 @@ e865efbc71059a414b3b2dd2e0adfcb3d2ab6ff9 jdk8-b51
e8569a473cee7f4955bd9e76a9bdf6c6a07ced27 jdk8-b52
2c6933c5106b81a8578b70996fe5b735fb3adb60 jdk8-b53
70ad0ed1d6cef0e7712690d1bab21e4769708aad jdk8-b54
1f3f4b333341873f00da3dee85e4879f0e89c9bb jdk8-b55
2e9eeef2909b33c9224a024afddb61ccb0b77f14 jdk8-b56
......@@ -542,6 +542,21 @@ CFLAGS_$(VARIANT)/BYFILE = $(CFLAGS_$(VARIANT)/$(@F)) \
CXXFLAGS_$(VARIANT)/BYFILE = $(CXXFLAGS_$(VARIANT)/$(@F)) \
$(CXXFLAGS_$(VARIANT)$(CXXFLAGS_$(VARIANT)/$(@F)))
# Command line define to provide basename of file being compiled to source.
# The C macro THIS_FILE can replace the use of __FILE__ in the source
# files for the current filename being compiled.
# The value of the __FILE__ macro is unpredictable and can be anything
# from a relative path to a full path, THIS_FILE will be more consistent..
# The THIS_FILE macro will always be just the basename of the file being
# compiled.
# Different string literals in the the object files makes it difficult to
# compare shared libraries from different builds.
#
# NOTE: If the THIS_FILE macro is actually expanded while in an included
# source file, it will not return the name of the included file.
#
CPP_THIS_FILE = -DTHIS_FILE='"$(<F)"'
#
# Tool flags
#
......@@ -551,7 +566,7 @@ ASFLAGS = $(ASFLAGS_$(VARIANT)) $(ASFLAGS_COMMON) $(OTHER_ASFLAGS)
CFLAGS = $(CFLAGS_$(VARIANT)/BYFILE) $(CFLAGS_COMMON) $(OTHER_CFLAGS) $(EXTRA_CFLAGS)
CXXFLAGS = $(CXXFLAGS_$(VARIANT)/BYFILE) $(CXXFLAGS_COMMON) $(OTHER_CXXFLAGS) $(EXTRA_CFLAGS)
CPPFLAGS = $(CPPFLAGS_$(VARIANT)) $(CPPFLAGS_COMMON) $(OTHER_CPPFLAGS) \
$(DEFINES) $(OPTIONS:%=-D%)
$(DEFINES) $(OPTIONS:%=-D%) $(CPP_THIS_FILE)
LDFLAGS = $(LDFLAGS_$(VARIANT)) $(LDFLAGS_COMMON) $(OTHER_LDFLAGS)
LDLIBS = $(OTHER_LDLIBS) $(LDLIBS_$(VARIANT)) $(LDLIBS_COMMON)
LINTFLAGS = $(LINTFLAGS_$(VARIANT)) $(LINTFLAGS_COMMON) \
......
......@@ -320,10 +320,10 @@ $(DEMO_LIBRARY): $(DEMO_FULL_OBJECTS)
ifeq ($(PLATFORM),windows)
$(RC) $(RC_FLAGS) $(CC_OBJECT_OUTPUT_FLAG)$(DEMO_VERSION_INFO) $(VERSIONINFO_RESOURCE)
$(LINK.demo) $(SHARED_LIBRARY_FLAG) -Fe$@ \
$(DEMO_FULL_OBJECTS) $(LDLIBS.demo)
$(sort $(DEMO_FULL_OBJECTS)) $(LDLIBS.demo)
else
$(LINK.demo) $(SHARED_LIBRARY_FLAG) -o $@ \
$(DEMO_FULL_OBJECTS) $(LDLIBS.demo)
$(sort $(DEMO_FULL_OBJECTS)) $(LDLIBS.demo)
endif
@$(call binary_file_verification,$@)
......
......@@ -199,7 +199,7 @@ endif # LIBRARY
$(OBJDIR)/$(LIBRARY).lcf: $(OBJDIR)/$(LIBRARY).res $(COMPILE_FILES_o) $(FILES_m)
@$(prep-target)
@$(MKDIR) -p $(TEMPDIR)
@$(ECHO) $(FILES_o) > $@
@$(ECHO) $(sort $(FILES_o)) > $@
ifndef LOCAL_RESOURCE_FILE
@$(ECHO) $(OBJDIR)/$(LIBRARY).res >> $@
endif
......@@ -256,9 +256,9 @@ $(ACTUAL_LIBRARY):: $(COMPILE_FILES_o) $(FILES_m) $(FILES_reorder)
@$(ECHO) "STATS: LIBRARY=$(LIBRARY), PRODUCT=$(PRODUCT), OPTIMIZATION_LEVEL=$(OPTIMIZATION_LEVEL)"
@$(ECHO) "Rebuilding $@ because of $?"
ifeq ($(LIBRARY), fdlibm)
$(AR) $(ARFLAGS) $@ $(FILES_o)
$(AR) $(ARFLAGS) $@ $(sort $(FILES_o))
else # LIBRARY
$(LINKER) $(SHARED_LIBRARY_FLAG) -o $@ $(FILES_o) $(LDLIBS)
$(LINKER) $(SHARED_LIBRARY_FLAG) -o $@ $(sort $(FILES_o)) $(LDLIBS)
@$(call binary_file_verification,$@)
ifeq ($(WRITE_LIBVERSION),true)
$(MCS) -d -a "$(FULL_VERSION)" $@
......
......@@ -262,7 +262,7 @@ else
$(ECHO) Rebuilding $@ because of $$1 $$2 $$3 $$4 $$5 $$6 $${7:+...};
@$(MKDIR) -p $(TEMPDIR)
$(LINK_PRE_CMD) $(CC) $(CC_OBJECT_OUTPUT_FLAG)$@ $(LDFLAGS) \
$(FILES_o) $(THREADLIBS) $(LDLIBS)
$(sort $(FILES_o)) $(THREADLIBS) $(LDLIBS)
ifeq ($(findstring privileged, $(INFO_PLIST_FILE)), privileged)
-codesign -s openjdk_codesign $@
endif
......@@ -392,8 +392,6 @@ VERSION_DEFINES += -DFULL_VERSION='"$(FULL_VERSION)"'
VERSION_DEFINES += -DJDK_MAJOR_VERSION='"$(JDK_MAJOR_VERSION)"' \
-DJDK_MINOR_VERSION='"$(JDK_MINOR_VERSION)"'
$(OBJDIR)/main.$(OBJECT_SUFFIX): $(LAUNCHER_SHARE_SRC)/bin/main.c
@$(prep-target)
$(COMPILE.c) $(CC_OBJECT_OUTPUT_FLAG)$(OBJDIR)/main.$(OBJECT_SUFFIX) \
......
......@@ -73,7 +73,7 @@ ifeq ($(ARCH_DATA_MODEL),64)
else ifeq ($(ARCH),universal)
MAX_VM_MEMORY = 1024
else
MAX_VM_MEMORY = 612
MAX_VM_MEMORY = 768
endif
# List of all possible directories for javadoc to look for sources
......
......@@ -128,7 +128,6 @@ AUTO_FILES_JAVA_DIRS = $(PKGDIR)
# Exclude the sources that get built by ../other/Makefile
#
AUTO_JAVA_PRUNE = \
ECKeyFactory.java \
ECParameters.java \
ECPrivateKeyImpl.java \
ECPublicKeyImpl.java \
......
......@@ -53,7 +53,6 @@ AUTO_FILES_JAVA_DIRS = \
# EC classes used by the packages above
#
FILES_java += \
sun/security/ec/ECKeyFactory.java \
sun/security/ec/ECParameters.java \
sun/security/ec/ECPrivateKeyImpl.java \
sun/security/ec/ECPublicKeyImpl.java \
......
......@@ -40,6 +40,7 @@ import java.awt.image.VolatileImage;
import java.awt.peer.ComponentPeer;
import java.awt.peer.ContainerPeer;
import java.awt.peer.KeyboardFocusManagerPeer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.lang.reflect.Field;
import java.security.AccessController;
......@@ -894,15 +895,15 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
", focusedWindowChangeAllowed=" + focusedWindowChangeAllowed +
", time= " + time + ", cause=" + cause);
}
if (LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
processSynchronousLightweightTransfer(getTarget(), lightweightChild, temporary,
focusedWindowChangeAllowed, time)) {
if (LWKeyboardFocusManagerPeer.processSynchronousLightweightTransfer(
getTarget(), lightweightChild, temporary,
focusedWindowChangeAllowed, time)) {
return true;
}
int result = LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
shouldNativelyFocusHeavyweight(getTarget(), lightweightChild, temporary,
focusedWindowChangeAllowed, time, cause);
int result = LWKeyboardFocusManagerPeer.shouldNativelyFocusHeavyweight(
getTarget(), lightweightChild, temporary,
focusedWindowChangeAllowed, time, cause);
switch (result) {
case LWKeyboardFocusManagerPeer.SNFH_FAILURE:
return false;
......@@ -951,14 +952,13 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
return false;
}
LWComponentPeer focusOwnerPeer =
LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
getFocusOwner();
Component focusOwner = (focusOwnerPeer != null) ? focusOwnerPeer.getTarget() : null;
KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
Component focusOwner = kfmPeer.getCurrentFocusOwner();
return LWKeyboardFocusManagerPeer.deliverFocus(lightweightChild,
getTarget(), temporary,
focusedWindowChangeAllowed,
time, cause, focusOwner);
case LWKeyboardFocusManagerPeer.SNFH_SUCCESS_HANDLED:
return true;
}
......@@ -1251,9 +1251,6 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
if (!target.isFocusOwner() && LWKeyboardFocusManagerPeer.shouldFocusOnClick(target)) {
LWKeyboardFocusManagerPeer.requestFocusFor(target, CausedFocusEvent.Cause.MOUSE_EVENT);
} else {
// Anyway request focus to the toplevel.
getWindowPeerOrSelf().requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
}
}
......@@ -1263,8 +1260,8 @@ public abstract class LWComponentPeer<T extends Component, D extends JComponent>
protected void handleJavaFocusEvent(FocusEvent e) {
// Note that the peer receives all the FocusEvents from
// its lightweight children as well
LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
setFocusOwner(e.getID() == FocusEvent.FOCUS_GAINED ? this : null);
KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
kfmPeer.setCurrentFocusOwner(e.getID() == FocusEvent.FOCUS_GAINED ? getTarget() : null);
}
/**
......
......@@ -26,85 +26,47 @@
package sun.lwawt;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.Window;
import java.util.Map;
import java.util.HashMap;
import sun.awt.AWTAccessor;
import sun.awt.AppContext;
import sun.awt.KeyboardFocusManagerPeerImpl;
public class LWKeyboardFocusManagerPeer extends KeyboardFocusManagerPeerImpl {
private static final LWKeyboardFocusManagerPeer inst = new LWKeyboardFocusManagerPeer();
private Object lock = new Object();
private LWWindowPeer focusedWindow;
private LWComponentPeer focusOwner;
private static Map<KeyboardFocusManager, LWKeyboardFocusManagerPeer> instances =
new HashMap<KeyboardFocusManager, LWKeyboardFocusManagerPeer>();
private Window focusedWindow;
private Component focusOwner;
public static synchronized LWKeyboardFocusManagerPeer getInstance(AppContext ctx) {
return getInstance(AWTAccessor.getKeyboardFocusManagerAccessor().
getCurrentKeyboardFocusManager(ctx));
public static LWKeyboardFocusManagerPeer getInstance() {
return inst;
}
public static synchronized LWKeyboardFocusManagerPeer getInstance(KeyboardFocusManager manager) {
LWKeyboardFocusManagerPeer instance = instances.get(manager);
if (instance == null) {
instance = new LWKeyboardFocusManagerPeer(manager);
instances.put(manager, instance);
}
return instance;
private LWKeyboardFocusManagerPeer() {
}
public LWKeyboardFocusManagerPeer(KeyboardFocusManager manager) {
super(manager);
@Override
public void setCurrentFocusedWindow(Window win) {
synchronized (this) {
focusedWindow = win;
}
}
@Override
public Window getCurrentFocusedWindow() {
synchronized (lock) {
return (focusedWindow != null) ? (Window)focusedWindow.getTarget() : null;
synchronized (this) {
return focusedWindow;
}
}
@Override
public Component getCurrentFocusOwner() {
synchronized (lock) {
return (focusOwner != null) ? focusOwner.getTarget() : null;
synchronized (this) {
return focusOwner;
}
}
@Override
public void setCurrentFocusOwner(Component comp) {
synchronized (lock) {
focusOwner = (comp != null) ? (LWComponentPeer)comp.getPeer() : null;
}
}
void setFocusedWindow(LWWindowPeer peer) {
synchronized (lock) {
focusedWindow = peer;
}
}
LWWindowPeer getFocusedWindow() {
synchronized (lock) {
return focusedWindow;
}
}
void setFocusOwner(LWComponentPeer peer) {
synchronized (lock) {
focusOwner = peer;
}
}
LWComponentPeer getFocusOwner() {
synchronized (lock) {
return focusOwner;
synchronized (this) {
focusOwner = comp;
}
}
}
......@@ -415,8 +415,8 @@ public abstract class LWToolkit extends SunToolkit implements Runnable {
}
@Override
public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) {
return LWKeyboardFocusManagerPeer.getInstance(manager);
public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
return LWKeyboardFocusManagerPeer.getInstance();
}
@Override
......
......@@ -88,10 +88,16 @@ public class LWWindowPeer
private volatile int windowState = Frame.NORMAL;
// A peer where the last mouse event came to. Used to generate
// MOUSE_ENTERED/EXITED notifications and by cursor manager to
// check that the mouse is over the window
private volatile boolean isMouseOver = false;
// A peer where the last mouse event came to. Used by cursor manager to
// find the component under cursor
private static volatile LWComponentPeer lastMouseEventPeer = null;
private static volatile LWComponentPeer lastCommonMouseEventPeer = null;
// A peer where the last mouse event came to. Used to generate
// MOUSE_ENTERED/EXITED notifications
private volatile LWComponentPeer lastMouseEventPeer;
// Peers where all dragged/released events should come to,
// depending on what mouse button is being dragged according to Cocoa
......@@ -232,8 +238,7 @@ public class LWWindowPeer
// TODO: update graphicsConfig, see 4868278
platformWindow.setVisible(visible);
if (isSimpleWindow()) {
LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
getInstance(getAppContext());
KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
if (visible) {
if (!getTarget().isAutoRequestFocus()) {
......@@ -242,7 +247,7 @@ public class LWWindowPeer
requestWindowFocus(CausedFocusEvent.Cause.ACTIVATION);
}
// Focus the owner in case this window is focused.
} else if (manager.getCurrentFocusedWindow() == getTarget()) {
} else if (kfmPeer.getCurrentFocusedWindow() == getTarget()) {
// Transfer focus to the owner.
LWWindowPeer owner = getOwnerFrameDialog(LWWindowPeer.this);
if (owner != null) {
......@@ -707,66 +712,65 @@ public class LWWindowPeer
Rectangle r = getBounds();
// findPeerAt() expects parent coordinates
LWComponentPeer targetPeer = findPeerAt(r.x + x, r.y + y);
LWWindowPeer lastWindowPeer =
(lastMouseEventPeer != null) ? lastMouseEventPeer.getWindowPeerOrSelf() : null;
LWWindowPeer curWindowPeer =
(targetPeer != null) ? targetPeer.getWindowPeerOrSelf() : null;
if (id == MouseEvent.MOUSE_EXITED) {
// Sometimes we may get MOUSE_EXITED after lastMouseEventPeer is switched
// to a peer from another window. So we must first check if this peer is
// the same as lastWindowPeer
if (lastWindowPeer == this) {
if (isEnabled()) {
isMouseOver = false;
if (lastMouseEventPeer != null) {
if (lastMouseEventPeer.isEnabled()) {
Point lp = lastMouseEventPeer.windowToLocal(x, y,
lastWindowPeer);
this);
postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
MouseEvent.MOUSE_EXITED, when,
modifiers, lp.x, lp.y, screenX,
screenY, clickCount, popupTrigger,
button));
MouseEvent.MOUSE_EXITED, when,
modifiers, lp.x, lp.y, screenX,
screenY, clickCount, popupTrigger,
button));
}
// Sometimes we may get MOUSE_EXITED after lastCommonMouseEventPeer is switched
// to a peer from another window. So we must first check if this peer is
// the same as lastWindowPeer
if (lastCommonMouseEventPeer != null && lastCommonMouseEventPeer.getWindowPeerOrSelf() == this) {
lastCommonMouseEventPeer = null;
}
lastMouseEventPeer = null;
}
} else {
if (targetPeer != lastMouseEventPeer) {
if (id != MouseEvent.MOUSE_DRAGGED || lastMouseEventPeer == null) {
// lastMouseEventPeer may be null if mouse was out of Java windows
if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
// Sometimes, MOUSE_EXITED is not sent by delegate (or is sent a bit
// later), in which case lastWindowPeer is another window
if (lastWindowPeer != this) {
Point oldp = lastMouseEventPeer.windowToLocal(x, y, lastWindowPeer);
// Additionally translate from this to lastWindowPeer coordinates
Rectangle lr = lastWindowPeer.getBounds();
oldp.x += r.x - lr.x;
oldp.y += r.y - lr.y;
postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
MouseEvent.MOUSE_EXITED,
when, modifiers,
oldp.x, oldp.y, screenX, screenY,
clickCount, popupTrigger, button));
} else {
Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
MouseEvent.MOUSE_EXITED,
when, modifiers,
oldp.x, oldp.y, screenX, screenY,
clickCount, popupTrigger, button));
}
}
if (targetPeer != null && targetPeer.isEnabled() && id != MouseEvent.MOUSE_ENTERED) {
Point newp = targetPeer.windowToLocal(x, y, curWindowPeer);
} else if(id == MouseEvent.MOUSE_ENTERED) {
isMouseOver = true;
if (targetPeer != null) {
if (targetPeer.isEnabled()) {
Point lp = targetPeer.windowToLocal(x, y, this);
postEvent(new MouseEvent(targetPeer.getTarget(),
MouseEvent.MOUSE_ENTERED,
when, modifiers,
newp.x, newp.y, screenX, screenY,
clickCount, popupTrigger, button));
}
MouseEvent.MOUSE_ENTERED, when,
modifiers, lp.x, lp.y, screenX,
screenY, clickCount, popupTrigger,
button));
}
lastCommonMouseEventPeer = targetPeer;
lastMouseEventPeer = targetPeer;
}
} else {
PlatformWindow topmostPlatforWindow =
platformWindow.getTopmostPlatformWindowUnderMouse();
LWWindowPeer topmostWindowPeer =
topmostPlatforWindow != null ? topmostPlatforWindow.getPeer() : null;
// topmostWindowPeer == null condition is added for the backward
// compatibility with applets. It can be removed when the
// getTopmostPlatformWindowUnderMouse() method will be properly
// implemented in CPlatformEmbeddedFrame class
if (topmostWindowPeer == this || topmostWindowPeer == null) {
generateMouseEnterExitEventsForComponents(when, button, x, y,
screenX, screenY, modifiers, clickCount, popupTrigger,
targetPeer);
} else {
LWComponentPeer topmostTargetPeer =
topmostWindowPeer != null ? topmostWindowPeer.findPeerAt(r.x + x, r.y + y) : null;
topmostWindowPeer.generateMouseEnterExitEventsForComponents(when, button, x, y,
screenX, screenY, modifiers, clickCount, popupTrigger,
topmostTargetPeer);
}
// TODO: fill "bdata" member of AWTEvent
int eventButtonMask = (button > 0)? MouseEvent.getMaskForButton(button) : 0;
......@@ -794,6 +798,14 @@ public class LWWindowPeer
mouseClickButtons |= eventButtonMask;
}
// The window should be focused on mouse click. If it gets activated by the native platform,
// this request will be no op. It will take effect when:
// 1. A simple not focused window is clicked.
// 2. An active but not focused owner frame/dialog is clicked.
// The mouse event then will trigger a focus request "in window" to the component, so the window
// should gain focus before.
requestWindowFocus(CausedFocusEvent.Cause.MOUSE_EVENT);
mouseDownTarget[targetIdx] = targetPeer;
} else if (id == MouseEvent.MOUSE_DRAGGED) {
// Cocoa dragged event has the information about which mouse
......@@ -816,19 +828,13 @@ public class LWWindowPeer
// mouseClickButtons is updated below, after MOUSE_CLICK is sent
}
// check if we receive mouseEvent from outside the window's bounds
// it can be either mouseDragged or mouseReleased
if (curWindowPeer == null) {
//TODO This can happen if this window is invisible. this is correct behavior in this case?
curWindowPeer = this;
}
if (targetPeer == null) {
//TODO This can happen if this window is invisible. this is correct behavior in this case?
targetPeer = this;
}
Point lp = targetPeer.windowToLocal(x, y, curWindowPeer);
Point lp = targetPeer.windowToLocal(x, y, this);
if (targetPeer.isEnabled()) {
MouseEvent event = new MouseEvent(targetPeer.getTarget(), id,
when, modifiers, lp.x, lp.y,
......@@ -852,6 +858,38 @@ public class LWWindowPeer
notifyUpdateCursor();
}
private void generateMouseEnterExitEventsForComponents(long when,
int button, int x, int y, int screenX, int screenY,
int modifiers, int clickCount, boolean popupTrigger,
LWComponentPeer targetPeer) {
if (!isMouseOver || targetPeer == lastMouseEventPeer) {
return;
}
// Generate Mouse Exit for components
if (lastMouseEventPeer != null && lastMouseEventPeer.isEnabled()) {
Point oldp = lastMouseEventPeer.windowToLocal(x, y, this);
postEvent(new MouseEvent(lastMouseEventPeer.getTarget(),
MouseEvent.MOUSE_EXITED,
when, modifiers,
oldp.x, oldp.y, screenX, screenY,
clickCount, popupTrigger, button));
}
lastCommonMouseEventPeer = targetPeer;
lastMouseEventPeer = targetPeer;
// Generate Mouse Enter for components
if (targetPeer != null && targetPeer.isEnabled()) {
Point newp = targetPeer.windowToLocal(x, y, this);
postEvent(new MouseEvent(targetPeer.getTarget(),
MouseEvent.MOUSE_ENTERED,
when, modifiers,
newp.x, newp.y, screenX, screenY,
clickCount, popupTrigger, button));
}
}
public void dispatchMouseWheelEvent(long when, int x, int y, int modifiers,
int scrollType, int scrollAmount,
int wheelRotation, double preciseWheelRotation,
......@@ -884,20 +922,16 @@ public class LWWindowPeer
public void dispatchKeyEvent(int id, long when, int modifiers,
int keyCode, char keyChar, int keyLocation)
{
LWComponentPeer focusOwner =
LWKeyboardFocusManagerPeer.getInstance(getAppContext()).
getFocusOwner();
LWKeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
Component focusOwner = kfmPeer.getCurrentFocusOwner();
// Null focus owner may receive key event when
// application hides the focused window upon ESC press
// (AWT transfers/clears the focus owner) and pending ESC release
// may come to already hidden window. This check eliminates NPE.
if (focusOwner != null) {
KeyEvent event =
new KeyEvent(focusOwner.getTarget(), id, when, modifiers,
keyCode, keyChar, keyLocation);
focusOwner.postEvent(event);
if (focusOwner == null) {
focusOwner = kfmPeer.getCurrentFocusedWindow();
if (focusOwner == null) {
focusOwner = this.getTarget();
}
}
postEvent(new KeyEvent(focusOwner, id, when, modifiers, keyCode, keyChar, keyLocation));
}
......@@ -1096,11 +1130,11 @@ public class LWWindowPeer
}
public static LWWindowPeer getWindowUnderCursor() {
return lastMouseEventPeer != null ? lastMouseEventPeer.getWindowPeerOrSelf() : null;
return lastCommonMouseEventPeer != null ? lastCommonMouseEventPeer.getWindowPeerOrSelf() : null;
}
public static LWComponentPeer<?, ?> getPeerUnderCursor() {
return lastMouseEventPeer;
return lastCommonMouseEventPeer;
}
/*
......@@ -1213,10 +1247,8 @@ public class LWWindowPeer
}
}
LWKeyboardFocusManagerPeer manager = LWKeyboardFocusManagerPeer.
getInstance(getAppContext());
Window oppositeWindow = becomesFocused ? manager.getCurrentFocusedWindow() : null;
KeyboardFocusManagerPeer kfmPeer = LWKeyboardFocusManagerPeer.getInstance();
Window oppositeWindow = becomesFocused ? kfmPeer.getCurrentFocusedWindow() : null;
// Note, the method is not called:
// - when the opposite (gaining focus) window is an owned/owner window.
......@@ -1229,10 +1261,10 @@ public class LWWindowPeer
grabbingWindow.ungrab();
}
manager.setFocusedWindow(becomesFocused ? LWWindowPeer.this : null);
kfmPeer.setCurrentFocusedWindow(becomesFocused ? getTarget() : null);
int eventID = becomesFocused ? WindowEvent.WINDOW_GAINED_FOCUS : WindowEvent.WINDOW_LOST_FOCUS;
WindowEvent windowEvent = new WindowEvent(getTarget(), eventID, oppositeWindow);
WindowEvent windowEvent = new TimedWindowEvent(getTarget(), eventID, oppositeWindow, System.currentTimeMillis());
// TODO: wrap in SequencedEvent
postEvent(windowEvent);
......
......@@ -118,6 +118,8 @@ public interface PlatformWindow {
public void setAlwaysOnTop(boolean value);
public PlatformWindow getTopmostPlatformWindowUnderMouse();
public void updateFocusableWindowState();
public boolean rejectFocusRequest(CausedFocusEvent.Cause cause);
......
......@@ -151,6 +151,10 @@ public class CPlatformEmbeddedFrame implements PlatformWindow {
@Override
public void setAlwaysOnTop(boolean value) {}
// This method should be properly implemented for applets.
// It returns null just as a stub.
public PlatformWindow getTopmostPlatformWindowUnderMouse() { return null; }
@Override
public void updateFocusableWindowState() {}
......
......@@ -61,8 +61,9 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
private static native void nativeSetNSWindowSecurityWarningPositioning(long nsWindowPtr, double x, double y, float biasX, float biasY);
private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr);
private static native void nativeSynthesizeMouseEnteredExitedEvents();
private static native void nativeDispose(long nsWindowPtr);
private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
private static native int nativeGetNSWindowDisplayID_AppKitThread(long nsWindowPtr);
......@@ -588,7 +589,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
}
}
nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
nativeSynthesizeMouseEnteredExitedEvents();
// Configure stuff #2
updateFocusabilityForAutoRequestFocus(true);
......@@ -729,6 +730,10 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
setStyleBits(ALWAYS_ON_TOP, isAlwaysOnTop);
}
public PlatformWindow getTopmostPlatformWindowUnderMouse(){
return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
}
@Override
public void setOpacity(float opacity) {
CWrapper.NSWindow.setAlphaValue(getNSWindowPtr(), opacity);
......@@ -803,7 +808,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
throw new RuntimeException("Unknown window state: " + windowState);
}
nativeSynthesizeMouseEnteredExitedEvents(nsWindowPtr);
nativeSynthesizeMouseEnteredExitedEvents();
// NOTE: the SWP.windowState field gets updated to the newWindowState
// value when the native notification comes to us
......
......@@ -37,7 +37,11 @@
#import "ThreadUtilities.h"
#import "CMenuBar.h"
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
static JNF_CLASS_CACHE(sjc_ScreenMenu, "com/apple/laf/ScreenMenu");
static jint ns2awtModifiers(NSUInteger keyMods) {
......@@ -97,7 +101,7 @@ static jint ns2awtMouseButton(NSInteger mouseButton) {
{
if (self.javaObjectWrapper == nil) {
#ifdef DEBUG
NSLog(@"_javaObject is NULL: (%s - %s : %d)", __FILE__, __FUNCTION__, __LINE__);
NSLog(@"_javaObject is NULL: (%s - %s : %d)", THIS_FILE, __FUNCTION__, __LINE__);
#endif
return;
}
......@@ -115,7 +119,7 @@ JNF_COCOA_EXIT(env);
{
if (self.javaObjectWrapper == nil) {
#ifdef DEBUG
NSLog(@"_javaObject is NULL: (%s - %s : %d)", __FILE__, __FUNCTION__, __LINE__);
NSLog(@"_javaObject is NULL: (%s - %s : %d)", THIS_FILE, __FUNCTION__, __LINE__);
#endif
return;
}
......@@ -133,7 +137,7 @@ JNF_COCOA_EXIT(env);
{
if (self.javaObjectWrapper == nil) {
#ifdef DEBUG
NSLog(@"_javaObject is NULL: (%s - %s : %d)", __FILE__, __FUNCTION__, __LINE__);
NSLog(@"_javaObject is NULL: (%s - %s : %d)", THIS_FILE, __FUNCTION__, __LINE__);
#endif
return;
}
......
......@@ -26,6 +26,11 @@
//#define USE_ERROR
//#define USE_TRACE
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
#if USE_PLATFORM_MIDI_OUT == TRUE
#include "PLATFORM_API_MacOSX_MidiUtils.h"
......@@ -128,7 +133,7 @@ INT32 MIDI_OUT_SendShortMessage(MidiDeviceHandle* handle, UINT32 packedMsg, UINT
case 0xF7:
// System exclusive
fprintf(stderr, "%s: %d->internal error: sysex message status=0x%X while sending short message\n",
__FILE__, __LINE__, data[0]);
THIS_FILE, __LINE__, data[0]);
byteIsInvalid = TRUE;
break;
......@@ -154,7 +159,7 @@ INT32 MIDI_OUT_SendShortMessage(MidiDeviceHandle* handle, UINT32 packedMsg, UINT
default:
// Invalid message
fprintf(stderr, "%s: %d->Invalid message: message status=0x%X while sending short message\n",
__FILE__, __LINE__, data[0]);
THIS_FILE, __LINE__, data[0]);
byteIsInvalid = TRUE;
break;
}
......@@ -164,7 +169,7 @@ INT32 MIDI_OUT_SendShortMessage(MidiDeviceHandle* handle, UINT32 packedMsg, UINT
default:
// This can't happen, but handle it anyway.
fprintf(stderr, "%s: %d->Invalid message: message status=0x%X while sending short message\n",
__FILE__, __LINE__, data[0]);
THIS_FILE, __LINE__, data[0]);
byteIsInvalid = TRUE;
break;
}
......
......@@ -42,6 +42,11 @@
//#define USE_ERROR
//#define USE_TRACE
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
#if (USE_PLATFORM_MIDI_IN == TRUE) || (USE_PLATFORM_MIDI_OUT == TRUE)
#include "PLATFORM_API_MacOSX_MidiUtils.h"
......@@ -317,7 +322,7 @@ static void processMessagesForPacket(const MIDIPacket* packet, MacMidiDeviceHand
packedMsg = pendingMessageStatus | pendingData[0] << 8;
} else {
fprintf(stderr, "%s: %d->internal error: pendingMessageStatus=0x%X, pendingDataLength=%d\n",
__FILE__, __LINE__, pendingMessageStatus, pendingDataLength);
THIS_FILE, __LINE__, pendingMessageStatus, pendingDataLength);
byteIsInvalid = TRUE;
}
pendingDataLength = 0;
......
......@@ -33,8 +33,8 @@
@private
jobject m_cPlatformView;
// Handler for the tracking rect needed for Enter/Exit events management.
NSTrackingRectTag rolloverTrackingRectTag;
// Handler for the tracking area needed for Enter/Exit events management.
NSTrackingArea* rolloverTrackingArea;
// TODO: NSMenu *contextualMenu;
......@@ -61,7 +61,7 @@
- (id) initWithRect:(NSRect) rect platformView:(jobject)cPlatformView windowLayer:(CALayer*)windowLayer;
- (void) deliverJavaMouseEvent: (NSEvent *) event;
- (void) resetTrackingRect;
- (void) resetTrackingArea;
- (void) deliverJavaKeyEventHelper: (NSEvent *) event;
- (jobject) awtComponent:(JNIEnv *)env;
......
......@@ -82,6 +82,7 @@ AWT_ASSERT_APPKIT_THREAD;
fPAHNeedsToSelect = NO;
mouseIsOver = NO;
[self resetTrackingArea];
if (windowLayer != nil) {
self.cglLayer = windowLayer;
......@@ -146,7 +147,7 @@ AWT_ASSERT_APPKIT_THREAD;
[[self window] makeFirstResponder: self];
}];
if ([self window] != NULL) {
[self resetTrackingRect];
[self resetTrackingArea];
}
}
......@@ -368,30 +369,31 @@ AWT_ASSERT_APPKIT_THREAD;
JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent);
}
- (void) clearTrackingRect {
if (rolloverTrackingRectTag > 0) {
[self removeTrackingRect:rolloverTrackingRectTag];
rolloverTrackingRectTag = 0;
- (void) resetTrackingArea {
if (rolloverTrackingArea != nil) {
[self removeTrackingArea:rolloverTrackingArea];
[rolloverTrackingArea release];
}
}
- (void) resetTrackingRect {
[self clearTrackingRect];
rolloverTrackingRectTag = [self addTrackingRect:[self visibleRect]
owner:self
userData:NULL
assumeInside:NO];
int options = (NSTrackingActiveInActiveApp | NSTrackingMouseEnteredAndExited |
NSTrackingMouseMoved | NSTrackingEnabledDuringMouseDrag);
rolloverTrackingArea = [[NSTrackingArea alloc] initWithRect:[self visibleRect]
options: options
owner:self
userInfo:nil
];
[self addTrackingArea:rolloverTrackingArea];
}
- (void)updateTrackingAreas {
[super updateTrackingAreas];
[self resetTrackingRect];
[self resetTrackingArea];
}
- (void) resetCursorRects {
[super resetCursorRects];
[self resetTrackingRect];
[self resetTrackingArea];
}
-(void) deliverJavaKeyEventHelper: (NSEvent *) event {
......@@ -402,7 +404,7 @@ AWT_ASSERT_APPKIT_THREAD;
}
[sLastKeyEvent release];
sLastKeyEvent = [event retain];
[AWTToolkit eventCountPlusPlus];
JNIEnv *env = [ThreadUtilities getJNIEnv];
......
......@@ -238,10 +238,12 @@ AWT_ASSERT_APPKIT_THREAD;
return self;
}
// checks that this window is under the mouse cursor and this point is not overlapped by others windows
- (BOOL) isTopmostWindowUnderMouse {
+ (BOOL) isAWTWindow:(NSWindow *)window {
return [window isKindOfClass: [AWTWindow_Panel class]] || [window isKindOfClass: [AWTWindow_Normal class]];
}
int currentWinID = [self.nsWindow windowNumber];
// returns id for the topmost window under mouse
+ (NSInteger) getTopmostWindowUnderMouseID {
NSRect screenRect = [[NSScreen mainScreen] frame];
NSPoint nsMouseLocation = [NSEvent mouseLocation];
......@@ -249,53 +251,77 @@ AWT_ASSERT_APPKIT_THREAD;
NSMutableArray *windows = (NSMutableArray *)CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
for (NSDictionary *window in windows) {
int layer = [[window objectForKey:(id)kCGWindowLayer] intValue];
NSInteger layer = [[window objectForKey:(id)kCGWindowLayer] integerValue];
if (layer == 0) {
int winID = [[window objectForKey:(id)kCGWindowNumber] intValue];
CGRect rect;
CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[window objectForKey:(id)kCGWindowBounds], &rect);
if (CGRectContainsPoint(rect, cgMouseLocation)) {
return currentWinID == winID;
} else if (currentWinID == winID) {
return NO;
return [[window objectForKey:(id)kCGWindowNumber] integerValue];
}
}
}
return NO;
return -1;
}
- (void) synthesizeMouseEnteredExitedEvents {
// checks that this window is under the mouse cursor and this point is not overlapped by others windows
- (BOOL) isTopmostWindowUnderMouse {
return [self.nsWindow windowNumber] == [AWTWindow getTopmostWindowUnderMouseID];
}
int eventType = 0;
BOOL isUnderMouse = [self isTopmostWindowUnderMouse];
BOOL mouseIsOver = [[self.nsWindow contentView] mouseIsOver];
+ (AWTWindow *) getTopmostWindowUnderMouse {
NSEnumerator *windowEnumerator = [[NSApp windows] objectEnumerator];
NSWindow *window;
if (isUnderMouse && !mouseIsOver) {
eventType = NSMouseEntered;
} else if (!isUnderMouse && mouseIsOver) {
eventType = NSMouseExited;
} else {
return;
NSInteger topmostWindowUnderMouseID = [AWTWindow getTopmostWindowUnderMouseID];
while ((window = [windowEnumerator nextObject]) != nil) {
if ([window windowNumber] == topmostWindowUnderMouseID) {
BOOL isAWTWindow = [AWTWindow isAWTWindow: window];
return isAWTWindow ? (AWTWindow *) [window delegate] : nil;
}
}
return nil;
}
+ (void) synthesizeMouseEnteredExitedEvents:(NSWindow*)window withType:(NSEventType)eventType {
NSPoint screenLocation = [NSEvent mouseLocation];
NSPoint windowLocation = [self.nsWindow convertScreenToBase: screenLocation];
NSPoint windowLocation = [window convertScreenToBase: screenLocation];
int modifierFlags = (eventType == NSMouseEntered) ? NSMouseEnteredMask : NSMouseExitedMask;
NSEvent *mouseEvent = [NSEvent enterExitEventWithType: eventType
location: windowLocation
modifierFlags: modifierFlags
timestamp: 0
windowNumber: [self.nsWindow windowNumber]
context: nil
eventNumber: 0
trackingNumber: 0
userData: nil
];
[[self.nsWindow contentView] deliverJavaMouseEvent: mouseEvent];
location: windowLocation
modifierFlags: modifierFlags
timestamp: 0
windowNumber: [window windowNumber]
context: nil
eventNumber: 0
trackingNumber: 0
userData: nil
];
[[window contentView] deliverJavaMouseEvent: mouseEvent];
}
+ (void) synthesizeMouseEnteredExitedEventsForAllWindows {
NSInteger topmostWindowUnderMouseID = [AWTWindow getTopmostWindowUnderMouseID];
NSArray *windows = [NSApp windows];
NSWindow *window;
NSEnumerator *windowEnumerator = [windows objectEnumerator];
while ((window = [windowEnumerator nextObject]) != nil) {
if ([AWTWindow isAWTWindow: window]) {
BOOL isUnderMouse = ([window windowNumber] == topmostWindowUnderMouseID);
BOOL mouseIsOver = [[window contentView] mouseIsOver];
if (isUnderMouse && !mouseIsOver) {
[AWTWindow synthesizeMouseEnteredExitedEvents:window withType:NSMouseEntered];
} else if (!isUnderMouse && mouseIsOver) {
[AWTWindow synthesizeMouseEnteredExitedEvents:window withType:NSMouseExited];
}
}
}
}
- (void) dealloc {
......@@ -825,7 +851,7 @@ AWT_ASSERT_NOT_APPKIT_THREAD;
// (this will also re-enable screen updates, which were disabled above)
// TODO: send PaintEvent
[window synthesizeMouseEnteredExitedEvents];
[AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
}];
JNF_COCOA_EXIT(env);
......@@ -1038,24 +1064,44 @@ AWT_ASSERT_NOT_APPKIT_THREAD;
JNF_COCOA_EXIT(env);
}
/*
* Class: sun_lwawt_macosx_CPlatformWindow
* Method: nativeGetTopmostPlatformWindowUnderMouse
* Signature: (J)V
*/
JNIEXPORT jobject
JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeGetTopmostPlatformWindowUnderMouse
(JNIEnv *env, jclass clazz)
{
jobject topmostWindowUnderMouse = nil;
JNF_COCOA_ENTER(env);
AWT_ASSERT_APPKIT_THREAD;
AWTWindow *awtWindow = [AWTWindow getTopmostWindowUnderMouse];
if (awtWindow != nil) {
topmostWindowUnderMouse = [awtWindow.javaPlatformWindow jObject];
}
JNF_COCOA_EXIT(env);
return topmostWindowUnderMouse;
}
/*
* Class: sun_lwawt_macosx_CPlatformWindow
* Method: nativeSynthesizeMouseEnteredExitedEvents
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
(JNIEnv *env, jclass clazz, jlong windowPtr)
(JNIEnv *env, jclass clazz)
{
JNF_COCOA_ENTER(env);
AWT_ASSERT_NOT_APPKIT_THREAD;
NSWindow *nsWindow = OBJC(windowPtr);
[JNFRunLoop performOnMainThreadWaiting:NO withBlock:^(){
AWT_ASSERT_APPKIT_THREAD;
AWTWindow *window = (AWTWindow*)[nsWindow delegate];
[window synthesizeMouseEnteredExitedEvents];
[AWTWindow synthesizeMouseEnteredExitedEventsForAllWindows];
}];
JNF_COCOA_EXIT(env);
......
......@@ -33,6 +33,11 @@
#import "ThreadUtilities.h"
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
NSColor **sColors = nil;
NSColor **appleColors = nil;
......@@ -130,7 +135,7 @@ static JNF_STATIC_MEMBER_CACHE(jm_systemColorsChanged, jc_LWCToolkit, "systemCol
result = (useAppleColor ? appleColors : sColors)[colorIndex];
}
else {
NSLog(@"%s: %s %sColor: %ld not found, returning black.", __FILE__, __FUNCTION__, (useAppleColor) ? "Apple" : "System", colorIndex);
NSLog(@"%s: %s %sColor: %ld not found, returning black.", THIS_FILE, __FUNCTION__, (useAppleColor) ? "Apple" : "System", colorIndex);
result = [NSColor blackColor];
}
......
......@@ -36,6 +36,10 @@
#import "QuartzSurfaceData.h"
#include "AWTStrike.h"
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
static const CGAffineTransform sInverseTX = { 1, 0, 0, -1, 0, 0 };
......@@ -501,7 +505,7 @@ static inline void doDrawGlyphsPipe_getGlyphVectorLengthAndAlloc
if (glyphs == NULL || advances == NULL)
{
(*env)->DeleteLocalRef(env, glyphsArray);
[NSException raise:NSMallocException format:@"%s-%s:%d", __FILE__, __FUNCTION__, __LINE__];
[NSException raise:NSMallocException format:@"%s-%s:%d", THIS_FILE, __FUNCTION__, __LINE__];
return;
}
......
......@@ -33,6 +33,11 @@
#import "CoreTextSupport.h"
//#import "jni_util.h"
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
@implementation AWTStrike
static CGAffineTransform sInverseTX = { 1, 0, 0, -1, 0, 0 };
......@@ -102,7 +107,7 @@ static CGAffineTransform sInverseTX = { 1, 0, 0, -1, 0, 0 };
#define AWT_FONT_CLEANUP_FINISH \
if (_fontThrowJavaException == YES) { \
char s[512]; \
sprintf(s, "%s-%s:%d", __FILE__, __FUNCTION__, __LINE__); \
sprintf(s, "%s-%s:%d", THIS_FILE, __FUNCTION__, __LINE__); \
[JNFException raise:env as:kRuntimeException reason:s]; \
}
......
......@@ -42,31 +42,36 @@ const char * jvmtiErrorText(jvmtiError);
const char * eventText(int);
const char * jdwpErrorText(jdwpError);
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
#define EXIT_ERROR(error,msg) \
{ \
print_message(stderr, "JDWP exit error ", "\n", \
"%s(%d): %s [%s:%d]", \
jvmtiErrorText((jvmtiError)error), error, (msg==NULL?"":msg), \
__FILE__, __LINE__); \
THIS_FILE, __LINE__); \
debugInit_exit((jvmtiError)error, msg); \
}
#define JDI_ASSERT(expression) \
do { \
if (gdata && gdata->assertOn && !(expression)) { \
jdiAssertionFailed(__FILE__, __LINE__, #expression); \
jdiAssertionFailed(THIS_FILE, __LINE__, #expression); \
} \
} while (0)
#define JDI_ASSERT_MSG(expression, msg) \
do { \
if (gdata && gdata->assertOn && !(expression)) { \
jdiAssertionFailed(__FILE__, __LINE__, msg); \
jdiAssertionFailed(THIS_FILE, __LINE__, msg); \
} \
} while (0)
#define JDI_ASSERT_FAILED(msg) \
jdiAssertionFailed(__FILE__, __LINE__, msg)
jdiAssertionFailed(THIS_FILE, __LINE__, msg)
void do_pause(void);
......
......@@ -33,11 +33,15 @@ void finish_logging(int);
#define LOG_NULL ((void)0)
#ifdef JDWP_LOGGING
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
#ifdef JDWP_LOGGING
#define _LOG(flavor,args) \
(log_message_begin(flavor,__FILE__,__LINE__), \
(log_message_begin(flavor,THIS_FILE,__LINE__), \
log_message_end args)
#define LOG_TEST(flag) (gdata->log_flags & (flag))
......
......@@ -68,12 +68,23 @@ int JLI_GetStdArgc();
#define JLI_StrNCaseCmp(p1, p2, p3) strnicmp((p1), (p2), (p3))
#define JLI_Snprintf _snprintf
void JLI_CmdToArgs(char *cmdline);
#else
#define JLI_Lseek _lseeki64
#else /* NIXES */
#include <unistd.h>
#include <strings.h>
#define JLI_StrCaseCmp(p1, p2) strcasecmp((p1), (p2))
#define JLI_StrNCaseCmp(p1, p2, p3) strncasecmp((p1), (p2), (p3))
#define JLI_Snprintf snprintf
#ifdef __solaris__
#define JLI_Lseek llseek
#endif
#ifdef __linux__
#define _LARGFILE64_SOURCE
#define JLI_Lseek lseek64
#endif
#ifdef MACOSX
#define JLI_Lseek lseek
#endif
#endif /* _WIN32 */
/*
......
/*
* Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -37,6 +37,8 @@
#define CENSIG 0x02014b50L /* "PK\001\002" */
#define ENDSIG 0x06054b50L /* "PK\005\006" */
#define ZIP64_ENDSIG 0x06064b50L /* "PK\006\006" */
#define ZIP64_LOCSIG 0x07064b50L /* "PK\006\007" */
/*
* Header sizes including signatures
*/
......@@ -45,12 +47,21 @@
#define CENHDR 46
#define ENDHDR 22
#define ZIP64_ENDHDR 56 // ZIP64 end header size
#define ZIP64_LOCHDR 20 // ZIP64 end loc header size
#define ZIP64_EXTHDR 24 // EXT header size
#define ZIP64_EXTID 1 // Extra field Zip64 header ID
#define ZIP64_MAGICVAL 0xffffffffLL
#define ZIP64_MAGICCOUNT 0xffff
/*
* Header field access macros
*/
#define CH(b, n) (((unsigned char *)(b))[n])
#define SH(b, n) (CH(b, n) | (CH(b, n+1) << 8))
#define LG(b, n) (SH(b, n) | (SH(b, n+2) << 16))
#define LG(b, n) ((SH(b, n) | (SH(b, n+2) << 16)) &0xffffffffUL)
#define LL(b, n) (((jlong)LG(b, n)) | (((jlong)LG(b, n+4)) << 32))
#define GETSIG(b) LG(b, 0)
/*
......@@ -101,6 +112,26 @@
#define ENDOFF(b) LG(b, 16) /* central directory offset */
#define ENDCOM(b) SH(b, 20) /* size of zip file comment */
/*
* Macros for getting Zip64 end of central directory header fields
*/
#define ZIP64_ENDLEN(b) LL(b, 4) /* size of zip64 end of central dir */
#define ZIP64_ENDVEM(b) SH(b, 12) /* version made by */
#define ZIP64_ENDVER(b) SH(b, 14) /* version needed to extract */
#define ZIP64_ENDNMD(b) LG(b, 16) /* number of this disk */
#define ZIP64_ENDDSK(b) LG(b, 20) /* disk number of start */
#define ZIP64_ENDTOD(b) LL(b, 24) /* total number of entries on this disk */
#define ZIP64_ENDTOT(b) LL(b, 32) /* total number of entries */
#define ZIP64_ENDSIZ(b) LL(b, 40) /* central directory size in bytes */
#define ZIP64_ENDOFF(b) LL(b, 48) /* offset of first CEN header */
/*
* Macros for getting Zip64 end of central directory locator fields
*/
#define ZIP64_LOCDSK(b) LG(b, 4) /* disk number start */
#define ZIP64_LOCOFF(b) LL(b, 8) /* offset of zip64 end */
#define ZIP64_LOCTOT(b) LG(b, 16) /* total number of disks */
/*
* A comment of maximum length of 64kb can follow the END record. This
* is the furthest the END record can be from the end of the file.
......@@ -119,7 +150,7 @@
typedef struct zentry { /* Zip file entry */
size_t isize; /* size of inflated data */
size_t csize; /* size of compressed data (zero if uncompressed) */
off_t offset; /* position of compressed data */
jlong offset; /* position of compressed data */
int how; /* compression method (if any) */
} zentry;
......
/*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 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
......@@ -61,7 +61,7 @@ inflate_file(int fd, zentry *entry, int *size_out)
if (entry->csize == (size_t) -1 || entry->isize == (size_t) -1 )
return (NULL);
if (lseek(fd, entry->offset, SEEK_SET) < (off_t)0)
if (JLI_Lseek(fd, entry->offset, SEEK_SET) < (jlong)0)
return (NULL);
if ((in = malloc(entry->csize + 1)) == NULL)
return (NULL);
......@@ -110,6 +110,38 @@ inflate_file(int fd, zentry *entry, int *size_out)
return (NULL);
}
static jboolean zip64_present = JNI_FALSE;
/*
* Checks to see if we have ZIP64 archive, and save
* the check for later use
*/
static int
haveZIP64(Byte *p) {
jlong cenlen, cenoff, centot;
cenlen = ENDSIZ(p);
cenoff = ENDOFF(p);
centot = ENDTOT(p);
zip64_present = (cenlen == ZIP64_MAGICVAL ||
cenoff == ZIP64_MAGICVAL ||
centot == ZIP64_MAGICCOUNT);
return zip64_present;
}
static jlong
find_end64(int fd, Byte *ep, jlong pos)
{
jlong end64pos;
jlong bytes;
if ((end64pos = JLI_Lseek(fd, pos - ZIP64_LOCHDR, SEEK_SET)) < (jlong)0)
return -1;
if ((bytes = read(fd, ep, ZIP64_LOCHDR)) < 0)
return -1;
if (GETSIG(ep) == ZIP64_LOCSIG)
return end64pos;
return -1;
}
/*
* A very little used routine to handle the case that zip file has
* a comment at the end. Believe it or not, the only way to find the
......@@ -122,12 +154,12 @@ inflate_file(int fd, zentry *entry, int *size_out)
* Returns the offset of the END record in the file on success,
* -1 on failure.
*/
static off_t
static jlong
find_end(int fd, Byte *eb)
{
off_t len;
off_t pos;
off_t flen;
jlong len;
jlong pos;
jlong flen;
int bytes;
Byte *cp;
Byte *endpos;
......@@ -136,14 +168,16 @@ find_end(int fd, Byte *eb)
/*
* 99.44% (or more) of the time, there will be no comment at the
* end of the zip file. Try reading just enough to read the END
* record from the end of the file.
* record from the end of the file, at this time we should also
* check to see if we have a ZIP64 archive.
*/
if ((pos = lseek(fd, -ENDHDR, SEEK_END)) < (off_t)0)
if ((pos = JLI_Lseek(fd, -ENDHDR, SEEK_END)) < (jlong)0)
return (-1);
if ((bytes = read(fd, eb, ENDHDR)) < 0)
return (-1);
if (GETSIG(eb) == ENDSIG)
return (pos);
if (GETSIG(eb) == ENDSIG) {
return haveZIP64(eb) ? find_end64(fd, eb, pos) : pos;
}
/*
* Shucky-Darn,... There is a comment at the end of the zip file.
......@@ -151,10 +185,10 @@ find_end(int fd, Byte *eb)
* Allocate and fill a buffer with enough of the zip file
* to meet the specification for a maximal comment length.
*/
if ((flen = lseek(fd, 0, SEEK_END)) < (off_t)0)
if ((flen = JLI_Lseek(fd, 0, SEEK_END)) < (jlong)0)
return (-1);
len = (flen < END_MAXLEN) ? flen : END_MAXLEN;
if (lseek(fd, -len, SEEK_END) < (off_t)0)
if (JLI_Lseek(fd, -len, SEEK_END) < (jlong)0)
return (-1);
if ((buffer = malloc(END_MAXLEN)) == NULL)
return (-1);
......@@ -175,12 +209,92 @@ find_end(int fd, Byte *eb)
(cp + ENDHDR + ENDCOM(cp) == endpos)) {
(void) memcpy(eb, cp, ENDHDR);
free(buffer);
return (flen - (endpos - cp));
pos = flen - (endpos - cp);
return haveZIP64(eb) ? find_end64(fd, eb, pos) : pos;
}
free(buffer);
return (-1);
}
#define BUFSIZE (3 * 65536 + CENHDR + SIGSIZ)
#define MINREAD 1024
/*
* Computes and positions at the start of the CEN header, ie. the central
* directory, this will also return the offset if there is a zip file comment
* at the end of the archive, for most cases this would be 0.
*/
static jlong
compute_cen(int fd, Byte *bp)
{
int bytes;
Byte *p;
jlong base_offset;
jlong offset;
char buffer[MINREAD];
p = buffer;
/*
* Read the END Header, which is the starting point for ZIP files.
* (Clearly designed to make writing a zip file easier than reading
* one. Now isn't that precious...)
*/
if ((base_offset = find_end(fd, bp)) == -1) {
return (-1);
}
p = bp;
/*
* There is a historical, but undocumented, ability to allow for
* additional "stuff" to be prepended to the zip/jar file. It seems
* that this has been used to prepend an actual java launcher
* executable to the jar on Windows. Although this is just another
* form of statically linking a small piece of the JVM to the
* application, we choose to continue to support it. Note that no
* guarantees have been made (or should be made) to the customer that
* this will continue to work.
*
* Therefore, calculate the base offset of the zip file (within the
* expanded file) by assuming that the central directory is followed
* immediately by the end record.
*/
if (zip64_present) {
if ((offset = ZIP64_LOCOFF(p)) < (jlong)0) {
return -1;
}
if (JLI_Lseek(fd, offset, SEEK_SET) < (jlong) 0) {
return (-1);
}
if ((bytes = read(fd, buffer, MINREAD)) < 0) {
return (-1);
}
if (GETSIG(buffer) != ZIP64_ENDSIG) {
return -1;
}
if ((offset = ZIP64_ENDOFF(buffer)) < (jlong)0) {
return -1;
}
if (JLI_Lseek(fd, offset, SEEK_SET) < (jlong)0) {
return (-1);
}
p = buffer;
base_offset = base_offset - ZIP64_ENDSIZ(p) - ZIP64_ENDOFF(p) - ZIP64_ENDHDR;
} else {
base_offset = base_offset - ENDSIZ(p) - ENDOFF(p);
/*
* The END Header indicates the start of the Central Directory
* Headers. Remember that the desired Central Directory Header (CEN)
* will almost always be the second one and the first one is a small
* directory entry ("META-INF/"). Keep the code optimized for
* that case.
*
* Seek to the beginning of the Central Directory.
*/
if (JLI_Lseek(fd, base_offset + ENDOFF(p), SEEK_SET) < (jlong) 0) {
return (-1);
}
}
return base_offset;
}
/*
* Locate the manifest file with the zip/jar file.
*
......@@ -208,9 +322,6 @@ find_end(int fd, Byte *eb)
* a typical jar file (META-INF and META-INF/MANIFEST.MF). Keep this factoid
* in mind when optimizing this code.
*/
#define BUFSIZE (3 * 65536 + CENHDR + SIGSIZ)
#define MINREAD 1024
static int
find_file(int fd, zentry *entry, const char *file_name)
{
......@@ -218,7 +329,7 @@ find_file(int fd, zentry *entry, const char *file_name)
int res;
int entry_size;
int read_size;
int base_offset;
jlong base_offset;
Byte *p;
Byte *bp;
Byte *buffer;
......@@ -228,54 +339,18 @@ find_file(int fd, zentry *entry, const char *file_name)
return(-1);
}
p = buffer;
bp = buffer;
/*
* Read the END Header, which is the starting point for ZIP files.
* (Clearly designed to make writing a zip file easier than reading
* one. Now isn't that precious...)
*/
if ((base_offset = find_end(fd, bp)) == -1) {
base_offset = compute_cen(fd, bp);
if (base_offset == -1) {
free(buffer);
return (-1);
return -1;
}
/*
* There is a historical, but undocumented, ability to allow for
* additional "stuff" to be prepended to the zip/jar file. It seems
* that this has been used to prepend an actual java launcher
* executable to the jar on Windows. Although this is just another
* form of statically linking a small piece of the JVM to the
* application, we choose to continue to support it. Note that no
* guarantees have been made (or should be made) to the customer that
* this will continue to work.
*
* Therefore, calculate the base offset of the zip file (within the
* expanded file) by assuming that the central directory is followed
* immediately by the end record.
*/
base_offset = base_offset - ENDSIZ(p) - ENDOFF(p);
/*
* The END Header indicates the start of the Central Directory
* Headers. Remember that the desired Central Directory Header (CEN)
* will almost always be the second one and the first one is a small
* directory entry ("META-INF/"). Keep the code optimized for
* that case.
*
* Begin by seeking to the beginning of the Central Directory and
* reading in the first buffer full of bits.
*/
if (lseek(fd, base_offset + ENDOFF(p), SEEK_SET) < (off_t)0) {
free(buffer);
return (-1);
}
if ((bytes = read(fd, bp, MINREAD)) < 0) {
free(buffer);
return (-1);
}
p = bp;
/*
* Loop through the Central Directory Headers. Note that a valid zip/jar
* must have an ENDHDR (with ENDSIG) after the Central Directory.
......@@ -319,7 +394,7 @@ find_file(int fd, zentry *entry, const char *file_name)
*/
if ((size_t)CENNAM(p) == JLI_StrLen(file_name) &&
memcmp((p + CENHDR), file_name, JLI_StrLen(file_name)) == 0) {
if (lseek(fd, base_offset + CENOFF(p), SEEK_SET) < (off_t)0) {
if (JLI_Lseek(fd, base_offset + CENOFF(p), SEEK_SET) < (jlong)0) {
free(buffer);
return (-1);
}
......@@ -487,6 +562,9 @@ JLI_ParseManifest(char *jarfile, manifest_info *info)
char *splashscreen_name = NULL;
if ((fd = open(jarfile, O_RDONLY
#ifdef O_LARGEFILE
| O_LARGEFILE /* large file mode on solaris */
#endif
#ifdef O_BINARY
| O_BINARY /* use binary mode on windows */
#endif
......
/*
* Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 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
......@@ -47,18 +47,122 @@ import javax.crypto.BadPaddingException;
* @see OutputFeedback
*/
public final class AESCipher extends CipherSpi {
abstract class AESCipher extends CipherSpi {
public static final class General extends AESCipher {
public General() {
super(-1);
}
}
abstract static class OidImpl extends AESCipher {
protected OidImpl(int keySize, String mode, String padding) {
super(keySize);
try {
engineSetMode(mode);
engineSetPadding(padding);
} catch (GeneralSecurityException gse) {
// internal error; re-throw as provider exception
ProviderException pe =new ProviderException("Internal Error");
pe.initCause(gse);
throw pe;
}
}
}
public static final class AES128_ECB_NoPadding extends OidImpl {
public AES128_ECB_NoPadding() {
super(16, "ECB", "NOPADDING");
}
}
public static final class AES192_ECB_NoPadding extends OidImpl {
public AES192_ECB_NoPadding() {
super(24, "ECB", "NOPADDING");
}
}
public static final class AES256_ECB_NoPadding extends OidImpl {
public AES256_ECB_NoPadding() {
super(32, "ECB", "NOPADDING");
}
}
public static final class AES128_CBC_NoPadding extends OidImpl {
public AES128_CBC_NoPadding() {
super(16, "CBC", "NOPADDING");
}
}
public static final class AES192_CBC_NoPadding extends OidImpl {
public AES192_CBC_NoPadding() {
super(24, "CBC", "NOPADDING");
}
}
public static final class AES256_CBC_NoPadding extends OidImpl {
public AES256_CBC_NoPadding() {
super(32, "CBC", "NOPADDING");
}
}
public static final class AES128_OFB_NoPadding extends OidImpl {
public AES128_OFB_NoPadding() {
super(16, "OFB", "NOPADDING");
}
}
public static final class AES192_OFB_NoPadding extends OidImpl {
public AES192_OFB_NoPadding() {
super(24, "OFB", "NOPADDING");
}
}
public static final class AES256_OFB_NoPadding extends OidImpl {
public AES256_OFB_NoPadding() {
super(32, "OFB", "NOPADDING");
}
}
public static final class AES128_CFB_NoPadding extends OidImpl {
public AES128_CFB_NoPadding() {
super(16, "CFB", "NOPADDING");
}
}
public static final class AES192_CFB_NoPadding extends OidImpl {
public AES192_CFB_NoPadding() {
super(24, "CFB", "NOPADDING");
}
}
public static final class AES256_CFB_NoPadding extends OidImpl {
public AES256_CFB_NoPadding() {
super(32, "CFB", "NOPADDING");
}
}
// utility method used by AESCipher and AESWrapCipher
static final void checkKeySize(Key key, int fixedKeySize)
throws InvalidKeyException {
if (fixedKeySize != -1) {
if (key == null) {
throw new InvalidKeyException("The key must not be null");
}
byte[] value = key.getEncoded();
if (value == null) {
throw new InvalidKeyException("Key encoding must not be null");
} else if (value.length != fixedKeySize) {
throw new InvalidKeyException("The key must be " +
fixedKeySize*8 + " bits");
}
}
}
/*
* internal CipherCore object which does the real work.
*/
private CipherCore core = null;
/*
* needed to support AES oids which associates a fixed key size
* to the cipher object.
*/
private final int fixedKeySize; // in bytes, -1 if no restriction
/**
* Creates an instance of AES cipher with default ECB mode and
* PKCS5Padding.
*/
public AESCipher() {
protected AESCipher(int keySize) {
core = new CipherCore(new AESCrypt(), AESConstants.AES_BLOCK_SIZE);
fixedKeySize = keySize;
}
/**
......@@ -183,6 +287,7 @@ public final class AESCipher extends CipherSpi {
*/
protected void engineInit(int opmode, Key key, SecureRandom random)
throws InvalidKeyException {
checkKeySize(key, fixedKeySize);
core.init(opmode, key, random);
}
......@@ -214,6 +319,7 @@ public final class AESCipher extends CipherSpi {
AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
checkKeySize(key, fixedKeySize);
core.init(opmode, key, params, random);
}
......@@ -221,6 +327,7 @@ public final class AESCipher extends CipherSpi {
AlgorithmParameters params,
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
checkKeySize(key, fixedKeySize);
core.init(opmode, key, params, random);
}
......
/*
* Copyright (c) 2004, 2009, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 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
......@@ -43,8 +43,27 @@ import javax.crypto.spec.*;
*
* @see AESCipher
*/
public final class AESWrapCipher extends CipherSpi {
abstract class AESWrapCipher extends CipherSpi {
public static final class General extends AESWrapCipher {
public General() {
super(-1);
}
}
public static final class AES128 extends AESWrapCipher {
public AES128() {
super(16);
}
}
public static final class AES192 extends AESWrapCipher {
public AES192() {
super(24);
}
}
public static final class AES256 extends AESWrapCipher {
public AES256() {
super(32);
}
}
private static final byte[] IV = {
(byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6,
(byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6
......@@ -62,12 +81,20 @@ public final class AESWrapCipher extends CipherSpi {
*/
private boolean decrypting = false;
/*
* needed to support AES oids which associates a fixed key size
* to the cipher object.
*/
private final int fixedKeySize; // in bytes, -1 if no restriction
/**
* Creates an instance of AES KeyWrap cipher with default
* mode, i.e. "ECB" and padding scheme, i.e. "NoPadding".
*/
public AESWrapCipher() {
public AESWrapCipher(int keySize) {
cipher = new AESCrypt();
fixedKeySize = keySize;
}
/**
......@@ -170,6 +197,7 @@ public final class AESWrapCipher extends CipherSpi {
throw new UnsupportedOperationException("This cipher can " +
"only be used for key wrapping and unwrapping");
}
AESCipher.checkKeySize(key, fixedKeySize);
cipher.init(decrypting, key.getAlgorithm(), key.getEncoded());
}
......
/*
* Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
......@@ -80,10 +80,10 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi {
* @param random the source of randomness
*/
public void initialize(int keysize, SecureRandom random) {
if ((keysize < 512) || (keysize > 1024) || (keysize % 64 != 0)) {
if ((keysize < 512) || (keysize > 2048) || (keysize % 64 != 0)) {
throw new InvalidParameterException("Keysize must be multiple "
+ "of 64, and can only range "
+ "from 512 to 1024 "
+ "from 512 to 2048 "
+ "(inclusive)");
}
this.pSize = keysize;
......@@ -115,11 +115,11 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi {
params = (DHParameterSpec)algParams;
pSize = params.getP().bitLength();
if ((pSize < 512) || (pSize > 1024) ||
if ((pSize < 512) || (pSize > 2048) ||
(pSize % 64 != 0)) {
throw new InvalidAlgorithmParameterException
("Prime size must be multiple of 64, and can only range "
+ "from 512 to 1024 (inclusive)");
+ "from 512 to 2048 (inclusive)");
}
// exponent size is optional, could be 0
......@@ -156,10 +156,11 @@ public final class DHKeyPairGenerator extends KeyPairGeneratorSpi {
BigInteger g = params.getG();
if (lSize <= 0) {
lSize = pSize >> 1;
// use an exponent size of (pSize / 2) but at least 384 bits
lSize = Math.max(384, pSize >> 1);
// if lSize is larger than pSize, limit by pSize
lSize = Math.min(lSize, pSize);
if (lSize < 384) {
lSize = 384;
}
}
BigInteger x;
......
/*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
......@@ -67,10 +67,10 @@ extends AlgorithmParameterGeneratorSpi {
* @param random the source of randomness
*/
protected void engineInit(int keysize, SecureRandom random) {
if ((keysize < 512) || (keysize > 1024) || (keysize % 64 != 0)) {
if ((keysize < 512) || (keysize > 2048) || (keysize % 64 != 0)) {
throw new InvalidParameterException("Keysize must be multiple "
+ "of 64, and can only range "
+ "from 512 to 1024 "
+ "from 512 to 2048 "
+ "(inclusive)");
}
this.primeSize = keysize;
......@@ -99,10 +99,10 @@ extends AlgorithmParameterGeneratorSpi {
DHGenParameterSpec dhParamSpec = (DHGenParameterSpec)genParamSpec;
primeSize = dhParamSpec.getPrimeSize();
if ((primeSize<512) || (primeSize>1024) || (primeSize%64 != 0)) {
if ((primeSize<512) || (primeSize>2048) || (primeSize%64 != 0)) {
throw new InvalidAlgorithmParameterException
("Modulus size must be multiple of 64, and can only range "
+ "from 512 to 1024 (inclusive)");
+ "from 512 to 2048 (inclusive)");
}
exponentSize = dhParamSpec.getExponentSize();
......
......@@ -167,17 +167,67 @@ public final class SunJCE extends Provider {
put("Cipher.Blowfish SupportedPaddings", BLOCK_PADS);
put("Cipher.Blowfish SupportedKeyFormats", "RAW");
put("Cipher.AES", "com.sun.crypto.provider.AESCipher");
put("Cipher.AES", "com.sun.crypto.provider.AESCipher$General");
put("Alg.Alias.Cipher.Rijndael", "AES");
put("Cipher.AES SupportedModes", BLOCK_MODES128);
put("Cipher.AES SupportedPaddings", BLOCK_PADS);
put("Cipher.AES SupportedKeyFormats", "RAW");
put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher");
put("Cipher.AES_128/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_ECB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.1", "AES_128/ECB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.1", "AES_128/ECB/NoPadding");
put("Cipher.AES_128/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_CBC_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.2", "AES_128/CBC/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.2", "AES_128/CBC/NoPadding");
put("Cipher.AES_128/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_OFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.3", "AES_128/OFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.3", "AES_128/OFB/NoPadding");
put("Cipher.AES_128/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES128_CFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.4", "AES_128/CFB/NoPadding");
put("Cipher.AES_192/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_ECB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.21", "AES_192/ECB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.21", "AES_192/ECB/NoPadding");
put("Cipher.AES_192/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_CBC_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.22", "AES_192/CBC/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.22", "AES_192/CBC/NoPadding");
put("Cipher.AES_192/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_OFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.23", "AES_192/OFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.23", "AES_192/OFB/NoPadding");
put("Cipher.AES_192/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES192_CFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.24", "AES_192/CFB/NoPadding");
put("Cipher.AES_256/ECB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_ECB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.41", "AES_256/ECB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.41", "AES_256/ECB/NoPadding");
put("Cipher.AES_256/CBC/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_CBC_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.42", "AES_256/CBC/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.42", "AES_256/CBC/NoPadding");
put("Cipher.AES_256/OFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_OFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.43", "AES_256/OFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.43", "AES_256/OFB/NoPadding");
put("Cipher.AES_256/CFB/NoPadding", "com.sun.crypto.provider.AESCipher$AES256_CFB_NoPadding");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.44", "AES_256/CFB/NoPadding");
put("Cipher.AESWrap", "com.sun.crypto.provider.AESWrapCipher$General");
put("Cipher.AESWrap SupportedModes", "ECB");
put("Cipher.AESWrap SupportedPaddings", "NOPADDING");
put("Cipher.AESWrap SupportedKeyFormats", "RAW");
put("Cipher.AESWrap_128", "com.sun.crypto.provider.AESWrapCipher$AES128");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.5", "AESWrap_128");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.5", "AESWrap_128");
put("Cipher.AESWrap_192", "com.sun.crypto.provider.AESWrapCipher$AES192");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.25", "AESWrap_192");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.25", "AESWrap_192");
put("Cipher.AESWrap_256", "com.sun.crypto.provider.AESWrapCipher$AES256");
put("Alg.Alias.Cipher.2.16.840.1.101.3.4.1.45", "AESWrap_256");
put("Alg.Alias.Cipher.OID.2.16.840.1.101.3.4.1.45", "AESWrap_256");
put("Cipher.RC2",
"com.sun.crypto.provider.RC2Cipher");
put("Cipher.RC2 SupportedModes", BLOCK_MODES);
......@@ -192,7 +242,7 @@ public final class SunJCE extends Provider {
put("Cipher.ARCFOUR SupportedKeyFormats", "RAW");
/*
* Key(pair) Generator engines
* Key(pair) Generator engines
*/
put("KeyGenerator.DES",
"com.sun.crypto.provider.DESKeyGenerator");
......@@ -221,6 +271,8 @@ public final class SunJCE extends Provider {
put("KeyGenerator.HmacSHA1",
"com.sun.crypto.provider.HmacSHA1KeyGenerator");
put("Alg.Alias.KeyGenerator.OID.1.2.840.113549.2.7", "HmacSHA1");
put("Alg.Alias.KeyGenerator.1.2.840.113549.2.7", "HmacSHA1");
put("KeyGenerator.HmacSHA224",
"com.sun.crypto.provider.KeyGeneratorCore$HmacSHA2KG$SHA224");
......@@ -326,14 +378,12 @@ public final class SunJCE extends Provider {
"com.sun.crypto.provider.AESParameters");
put("Alg.Alias.AlgorithmParameters.Rijndael", "AES");
put("AlgorithmParameters.RC2",
"com.sun.crypto.provider.RC2Parameters");
put("AlgorithmParameters.OAEP",
"com.sun.crypto.provider.OAEPParameters");
/*
* Key factories
*/
......@@ -403,6 +453,8 @@ public final class SunJCE extends Provider {
*/
put("Mac.HmacMD5", "com.sun.crypto.provider.HmacMD5");
put("Mac.HmacSHA1", "com.sun.crypto.provider.HmacSHA1");
put("Alg.Alias.Mac.OID.1.2.840.113549.2.7", "HmacSHA1");
put("Alg.Alias.Mac.1.2.840.113549.2.7", "HmacSHA1");
put("Mac.HmacSHA224",
"com.sun.crypto.provider.HmacCore$HmacSHA224");
put("Alg.Alias.Mac.OID.1.2.840.113549.2.8", "HmacSHA224");
......
......@@ -30,6 +30,8 @@ import java.awt.Container;
import java.awt.Event;
import java.awt.KeyEventPostProcessor;
import java.awt.Window;
import java.awt.Toolkit;
import sun.awt.SunToolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
......@@ -125,7 +127,19 @@ public class WindowsRootPaneUI extends BasicRootPaneUI {
}
JMenu menu = mbar != null ? mbar.getMenu(0) : null;
if (menu != null) {
// It might happen that the altRelease event is processed
// with a reasonable delay since it has been generated.
// Here we check the last deactivation time of the containing
// window. If this time appears to be greater than the altRelease
// event time the event is skipped to avoid unexpected menu
// activation. See 7121442.
boolean skip = false;
Toolkit tk = Toolkit.getDefaultToolkit();
if (tk instanceof SunToolkit) {
skip = ev.getWhen() <= ((SunToolkit)tk).getWindowDeactivationTime(winAncestor);
}
if (menu != null && !skip) {
MenuElement[] path = new MenuElement[2];
path[0] = mbar;
path[1] = menu;
......
......@@ -4710,7 +4710,10 @@ public abstract class Component implements ImageObserver, MenuContainer,
/*
* 0. Set timestamp and modifiers of current event.
*/
EventQueue.setCurrentEventAndMostRecentTime(e);
if (!(e instanceof KeyEvent)) {
// Timestamp of a key event is set later in DKFM.preDispatchKeyEvent(KeyEvent).
EventQueue.setCurrentEventAndMostRecentTime(e);
}
/*
* 1. Pre-dispatchers. Do any necessary retargeting/reordering here
......@@ -7606,13 +7609,33 @@ public abstract class Component implements ImageObserver, MenuContainer,
boolean focusedWindowChangeAllowed,
CausedFocusEvent.Cause cause)
{
// 1) Check if the event being dispatched is a system-generated mouse event.
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof MouseEvent &&
SunToolkit.isSystemGenerated(currentEvent))
{
// 2) Sanity check: if the mouse event component source belongs to the same containing window.
Component source = ((MouseEvent)currentEvent).getComponent();
if (source == null || source.getContainingWindow() == getContainingWindow()) {
focusLog.finest("requesting focus by mouse event \"in window\"");
// If both the conditions are fulfilled the focus request should be strictly
// bounded by the toplevel window. It's assumed that the mouse event activates
// the window (if it wasn't active) and this makes it possible for a focus
// request with a strong in-window requirement to change focus in the bounds
// of the toplevel. If, by any means, due to asynchronous nature of the event
// dispatching mechanism, the window happens to be natively inactive by the time
// this focus request is eventually handled, it should not re-activate the
// toplevel. Otherwise the result may not meet user expectations. See 6981400.
focusedWindowChangeAllowed = false;
}
}
if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
if (focusLog.isLoggable(PlatformLogger.FINEST)) {
focusLog.finest("requestFocus is not accepted");
}
return false;
}
// Update most-recent map
KeyboardFocusManager.setMostRecentFocusOwner(this);
......@@ -7645,7 +7668,15 @@ public abstract class Component implements ImageObserver, MenuContainer,
}
// Focus this Component
long time = EventQueue.getMostRecentEventTime();
long time = 0;
if (EventQueue.isDispatchThread()) {
time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
} else {
// A focus request made from outside EDT should not be associated with any event
// and so its time stamp is simply set to the current time.
time = System.currentTimeMillis();
}
boolean success = peer.requestFocus
(this, temporary, focusedWindowChangeAllowed, time, cause);
if (!success) {
......
......@@ -2863,7 +2863,7 @@ public class Container extends Component {
// keep the KeyEvents from being dispatched
// until the focus has been transfered
long time = Toolkit.getEventQueue().getMostRecentEventTime();
long time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
Component predictedFocusOwner = (Component.isInstanceOf(this, "javax.swing.JInternalFrame")) ? ((javax.swing.JInternalFrame)(this)).getMostRecentFocusOwner() : null;
if (predictedFocusOwner != null) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().
......
......@@ -41,6 +41,7 @@ import sun.awt.AppContext;
import sun.awt.SunToolkit;
import sun.awt.AWTAccessor;
import sun.awt.CausedFocusEvent;
import sun.awt.TimedWindowEvent;
/**
* The default KeyboardFocusManager for AWT applications. Focus traversal is
......@@ -72,8 +73,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
private WeakReference<Window> realOppositeWindowWR = NULL_WINDOW_WR;
private WeakReference<Component> realOppositeComponentWR = NULL_COMPONENT_WR;
private int inSendMessage;
private LinkedList enqueuedKeyEvents = new LinkedList(),
typeAheadMarkers = new LinkedList();
private LinkedList<KeyEvent> enqueuedKeyEvents = new LinkedList<KeyEvent>();
private LinkedList<TypeAheadMarker> typeAheadMarkers = new LinkedList<TypeAheadMarker>();
private boolean consumeNextKeyTyped;
static {
......@@ -269,6 +270,31 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
return se.dispatched;
}
/*
* Checks if the focus window event follows key events waiting in the type-ahead
* queue (if any). This may happen when a user types ahead in the window, the client
* listeners hang EDT for a while, and the user switches b/w toplevels. In that
* case the focus window events may be dispatched before the type-ahead events
* get handled. This may lead to wrong focus behavior and in order to avoid it,
* the focus window events are reposted to the end of the event queue. See 6981400.
*/
private boolean repostIfFollowsKeyEvents(WindowEvent e) {
if (!(e instanceof TimedWindowEvent)) {
return false;
}
TimedWindowEvent we = (TimedWindowEvent)e;
long time = we.getWhen();
synchronized (this) {
for (KeyEvent ke: enqueuedKeyEvents) {
if (time >= ke.getWhen()) {
SunToolkit.postEvent(AppContext.getAppContext(), new SequencedEvent(e));
return true;
}
}
}
return false;
}
/**
* This method is called by the AWT event dispatcher requesting that the
* current KeyboardFocusManager dispatch the specified event on its behalf.
......@@ -287,6 +313,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
if (focusLog.isLoggable(PlatformLogger.FINE) && (e instanceof WindowEvent || e instanceof FocusEvent)) focusLog.fine("" + e);
switch (e.getID()) {
case WindowEvent.WINDOW_GAINED_FOCUS: {
if (repostIfFollowsKeyEvents((WindowEvent)e)) {
break;
}
WindowEvent we = (WindowEvent)e;
Window oldFocusedWindow = getGlobalFocusedWindow();
Window newFocusedWindow = we.getWindow();
......@@ -646,6 +676,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
}
case WindowEvent.WINDOW_LOST_FOCUS: {
if (repostIfFollowsKeyEvents((WindowEvent)e)) {
break;
}
WindowEvent we = (WindowEvent)e;
Window currentFocusedWindow = getGlobalFocusedWindow();
Window losingFocusWindow = we.getWindow();
......@@ -825,10 +859,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
ke = null;
synchronized (this) {
if (enqueuedKeyEvents.size() != 0) {
ke = (KeyEvent)enqueuedKeyEvents.getFirst();
ke = enqueuedKeyEvents.getFirst();
if (typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = (TypeAheadMarker)
typeAheadMarkers.getFirst();
TypeAheadMarker marker = typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
......@@ -857,9 +890,9 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
focusLog.finest(">>> Markers dump, time: {0}", System.currentTimeMillis());
synchronized (this) {
if (typeAheadMarkers.size() != 0) {
Iterator iter = typeAheadMarkers.iterator();
Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
while (iter.hasNext()) {
TypeAheadMarker marker = (TypeAheadMarker)iter.next();
TypeAheadMarker marker = iter.next();
focusLog.finest(" {0}", marker);
}
}
......@@ -881,8 +914,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
KeyEvent ke = (KeyEvent)e;
synchronized (this) {
if (e.isPosted && typeAheadMarkers.size() != 0) {
TypeAheadMarker marker = (TypeAheadMarker)
typeAheadMarkers.getFirst();
TypeAheadMarker marker = typeAheadMarkers.getFirst();
// Fixed 5064013: may appears that the events have the same time
// if (ke.getWhen() >= marker.after) {
// The fix is rolled out.
......@@ -915,12 +947,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
synchronized (this) {
boolean found = false;
if (hasMarker(target)) {
for (Iterator iter = typeAheadMarkers.iterator();
for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator();
iter.hasNext(); )
{
if (((TypeAheadMarker)iter.next()).untilFocused ==
target)
{
if (iter.next().untilFocused == target) {
found = true;
} else if (found) {
break;
......@@ -955,8 +985,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
* @since 1.5
*/
private boolean hasMarker(Component comp) {
for (Iterator iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
if (((TypeAheadMarker)iter.next()).untilFocused == comp) {
for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
if (iter.next().untilFocused == comp) {
return true;
}
}
......@@ -982,11 +1012,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
return true;
}
// Explicitly set the current event and most recent timestamp here in
// addition to the call in Component.dispatchEventImpl. Because
// KeyEvents can be delivered in response to a FOCUS_GAINED event, the
// current timestamp may be incorrect. We need to set it here so that
// KeyEventDispatchers will use the correct time.
// Explicitly set the key event timestamp here (not in Component.dispatchEventImpl):
// - A key event is anyway passed to this method which starts its actual dispatching.
// - If a key event is put to the type ahead queue, its time stamp should not be registered
// until its dispatching actually starts (by this method).
EventQueue.setCurrentEventAndMostRecentTime(ke);
/**
......@@ -1174,10 +1203,10 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
int insertionIndex = 0,
i = typeAheadMarkers.size();
ListIterator iter = typeAheadMarkers.listIterator(i);
ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator(i);
for (; i > 0; i--) {
TypeAheadMarker marker = (TypeAheadMarker)iter.previous();
TypeAheadMarker marker = iter.previous();
if (marker.after <= after) {
insertionIndex = i;
break;
......@@ -1213,12 +1242,12 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
after, untilFocused);
TypeAheadMarker marker;
ListIterator iter = typeAheadMarkers.listIterator
ListIterator<TypeAheadMarker> iter = typeAheadMarkers.listIterator
((after >= 0) ? typeAheadMarkers.size() : 0);
if (after < 0) {
while (iter.hasNext()) {
marker = (TypeAheadMarker)iter.next();
marker = iter.next();
if (marker.untilFocused == untilFocused)
{
iter.remove();
......@@ -1227,7 +1256,7 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
}
} else {
while (iter.hasPrevious()) {
marker = (TypeAheadMarker)iter.previous();
marker = iter.previous();
if (marker.untilFocused == untilFocused &&
marker.after == after)
{
......@@ -1255,8 +1284,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
long start = -1;
for (Iterator iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
TypeAheadMarker marker = (TypeAheadMarker)iter.next();
for (Iterator<TypeAheadMarker> iter = typeAheadMarkers.iterator(); iter.hasNext(); ) {
TypeAheadMarker marker = iter.next();
Component toTest = marker.untilFocused;
boolean match = (toTest == comp);
while (!match && toTest != null && !(toTest instanceof Window)) {
......@@ -1287,8 +1316,8 @@ public class DefaultKeyboardFocusManager extends KeyboardFocusManager {
return;
}
for (Iterator iter = enqueuedKeyEvents.iterator(); iter.hasNext(); ) {
KeyEvent ke = (KeyEvent)iter.next();
for (Iterator<KeyEvent> iter = enqueuedKeyEvents.iterator(); iter.hasNext(); ) {
KeyEvent ke = iter.next();
long time = ke.getWhen();
if (start < time && (end < 0 || time <= end)) {
......
......@@ -924,7 +924,7 @@ public class Dialog extends Window {
isEnabled() && !isModalBlocked()) {
// keep the KeyEvents from being dispatched
// until the focus has been transfered
time.set(Toolkit.getEventQueue().getMostRecentEventTimeEx());
time.set(Toolkit.getEventQueue().getMostRecentKeyEventTime());
KeyboardFocusManager.getCurrentKeyboardFocusManager().
enqueueKeyEvents(time.get(), toFocus);
}
......
......@@ -162,6 +162,11 @@ public class EventQueue {
*/
private long mostRecentEventTime = System.currentTimeMillis();
/*
* The time stamp of the last KeyEvent .
*/
private long mostRecentKeyEventTime = System.currentTimeMillis();
/**
* The modifiers field of the current event, if the current event is an
* InputEvent or ActionEvent.
......@@ -1142,6 +1147,15 @@ public class EventQueue {
}
}
synchronized long getMostRecentKeyEventTime() {
pushPopLock.lock();
try {
return mostRecentKeyEventTime;
} finally {
pushPopLock.unlock();
}
}
static void setCurrentEventAndMostRecentTime(AWTEvent e) {
Toolkit.getEventQueue().setCurrentEventAndMostRecentTimeImpl(e);
}
......@@ -1166,6 +1180,9 @@ public class EventQueue {
if (e instanceof InputEvent) {
InputEvent ie = (InputEvent)e;
mostRecentEventTime2 = ie.getWhen();
if (e instanceof KeyEvent) {
mostRecentKeyEventTime = ie.getWhen();
}
} else if (e instanceof InputMethodEvent) {
InputMethodEvent ime = (InputMethodEvent)e;
mostRecentEventTime2 = ime.getWhen();
......
......@@ -445,7 +445,7 @@ public abstract class KeyboardFocusManager
private void initPeer() {
Toolkit tk = Toolkit.getDefaultToolkit();
KeyboardFocusManagerPeerProvider peerProvider = (KeyboardFocusManagerPeerProvider)tk;
peer = peerProvider.createKeyboardFocusManagerPeer(this);
peer = peerProvider.getKeyboardFocusManagerPeer();
}
/**
......
......@@ -26,6 +26,7 @@
package java.awt;
import java.util.LinkedList;
import sun.awt.AWTAccessor;
import sun.awt.AppContext;
import sun.awt.SunToolkit;
......@@ -54,6 +55,17 @@ class SequencedEvent extends AWTEvent implements ActiveEvent {
private AppContext appContext;
private boolean disposed;
static {
AWTAccessor.setSequencedEventAccessor(new AWTAccessor.SequencedEventAccessor() {
public AWTEvent getNested(AWTEvent sequencedEvent) {
return ((SequencedEvent)sequencedEvent).nested;
}
public boolean isSequencedEvent(AWTEvent event) {
return event instanceof SequencedEvent;
}
});
}
/**
* Constructs a new SequencedEvent which will dispatch the specified
* nested event.
......
......@@ -33,6 +33,14 @@ import java.awt.Window;
*/
public interface KeyboardFocusManagerPeer {
/**
* Sets the window that should become the focused window.
*
* @param win the window that should become the focused window
*
*/
void setCurrentFocusedWindow(Window win);
/**
* Returns the currently focused window.
*
......
......@@ -1460,7 +1460,7 @@ class GenericBeanInfo extends SimpleBeanInfo {
private PropertyDescriptor[] properties;
private int defaultProperty;
private MethodDescriptor[] methods;
private final Reference<BeanInfo> targetBeanInfoRef;
private Reference<BeanInfo> targetBeanInfoRef;
public GenericBeanInfo(BeanDescriptor beanDescriptor,
EventSetDescriptor[] events, int defaultEvent,
......@@ -1472,7 +1472,9 @@ class GenericBeanInfo extends SimpleBeanInfo {
this.properties = properties;
this.defaultProperty = defaultProperty;
this.methods = methods;
this.targetBeanInfoRef = new SoftReference<>(targetBeanInfo);
this.targetBeanInfoRef = (targetBeanInfo != null)
? new SoftReference<>(targetBeanInfo)
: null;
}
/**
......@@ -1539,10 +1541,25 @@ class GenericBeanInfo extends SimpleBeanInfo {
}
public java.awt.Image getIcon(int iconKind) {
BeanInfo targetBeanInfo = this.targetBeanInfoRef.get();
BeanInfo targetBeanInfo = getTargetBeanInfo();
if (targetBeanInfo != null) {
return targetBeanInfo.getIcon(iconKind);
}
return super.getIcon(iconKind);
}
private BeanInfo getTargetBeanInfo() {
if (this.targetBeanInfoRef == null) {
return null;
}
BeanInfo targetBeanInfo = this.targetBeanInfoRef.get();
if (targetBeanInfo == null) {
targetBeanInfo = ThreadGroupContext.getContext().getBeanInfoFinder()
.find(this.beanDescriptor.getBeanClass());
if (targetBeanInfo != null) {
this.targetBeanInfoRef = new SoftReference<>(targetBeanInfo);
}
}
return targetBeanInfo;
}
}
......@@ -109,6 +109,10 @@ public class PropertyDescriptor extends FeatureDescriptor {
if (writeMethodName != null && getWriteMethod() == null) {
throw new IntrospectionException("Method not found: " + writeMethodName);
}
boundInitialization(beanClass);
}
private void boundInitialization(Class<?> beanClass) {
// If this class or one of its base classes allow PropertyChangeListener,
// then we assume that any properties we discover are "bound".
// See Introspector.getTargetPropertyInfo() method.
......@@ -159,6 +163,7 @@ public class PropertyDescriptor extends FeatureDescriptor {
setReadMethod(read);
setWriteMethod(write);
this.baseName = base;
boundInitialization(bean);
}
/**
......@@ -588,7 +593,7 @@ public class PropertyDescriptor extends FeatureDescriptor {
Method yw = y.getWriteMethod();
try {
if (yw != null && yw.getDeclaringClass() == getClass0()) {
if (yw != null) {
setWriteMethod(yw);
} else {
setWriteMethod(xw);
......
......@@ -631,7 +631,12 @@ public class XMLEncoder extends Encoder implements AutoCloseable {
}
if (d.name != null) {
outputXML(isArgument ? "object" : "void", " idref=" + quote(d.name), value);
if (isArgument) {
writeln("<object idref=" + quote(d.name) + "/>");
}
else {
outputXML("void", " idref=" + quote(d.name), value);
}
}
else if (d.exp != null) {
outputStatement(d.exp, outer, isArgument);
......@@ -710,12 +715,14 @@ public class XMLEncoder extends Encoder implements AutoCloseable {
}
else {
d.refs = 2;
getValueData(target).refs++;
List<Statement> statements = statementList(target);
if (!statements.contains(exp)) {
statements.add(exp);
if (d.name == null) {
getValueData(target).refs++;
List<Statement> statements = statementList(target);
if (!statements.contains(exp)) {
statements.add(exp);
}
outputValue(target, outer, false);
}
outputValue(target, outer, false);
if (expression) {
outputValue(value, outer, isArgument);
}
......
/*
* Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1994, 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
......@@ -210,21 +210,21 @@ public class ByteArrayOutputStream extends OutputStream {
/**
* Converts the buffer's contents into a string by decoding the bytes using
* the specified {@link java.nio.charset.Charset charsetName}. The length of
* the new <tt>String</tt> is a function of the charset, and hence may not be
* equal to the length of the byte array.
* the named {@link java.nio.charset.Charset charset}. The length of the new
* <tt>String</tt> is a function of the charset, and hence may not be equal
* to the length of the byte array.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*
* @param charsetName the name of a supported
* {@linkplain java.nio.charset.Charset </code>charset<code>}
* @return String decoded from the buffer's contents.
* @param charsetName the name of a supported
* {@link java.nio.charset.Charset charset}
* @return String decoded from the buffer's contents.
* @exception UnsupportedEncodingException
* If the named charset is not supported
* @since JDK1.1
* @since JDK1.1
*/
public synchronized String toString(String charsetName)
throws UnsupportedEncodingException
......
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 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
......@@ -86,7 +86,7 @@ public class InputStreamReader extends Reader {
*
* @param charsetName
* The name of a supported
* {@link java.nio.charset.Charset </code>charset<code>}
* {@link java.nio.charset.Charset charset}
*
* @exception UnsupportedEncodingException
* If the named charset is not supported
......
/*
* Copyright (c) 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 java.lang.annotation;
/**
* Indicates that an annotation type is a container for repeated
* instances of annotations of the type of the value of the
* {@code ContainerFor}'s value element.
*
* @since 1.8
* @jls 9.6 Annotation Types
* @jls 9.7 Annotations
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface ContainerFor {
/**
* The repeating annotation type that the annotation type
* annotated with this annotation is a container for.
*/
Class<? extends Annotation> value();
}
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
......@@ -62,6 +62,9 @@ import java.security.*;
* interface is all that is needed when you accept defaults for algorithm-specific
* parameters.
*
* <p>Note: Some earlier implementations of this interface may not support
* larger sizes of DSA parameters such as 2048 and 3072-bit.
*
* @see java.security.KeyPairGenerator
*/
public interface DSAKeyPairGenerator {
......@@ -78,7 +81,7 @@ public interface DSAKeyPairGenerator {
* can be null.
*
* @exception InvalidParameterException if the <code>params</code>
* value is invalid or null.
* value is invalid, null, or unsupported.
*/
public void initialize(DSAParams params, SecureRandom random)
throws InvalidParameterException;
......@@ -97,7 +100,7 @@ public interface DSAKeyPairGenerator {
* default parameters for modulus lengths of 512 and 1024 bits.
*
* @param modlen the modulus length in bits. Valid values are any
* multiple of 8 between 512 and 1024, inclusive.
* multiple of 64 between 512 and 1024, inclusive, 2048, and 3072.
*
* @param random the random bit source to use to generate key bits;
* can be null.
......@@ -105,10 +108,9 @@ public interface DSAKeyPairGenerator {
* @param genParams whether or not to generate new parameters for
* the modulus length requested.
*
* @exception InvalidParameterException if <code>modlen</code> is not
* between 512 and 1024, or if <code>genParams</code> is false and
* there are no precomputed parameters for the requested modulus
* length.
* @exception InvalidParameterException if <code>modlen</code> is
* invalid, or unsupported, or if <code>genParams</code> is false and there
* are no precomputed parameters for the requested modulus length.
*/
public void initialize(int modlen, boolean genParams, SecureRandom random)
throws InvalidParameterException;
......
/*
* Copyright (c) 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 java.security.spec;
/**
* This immutable class specifies the set of parameters used for
* generating DSA parameters as specified in
* <a href="http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf">FIPS 186-3 Digital Signature Standard (DSS)</a>.
*
* @see AlgorithmParameterSpec
*
* @since 8
*/
public final class DSAGenParameterSpec implements AlgorithmParameterSpec {
private final int pLen;
private final int qLen;
private final int seedLen;
/**
* Creates a domain parameter specification for DSA parameter
* generation using <code>primePLen</code> and <code>subprimeQLen</code>.
* The value of <code>subprimeQLen</code> is also used as the default
* length of the domain parameter seed in bits.
* @param primePLen the desired length of the prime P in bits.
* @param subprimeQLen the desired length of the sub-prime Q in bits.
* @exception IllegalArgumentException if <code>primePLen</code>
* or <code>subprimeQLen</code> is illegal per the specification of
* FIPS 186-3.
*/
public DSAGenParameterSpec(int primePLen, int subprimeQLen) {
this(primePLen, subprimeQLen, subprimeQLen);
}
/**
* Creates a domain parameter specification for DSA parameter
* generation using <code>primePLen</code>, <code>subprimeQLen</code>,
* and <code>seedLen</code>.
* @param primePLen the desired length of the prime P in bits.
* @param subprimeQLen the desired length of the sub-prime Q in bits.
* @param seedLen the desired length of the domain parameter seed in bits,
* shall be equal to or greater than <code>subprimeQLen</code>.
* @exception IllegalArgumentException if <code>primePLenLen</code>,
* <code>subprimeQLen</code>, or <code>seedLen</code> is illegal per the
* specification of FIPS 186-3.
*/
public DSAGenParameterSpec(int primePLen, int subprimeQLen, int seedLen) {
switch (primePLen) {
case 1024:
if (subprimeQLen != 160) {
throw new IllegalArgumentException
("subprimeQLen must be 160 when primePLen=1024");
}
break;
case 2048:
if (subprimeQLen != 224 && subprimeQLen != 256) {
throw new IllegalArgumentException
("subprimeQLen must be 224 or 256 when primePLen=2048");
}
break;
case 3072:
if (subprimeQLen != 256) {
throw new IllegalArgumentException
("subprimeQLen must be 256 when primePLen=3072");
}
break;
default:
throw new IllegalArgumentException
("primePLen must be 1024, 2048, or 3072");
}
if (seedLen < subprimeQLen) {
throw new IllegalArgumentException
("seedLen must be equal to or greater than subprimeQLen");
}
this.pLen = primePLen;
this.qLen = subprimeQLen;
this.seedLen = seedLen;
}
/**
* Returns the desired length of the prime P of the
* to-be-generated DSA domain parameters in bits.
* @return the length of the prime P.
*/
public int getPrimePLength() {
return pLen;
}
/**
* Returns the desired length of the sub-prime Q of the
* to-be-generated DSA domain parameters in bits.
* @return the length of the sub-prime Q.
*/
public int getSubprimeQLength() {
return qLen;
}
/**
* Returns the desired length of the domain parameter seed in bits.
* @return the length of the domain parameter seed.
*/
public int getSeedLength() {
return seedLen;
}
}
......@@ -510,7 +510,7 @@ public class DriverManager {
public Void run() {
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
Iterator driversIterator = loadedDrivers.iterator();
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
......
......@@ -666,6 +666,21 @@ public final class AWTAccessor {
public void consumeNextKeyTyped(DefaultKeyboardFocusManager dkfm, KeyEvent e);
}
/*
* An accessor for the SequencedEventAccessor class
*/
public interface SequencedEventAccessor {
/*
* Returns the nested event.
*/
AWTEvent getNested(AWTEvent sequencedEvent);
/*
* Returns true if the event is an instances of SequencedEvent.
*/
boolean isSequencedEvent(AWTEvent event);
}
/*
* Accessor instances are initialized in the static initializers of
* corresponding AWT classes by using setters defined below.
......@@ -692,6 +707,7 @@ public final class AWTAccessor {
private static SystemTrayAccessor systemTrayAccessor;
private static TrayIconAccessor trayIconAccessor;
private static DefaultKeyboardFocusManagerAccessor defaultKeyboardFocusManagerAccessor;
private static SequencedEventAccessor sequencedEventAccessor;
/*
* Set an accessor object for the java.awt.Component class.
......@@ -1069,4 +1085,20 @@ public final class AWTAccessor {
}
return defaultKeyboardFocusManagerAccessor;
}
/*
* Set an accessor object for the java.awt.SequencedEvent class.
*/
public static void setSequencedEventAccessor(SequencedEventAccessor sea) {
sequencedEventAccessor = sea;
}
/*
* Get the accessor object for the java.awt.SequencedEvent class.
*/
public static SequencedEventAccessor getSequencedEventAccessor() {
// The class is not public. So we can't ensure it's initialized.
// Null returned value means it's not initialized
// (so not a single instance of the event has been created).
return sequencedEventAccessor;
}
}
......@@ -44,6 +44,14 @@ import java.util.Properties;
public class HToolkit extends SunToolkit
implements ComponentFactory {
private static final KeyboardFocusManagerPeer kfmPeer = new KeyboardFocusManagerPeer() {
public void setCurrentFocusedWindow(Window win) {}
public Window getCurrentFocusedWindow() { return null; }
public void setCurrentFocusOwner(Component comp) {}
public Component getCurrentFocusOwner() { return null; }
public void clearGlobalFocusOwner(Window activeWindow) {}
};
public HToolkit() {
}
......@@ -152,15 +160,9 @@ public class HToolkit extends SunToolkit
throw new HeadlessException();
}
public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) {
public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
// See 6833019.
return
new KeyboardFocusManagerPeer() {
public Window getCurrentFocusedWindow() { return null; }
public void setCurrentFocusOwner(Component comp) {}
public Component getCurrentFocusOwner() { return null; }
public void clearGlobalFocusOwner(Window activeWindow) {}
};
return kfmPeer;
}
public TrayIconPeer createTrayIcon(TrayIcon target)
......
......@@ -30,22 +30,25 @@ import java.awt.dnd.*;
import java.awt.dnd.peer.DragSourceContextPeer;
import java.awt.event.*;
import java.awt.im.InputMethodHighlight;
import java.awt.im.spi.InputMethodDescriptor;
import java.awt.image.*;
import java.awt.datatransfer.Clipboard;
import java.awt.peer.*;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import sun.awt.im.InputContext;
import sun.awt.image.ImageRepresentation;
public class HeadlessToolkit extends Toolkit
implements ComponentFactory, KeyboardFocusManagerPeerProvider {
private static final KeyboardFocusManagerPeer kfmPeer = new KeyboardFocusManagerPeer() {
public void setCurrentFocusedWindow(Window win) {}
public Window getCurrentFocusedWindow() { return null; }
public void setCurrentFocusOwner(Component comp) {}
public Component getCurrentFocusOwner() { return null; }
public void clearGlobalFocusOwner(Window activeWindow) {}
};
private Toolkit tk;
private ComponentFactory componentFactory;
......@@ -179,15 +182,9 @@ public class HeadlessToolkit extends Toolkit
throw new HeadlessException();
}
public KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager) {
public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer() {
// See 6833019.
return
new KeyboardFocusManagerPeer() {
public Window getCurrentFocusedWindow() { return null; }
public void setCurrentFocusOwner(Component comp) {}
public Component getCurrentFocusOwner() { return null; }
public void clearGlobalFocusOwner(Window activeWindow) {}
};
return kfmPeer;
}
public TrayIconPeer createTrayIcon(TrayIcon target)
......
......@@ -53,12 +53,6 @@ public abstract class KeyboardFocusManagerPeerImpl implements KeyboardFocusManag
public static final int SNFH_SUCCESS_HANDLED = 1;
public static final int SNFH_SUCCESS_PROCEED = 2;
protected KeyboardFocusManager manager;
public KeyboardFocusManagerPeerImpl(KeyboardFocusManager manager) {
this.manager = manager;
}
@Override
public void clearGlobalFocusOwner(Window activeWindow) {
if (activeWindow != null) {
......@@ -134,7 +128,7 @@ public abstract class KeyboardFocusManagerPeerImpl implements KeyboardFocusManag
if (focusLog.isLoggable(PlatformLogger.FINER))
focusLog.finer("Posting focus event: " + fl);
SunToolkit.postPriorityEvent(fl);
SunToolkit.postEvent(SunToolkit.targetToAppContext(currentOwner), fl);
}
FocusEvent fg = new CausedFocusEvent(lightweightChild, FocusEvent.FOCUS_GAINED,
......@@ -142,7 +136,7 @@ public abstract class KeyboardFocusManagerPeerImpl implements KeyboardFocusManag
if (focusLog.isLoggable(PlatformLogger.FINER))
focusLog.finer("Posting focus event: " + fg);
SunToolkit.postPriorityEvent(fg);
SunToolkit.postEvent(SunToolkit.targetToAppContext(lightweightChild), fg);
return true;
}
......
......@@ -25,20 +25,19 @@
package sun.awt;
import java.awt.KeyboardFocusManager;
import java.awt.peer.KeyboardFocusManagerPeer;
/**
* {@link KeyboardFocusManagerPeerProvider} is required to be implemented by
* the currently used {@link java.awt.Toolkit} instance. In order to initialize
* {@link java.awt.KeyboardFocusManager}, an instance of {@link KeyboardFocusManagerPeer}
* is needed. To create that instance, the {@link #createKeyboardFocusManagerPeer}
* {@link java.awt.KeyboardFocusManager}, a singleton instance of {@link KeyboardFocusManagerPeer}
* is needed. To obtain that instance, the {@link #getKeyboardFocusManagerPeer}
* method of the current toolkit is called.
*/
public interface KeyboardFocusManagerPeerProvider {
/**
* Creates a KeyboardFocusManagerPeer for the specified KeyboardFocusManager.
* Gets a singleton KeyboardFocusManagerPeer instance.
*/
KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager);
KeyboardFocusManagerPeer getKeyboardFocusManagerPeer();
}
......@@ -197,7 +197,7 @@ public abstract class SunToolkit extends Toolkit
public abstract RobotPeer createRobot(Robot target, GraphicsDevice screen)
throws AWTException;
public abstract KeyboardFocusManagerPeer createKeyboardFocusManagerPeer(KeyboardFocusManager manager)
public abstract KeyboardFocusManagerPeer getKeyboardFocusManagerPeer()
throws HeadlessException;
/**
......@@ -463,6 +463,19 @@ public abstract class SunToolkit extends Toolkit
if (event == null) {
throw new NullPointerException();
}
AWTAccessor.SequencedEventAccessor sea = AWTAccessor.getSequencedEventAccessor();
if (sea != null && sea.isSequencedEvent(event)) {
AWTEvent nested = sea.getNested(event);
if (nested.getID() == WindowEvent.WINDOW_LOST_FOCUS &&
nested instanceof TimedWindowEvent)
{
TimedWindowEvent twe = (TimedWindowEvent)nested;
((SunToolkit)Toolkit.getDefaultToolkit()).
setWindowDeactivationTime((Window)twe.getSource(), twe.getWhen());
}
}
// All events posted via this method are system-generated.
// Placing the following call here reduces considerably the
// number of places throughout the toolkit that would
......@@ -1863,6 +1876,28 @@ public abstract class SunToolkit extends Toolkit
return false;
}
private static final Object DEACTIVATION_TIMES_MAP_KEY = new Object();
public synchronized void setWindowDeactivationTime(Window w, long time) {
AppContext ctx = getAppContext(w);
WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
if (map == null) {
map = new WeakHashMap<Window, Long>();
ctx.put(DEACTIVATION_TIMES_MAP_KEY, map);
}
map.put(w, time);
}
public synchronized long getWindowDeactivationTime(Window w) {
AppContext ctx = getAppContext(w);
WeakHashMap<Window, Long> map = (WeakHashMap<Window, Long>)ctx.get(DEACTIVATION_TIMES_MAP_KEY);
if (map == null) {
return -1;
}
Long time = map.get(w);
return time == null ? -1 : time;
}
// Cosntant alpha
public boolean isWindowOpacitySupported() {
return false;
......
/*
* Copyright (c) 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 sun.awt;
import java.awt.event.WindowEvent;
import java.awt.Window;
public class TimedWindowEvent extends WindowEvent {
private long time;
public long getWhen() {
return time;
}
public TimedWindowEvent(Window source, int id, Window opposite, long time) {
super(source, id, opposite);
this.time = time;
}
public TimedWindowEvent(Window source, int id, Window opposite,
int oldState, int newState, long time)
{
super(source, id, opposite, oldState, newState);
this.time = time;
}
}
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 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
......@@ -51,33 +51,21 @@ import java.security.spec.*;
*/
public final class ECKeyFactory extends KeyFactorySpi {
// Used by translateKey() and the SunPKCS11 provider
public final static KeyFactory INSTANCE;
// Used by translateKey()
private static KeyFactory instance;
// Internal provider object we can obtain the KeyFactory and
// AlgorithmParameters from. Used by ECParameters and AlgorithmId.
// This can go away once we have EC always available in the SUN provider.
// Used by ECParameters and AlgorithmId.
public final static Provider ecInternalProvider;
static {
final Provider p = new Provider("SunEC-Internal", 1.0d, null) {
private static final long serialVersionUID = 970685700309471261L;
};
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
p.put("KeyFactory.EC", "sun.security.ec.ECKeyFactory");
p.put("AlgorithmParameters.EC", "sun.security.ec.ECParameters");
p.put("Alg.Alias.AlgorithmParameters.1.2.840.10045.2.1", "EC");
return null;
private static KeyFactory getInstance() {
if (instance == null) {
try {
instance = KeyFactory.getInstance("EC", "SunEC");
} catch (NoSuchProviderException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
});
try {
INSTANCE = KeyFactory.getInstance("EC", p);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
ecInternalProvider = p;
return instance;
}
public ECKeyFactory() {
......@@ -102,7 +90,12 @@ public final class ECKeyFactory extends KeyFactorySpi {
checkKey(ecKey);
return ecKey;
} else {
return (ECKey)INSTANCE.translateKey(key);
/*
* We don't call the engineTranslateKey method directly
* because KeyFactory.translateKey adds code to loop through
* all key factories.
*/
return (ECKey)getInstance().translateKey(key);
}
}
......
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 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
......@@ -276,8 +276,8 @@ public final class ECParameters extends AlgorithmParametersSpi {
static AlgorithmParameters getAlgorithmParameters(ECParameterSpec spec)
throws InvalidKeyException {
try {
AlgorithmParameters params = AlgorithmParameters.getInstance
("EC", ECKeyFactory.ecInternalProvider);
AlgorithmParameters params =
AlgorithmParameters.getInstance("EC", "SunEC");
params.init(spec);
return params;
} catch (GeneralSecurityException e) {
......
......@@ -96,8 +96,13 @@ public final class ECPublicKeyImpl extends X509Key implements ECPublicKey {
*/
@SuppressWarnings("deprecation")
protected void parseKeyBits() throws InvalidKeyException {
AlgorithmParameters algParams = this.algid.getParameters();
if (algParams == null) {
throw new InvalidKeyException("EC domain parameters must be " +
"encoded in the algorithm identifier");
}
try {
AlgorithmParameters algParams = this.algid.getParameters();
params = algParams.getParameterSpec(ECParameterSpec.class);
w = ECParameters.decodePoint(key, params.getCurve());
} catch (IOException e) {
......
......@@ -54,6 +54,7 @@ final class SunECEntries {
*/
map.put("AlgorithmParameters.EC", "sun.security.ec.ECParameters");
map.put("Alg.Alias.AlgorithmParameters.EllipticCurve", "EC");
map.put("Alg.Alias.AlgorithmParameters.1.2.840.10045.2.1", "EC");
map.put("AlgorithmParameters.EC KeySize", "256");
......@@ -133,6 +134,9 @@ final class SunECEntries {
"sun.security.ec.ECDSASignature$Raw");
map.put("Signature.SHA1withECDSA",
"sun.security.ec.ECDSASignature$SHA1");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.1", "SHA1withECDSA");
map.put("Alg.Alias.Signature.1.2.840.10045.4.1", "SHA1withECDSA");
map.put("Signature.SHA224withECDSA",
"sun.security.ec.ECDSASignature$SHA224");
map.put("Alg.Alias.Signature.OID.1.2.840.10045.4.3.1", "SHA224withECDSA");
......
......@@ -115,7 +115,12 @@ public class Config {
private static boolean isMacosLionOrBetter() {
// split the "10.x.y" version number
String osVersion = System.getProperty("os.version");
String osname = getProperty("os.name");
if (!osname.contains("OS X")) {
return false;
}
String osVersion = getProperty("os.version");
String[] fragments = osVersion.split("\\.");
// sanity check the "10." part of the version
......@@ -140,20 +145,14 @@ public class Config {
/*
* If either one system property is specified, we throw exception.
*/
String tmp =
java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction
("java.security.krb5.kdc"));
String tmp = getProperty("java.security.krb5.kdc");
if (tmp != null) {
// The user can specify a list of kdc hosts separated by ":"
defaultKDC = tmp.replace(':', ' ');
} else {
defaultKDC = null;
}
defaultRealm =
java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction
("java.security.krb5.realm"));
defaultRealm = getProperty("java.security.krb5.realm");
if ((defaultKDC == null && defaultRealm != null) ||
(defaultRealm == null && defaultKDC != null)) {
throw new KrbException
......@@ -165,11 +164,34 @@ public class Config {
// Always read the Kerberos configuration file
try {
Vector<String> configFile;
configFile = loadConfigFile();
if (configFile == null && isMacosLionOrBetter()) {
stanzaTable = SCDynamicStoreConfig.getConfig();
} else {
String fileName = getJavaFileName();
if (fileName != null) {
configFile = loadConfigFile(fileName);
stanzaTable = parseStanzaTable(configFile);
if (DEBUG) {
System.out.println("Loaded from Java config");
}
} else {
boolean found = false;
if (isMacosLionOrBetter()) {
try {
stanzaTable = SCDynamicStoreConfig.getConfig();
if (DEBUG) {
System.out.println("Loaded from SCDynamicStoreConfig");
}
found = true;
} catch (IOException ioe) {
// OK. Will go on with file
}
}
if (!found) {
fileName = getNativeFileName();
configFile = loadConfigFile(fileName);
stanzaTable = parseStanzaTable(configFile);
if (DEBUG) {
System.out.println("Loaded from native config");
}
}
}
} catch (IOException ioe) {
// No krb5.conf, no problem. We'll use DNS or system property etc.
......@@ -546,10 +568,13 @@ public class Config {
* [domain_realm]
* blue.sample.com = TEST.SAMPLE.COM
* .backup.com = EXAMPLE.COM
*
* @params fileName the conf file, cannot be null
* @return the content, null if fileName is empty
* @throws IOException if there is an I/O or format error
*/
private Vector<String> loadConfigFile() throws IOException {
private Vector<String> loadConfigFile(final String fileName) throws IOException {
try {
final String fileName = getFileName();
if (!fileName.equals("")) {
BufferedReader br = new BufferedReader(new InputStreamReader(
java.security.AccessController.doPrivileged(
......@@ -668,97 +693,106 @@ public class Config {
}
/**
* Gets the default configuration file name. This method will never
* return null.
* Gets the default Java configuration file name.
*
* If the system property "java.security.krb5.conf" is defined, we'll
* use its value, no matter if the file exists or not. Otherwise,
* the file will be searched in a list of possible loations in the
* following order:
* use its value, no matter if the file exists or not. Otherwise, we
* will look at $JAVA_HOME/lib/security directory with "krb5.conf" name,
* and return it if the file exists.
*
* The method returns null if it cannot find a Java config file.
*/
private String getJavaFileName() {
String name = getProperty("java.security.krb5.conf");
if (name == null) {
name = getProperty("java.home") + File.separator +
"lib" + File.separator + "security" +
File.separator + "krb5.conf";
if (!fileExists(name)) {
name = null;
}
}
if (DEBUG) {
System.out.println("Java config name: " + name);
}
return name;
}
/**
* Gets the default native configuration file name.
*
* 1. at Java home lib\security directory with "krb5.conf" name,
* 2. at windows directory with the name of "krb5.ini" for Windows,
* /etc/krb5/krb5.conf for Solaris, /etc/krb5.conf otherwise.
* Depending on the OS type, the method returns the default native
* kerberos config file name, which is at windows directory with
* the name of "krb5.ini" for Windows, /etc/krb5/krb5.conf for Solaris,
* /etc/krb5.conf otherwise. Mac OSX X has a different file name.
*
* Note: When the Terminal Service is started in Windows (from 2003),
* there are two kinds of Windows directories: A system one (say,
* C:\Windows), and a user-private one (say, C:\Users\Me\Windows).
* We will first look for krb5.ini in the user-private one. If not
* found, try the system one instead.
*
* This method will always return a non-null non-empty file name,
* even if that file does not exist.
*/
private String getFileName() {
String name =
java.security.AccessController.doPrivileged(
new sun.security.action.
GetPropertyAction("java.security.krb5.conf"));
if (name == null) {
name = java.security.AccessController.doPrivileged(
new sun.security.action.
GetPropertyAction("java.home")) + File.separator +
"lib" + File.separator + "security" +
File.separator + "krb5.conf";
if (!fileExists(name)) {
name = null;
String osname =
java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("os.name"));
if (osname.startsWith("Windows")) {
try {
Credentials.ensureLoaded();
} catch (Exception e) {
// ignore exceptions
private String getNativeFileName() {
String name = null;
String osname = getProperty("os.name");
if (osname.startsWith("Windows")) {
try {
Credentials.ensureLoaded();
} catch (Exception e) {
// ignore exceptions
}
if (Credentials.alreadyLoaded) {
String path = getWindowsDirectory(false);
if (path != null) {
if (path.endsWith("\\")) {
path = path + "krb5.ini";
} else {
path = path + "\\krb5.ini";
}
if (Credentials.alreadyLoaded) {
String path = getWindowsDirectory(false);
if (path != null) {
if (path.endsWith("\\")) {
path = path + "krb5.ini";
} else {
path = path + "\\krb5.ini";
}
if (fileExists(path)) {
name = path;
}
}
if (name == null) {
path = getWindowsDirectory(true);
if (path != null) {
if (path.endsWith("\\")) {
path = path + "krb5.ini";
} else {
path = path + "\\krb5.ini";
}
name = path;
}
}
if (fileExists(path)) {
name = path;
}
if (name == null) {
name = "c:\\winnt\\krb5.ini";
}
if (name == null) {
path = getWindowsDirectory(true);
if (path != null) {
if (path.endsWith("\\")) {
path = path + "krb5.ini";
} else {
path = path + "\\krb5.ini";
}
name = path;
}
} else if (osname.startsWith("SunOS")) {
name = "/etc/krb5/krb5.conf";
} else if (osname.contains("OS X")) {
if (isMacosLionOrBetter()) return "";
name = findMacosConfigFile();
} else {
name = "/etc/krb5.conf";
}
}
if (name == null) {
name = "c:\\winnt\\krb5.ini";
}
} else if (osname.startsWith("SunOS")) {
name = "/etc/krb5/krb5.conf";
} else if (osname.contains("OS X")) {
name = findMacosConfigFile();
} else {
name = "/etc/krb5.conf";
}
if (DEBUG) {
System.out.println("Config name: " + name);
System.out.println("Native config name: " + name);
}
return name;
}
private String getProperty(String property) {
return java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction(property));
private static String getProperty(String property) {
return java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(property));
}
private String findMacosConfigFile() {
String userHome = getProperty("user.home");
final String PREF_FILE = "/Library/Preferences/edu.mit.Kerberos";
String userPrefs=userHome + PREF_FILE;
String userPrefs = userHome + PREF_FILE;
if (fileExists(userPrefs)) {
return userPrefs;
......@@ -768,11 +802,7 @@ public class Config {
return PREF_FILE;
}
if (fileExists("/etc/krb5.conf")) {
return "/etc/krb5.conf";
}
return "";
return "/etc/krb5.conf";
}
private static String trimmed(String s) {
......@@ -1344,32 +1374,52 @@ public class Config {
}
}
// Shows the content of the Config object for debug purpose.
//
// {
// libdefaults = {
// default_realm = R
// }
// realms = {
// R = {
// kdc = [k1,k2]
// }
// }
// }
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
toStringIndented("", stanzaTable, sb);
toStringInternal("", stanzaTable, sb);
return sb.toString();
}
private static void toStringIndented(String prefix, Object obj,
private static void toStringInternal(String prefix, Object obj,
StringBuffer sb) {
if (obj instanceof String) {
sb.append(prefix);
sb.append(obj);
sb.append('\n');
// A string value, just print it
sb.append(obj).append('\n');
} else if (obj instanceof Hashtable) {
// A table, start a new sub-section...
Hashtable<?, ?> tab = (Hashtable<?, ?>)obj;
sb.append("{\n");
for (Object o: tab.keySet()) {
sb.append(prefix);
sb.append(o);
sb.append(" = {\n");
toStringIndented(prefix + " ", tab.get(o), sb);
sb.append(prefix + "}\n");
// ...indent, print "key = ", and
sb.append(prefix).append(" ").append(o).append(" = ");
// ...go recursively into value
toStringInternal(prefix + " ", tab.get(o), sb);
}
sb.append(prefix).append("}\n");
} else if (obj instanceof Vector) {
// A vector of strings, print them inside [ and ]
Vector<?> v = (Vector<?>)obj;
sb.append("[");
boolean first = true;
for (Object o: v.toArray()) {
toStringIndented(prefix + " ", o, sb);
if (!first) sb.append(",");
sb.append(o);
first = false;
}
sb.append("]\n");
}
}
}
......@@ -164,6 +164,10 @@ final class P11Cipher extends CipherSpi {
// if we do the padding
private int bytesBuffered;
// length of key size in bytes; currently only used by AES given its oid
// specification mandates a fixed size of the key
private int fixedKeySize = -1;
P11Cipher(Token token, String algorithm, long mechanism)
throws PKCS11Exception, NoSuchAlgorithmException {
super();
......@@ -172,19 +176,26 @@ final class P11Cipher extends CipherSpi {
this.mechanism = mechanism;
String algoParts[] = algorithm.split("/");
keyAlgorithm = algoParts[0];
if (keyAlgorithm.equals("AES")) {
if (algoParts[0].startsWith("AES")) {
blockSize = 16;
} else if (keyAlgorithm.equals("RC4") ||
keyAlgorithm.equals("ARCFOUR")) {
blockSize = 0;
} else { // DES, DESede, Blowfish
blockSize = 8;
}
this.blockMode =
int index = algoParts[0].indexOf('_');
if (index != -1) {
// should be well-formed since we specify what we support
fixedKeySize = Integer.parseInt(algoParts[0].substring(index+1))/8;
}
keyAlgorithm = "AES";
} else {
keyAlgorithm = algoParts[0];
if (keyAlgorithm.equals("RC4") ||
keyAlgorithm.equals("ARCFOUR")) {
blockSize = 0;
} else { // DES, DESede, Blowfish
blockSize = 8;
}
this.blockMode =
(algoParts.length > 1 ? parseMode(algoParts[1]) : MODE_ECB);
}
String defPadding = (blockSize == 0 ? "NoPadding" : "PKCS5Padding");
String paddingStr =
(algoParts.length > 2 ? algoParts[2] : defPadding);
......@@ -333,6 +344,9 @@ final class P11Cipher extends CipherSpi {
SecureRandom random)
throws InvalidKeyException, InvalidAlgorithmParameterException {
cancelOperation();
if (fixedKeySize != -1 && key.getEncoded().length != fixedKeySize) {
throw new InvalidKeyException("Key size is invalid");
}
switch (opmode) {
case Cipher.ENCRYPT_MODE:
encrypt = true;
......
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 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
......@@ -304,7 +304,7 @@ final class P11ECKeyFactory extends P11KeyFactory {
}
KeyFactory implGetSoftwareFactory() throws GeneralSecurityException {
return sun.security.ec.ECKeyFactory.INSTANCE;
return KeyFactory.getInstance("EC", "SunEC");
}
}
......@@ -399,12 +399,8 @@ public final class SunPKCS11 extends AuthProvider {
return System.identityHashCode(this);
}
private static String[] s(String s1) {
return new String[] {s1};
}
private static String[] s(String s1, String s2) {
return new String[] {s1, s2};
private static String[] s(String ...aliases) {
return aliases;
}
private static final class Descriptor {
......@@ -521,7 +517,8 @@ public final class SunPKCS11 extends AuthProvider {
m(CKM_MD2));
d(MD, "MD5", P11Digest,
m(CKM_MD5));
d(MD, "SHA1", P11Digest, s("SHA", "SHA-1"),
d(MD, "SHA1", P11Digest,
s("SHA", "SHA-1", "1.3.14.3.2.26", "OID.1.3.14.3.2.26"),
m(CKM_SHA_1));
d(MD, "SHA-224", P11Digest,
......@@ -540,6 +537,7 @@ public final class SunPKCS11 extends AuthProvider {
d(MAC, "HmacMD5", P11MAC,
m(CKM_MD5_HMAC));
d(MAC, "HmacSHA1", P11MAC,
s("1.2.840.113549.2.7", "OID.1.2.840.113549.2.7"),
m(CKM_SHA_1_HMAC));
d(MAC, "HmacSHA224", P11MAC,
s("1.2.840.113549.2.8", "OID.1.2.840.113549.2.8"),
......@@ -561,6 +559,7 @@ public final class SunPKCS11 extends AuthProvider {
d(KPG, "RSA", P11KeyPairGenerator,
m(CKM_RSA_PKCS_KEY_PAIR_GEN));
d(KPG, "DSA", P11KeyPairGenerator,
s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
m(CKM_DSA_KEY_PAIR_GEN));
d(KPG, "DH", P11KeyPairGenerator, s("DiffieHellman"),
m(CKM_DH_PKCS_KEY_PAIR_GEN));
......@@ -583,6 +582,7 @@ public final class SunPKCS11 extends AuthProvider {
d(KF, "RSA", P11RSAKeyFactory,
m(CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509));
d(KF, "DSA", P11DSAKeyFactory,
s("1.3.14.3.2.12", "1.2.840.10040.4.1", "OID.1.2.840.10040.4.1"),
m(CKM_DSA_KEY_PAIR_GEN, CKM_DSA, CKM_DSA_SHA1));
d(KF, "DH", P11DHKeyFactory, s("DiffieHellman"),
m(CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_DERIVE));
......@@ -609,6 +609,7 @@ public final class SunPKCS11 extends AuthProvider {
d(SKF, "DESede", P11SecretKeyFactory,
m(CKM_DES3_CBC));
d(SKF, "AES", P11SecretKeyFactory,
s("2.16.840.1.101.3.4.1", "OID.2.16.840.1.101.3.4.1"),
m(CKM_AES_CBC));
d(SKF, "Blowfish", P11SecretKeyFactory,
m(CKM_BLOWFISH_CBC));
......@@ -635,10 +636,28 @@ public final class SunPKCS11 extends AuthProvider {
m(CKM_DES3_ECB));
d(CIP, "AES/CBC/NoPadding", P11Cipher,
m(CKM_AES_CBC));
d(CIP, "AES_128/CBC/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.2", "OID.2.16.840.1.101.3.4.1.2"),
m(CKM_AES_CBC));
d(CIP, "AES_192/CBC/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.22", "OID.2.16.840.1.101.3.4.1.22"),
m(CKM_AES_CBC));
d(CIP, "AES_256/CBC/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.42", "OID.2.16.840.1.101.3.4.1.42"),
m(CKM_AES_CBC));
d(CIP, "AES/CBC/PKCS5Padding", P11Cipher,
m(CKM_AES_CBC_PAD, CKM_AES_CBC));
d(CIP, "AES/ECB/NoPadding", P11Cipher,
m(CKM_AES_ECB));
d(CIP, "AES_128/ECB/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.1", "OID.2.16.840.1.101.3.4.1.1"),
m(CKM_AES_ECB));
d(CIP, "AES_192/ECB/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.21", "OID.2.16.840.1.101.3.4.1.21"),
m(CKM_AES_ECB));
d(CIP, "AES_256/ECB/NoPadding", P11Cipher,
s("2.16.840.1.101.3.4.1.41", "OID.2.16.840.1.101.3.4.1.41"),
m(CKM_AES_ECB));
d(CIP, "AES/ECB/PKCS5Padding", P11Cipher, s("AES"),
m(CKM_AES_ECB));
d(CIP, "AES/CTR/NoPadding", P11Cipher,
......@@ -654,13 +673,16 @@ public final class SunPKCS11 extends AuthProvider {
d(CIP, "RSA/ECB/NoPadding", P11RSACipher,
m(CKM_RSA_X_509));
d(SIG, "RawDSA", P11Signature, s("NONEwithDSA"),
d(SIG, "RawDSA", P11Signature, s("NONEwithDSA"),
m(CKM_DSA));
d(SIG, "DSA", P11Signature, s("SHA1withDSA"),
d(SIG, "DSA", P11Signature,
s("SHA1withDSA", "1.3.14.3.2.13", "1.3.14.3.2.27",
"1.2.840.10040.4.3", "OID.1.2.840.10040.4.3"),
m(CKM_DSA_SHA1, CKM_DSA));
d(SIG, "NONEwithECDSA", P11Signature,
m(CKM_ECDSA));
d(SIG, "SHA1withECDSA", P11Signature, s("ECDSA"),
d(SIG, "SHA1withECDSA", P11Signature,
s("ECDSA", "1.2.840.10045.4.1", "OID.1.2.840.10045.4.1"),
m(CKM_ECDSA_SHA1, CKM_ECDSA));
d(SIG, "SHA224withECDSA", P11Signature,
s("1.2.840.10045.4.3.1", "OID.1.2.840.10045.4.3.1"),
......@@ -675,10 +697,14 @@ public final class SunPKCS11 extends AuthProvider {
s("1.2.840.10045.4.3.4", "OID.1.2.840.10045.4.3.4"),
m(CKM_ECDSA));
d(SIG, "MD2withRSA", P11Signature,
s("1.2.840.113549.1.1.2", "OID.1.2.840.113549.1.1.2"),
m(CKM_MD2_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
d(SIG, "MD5withRSA", P11Signature,
s("1.2.840.113549.1.1.4", "OID.1.2.840.113549.1.1.4"),
m(CKM_MD5_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
d(SIG, "SHA1withRSA", P11Signature,
s("1.2.840.113549.1.1.5", "OID.1.2.840.113549.1.1.5",
"1.3.14.3.2.29"),
m(CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS, CKM_RSA_X_509));
d(SIG, "SHA224withRSA", P11Signature,
s("1.2.840.113549.1.1.14", "OID.1.2.840.113549.1.1.14"),
......
/*
* Copyright (c) 1997, 2005, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
......@@ -48,8 +48,9 @@ import sun.security.jca.JCAUtil;
public class DSAKeyPairGenerator extends KeyPairGenerator
implements java.security.interfaces.DSAKeyPairGenerator {
/* The modulus length */
private int modlen;
/* Length for prime P and subPrime Q in bits */
private int plen;
private int qlen;
/* whether to force new parameters to be generated for each KeyPair */
private boolean forceNewParameters;
......@@ -65,20 +66,23 @@ implements java.security.interfaces.DSAKeyPairGenerator {
initialize(1024, null);
}
private static void checkStrength(int strength) {
if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
private static void checkStrength(int sizeP, int sizeQ) {
if ((sizeP >= 512) && (sizeP <= 1024) && (sizeP % 64 == 0)
&& sizeQ == 160) {
// traditional - allow for backward compatibility
// L=multiples of 64 and between 512 and 1024 (inclusive)
// N=160
} else if (sizeP == 2048 && (sizeQ == 224 || sizeQ == 256)) {
// L=2048, N=224 or 256
} else {
throw new InvalidParameterException
("Modulus size must range from 512 to 1024 "
+ "and be a multiple of 64");
("Unsupported prime and subprime size combination: " +
sizeP + ", " + sizeQ);
}
}
public void initialize(int modlen, SecureRandom random) {
checkStrength(modlen);
this.random = random;
this.modlen = modlen;
this.params = null;
this.forceNewParameters = false;
initialize(modlen, false, random);
}
/**
......@@ -86,18 +90,27 @@ implements java.security.interfaces.DSAKeyPairGenerator {
* is false, a set of pre-computed parameters is used.
*/
public void initialize(int modlen, boolean genParams, SecureRandom random) {
checkStrength(modlen);
int subPrimeLen = -1;
if (modlen <= 1024) {
subPrimeLen = 160;
} else if (modlen == 2048) {
subPrimeLen = 224;
}
checkStrength(modlen, subPrimeLen);
if (genParams) {
params = null;
} else {
params = ParameterCache.getCachedDSAParameterSpec(modlen);
params = ParameterCache.getCachedDSAParameterSpec(modlen,
subPrimeLen);
if (params == null) {
throw new InvalidParameterException
("No precomputed parameters for requested modulus size "
+ "available");
}
}
this.modlen = modlen;
this.plen = modlen;
this.qlen = subPrimeLen;
this.random = random;
this.forceNewParameters = genParams;
}
......@@ -136,9 +149,11 @@ implements java.security.interfaces.DSAKeyPairGenerator {
}
private void initialize0(DSAParameterSpec params, SecureRandom random) {
int modlen = params.getP().bitLength();
checkStrength(modlen);
this.modlen = modlen;
int sizeP = params.getP().bitLength();
int sizeQ = params.getQ().bitLength();
checkStrength(sizeP, sizeQ);
this.plen = sizeP;
this.qlen = sizeQ;
this.params = params;
this.random = random;
this.forceNewParameters = false;
......@@ -156,11 +171,11 @@ implements java.security.interfaces.DSAKeyPairGenerator {
try {
if (forceNewParameters) {
// generate new parameters each time
spec = ParameterCache.getNewDSAParameterSpec(modlen, random);
spec = ParameterCache.getNewDSAParameterSpec(plen, qlen, random);
} else {
if (params == null) {
params =
ParameterCache.getDSAParameterSpec(modlen, random);
ParameterCache.getDSAParameterSpec(plen, qlen, random);
}
spec = params;
}
......@@ -203,43 +218,14 @@ implements java.security.interfaces.DSAKeyPairGenerator {
*/
private BigInteger generateX(SecureRandom random, BigInteger q) {
BigInteger x = null;
byte[] temp = new byte[qlen];
while (true) {
int[] seed = new int[5];
for (int i = 0; i < 5; i++) {
seed[i] = random.nextInt();
}
x = generateX(seed, q);
random.nextBytes(temp);
x = new BigInteger(1, temp).mod(q);
if (x.signum() > 0 && (x.compareTo(q) < 0)) {
break;
}
}
return x;
}
/**
* Given a seed, generate the private key component of the key
* pair. In the terminology used in the DSA specification
* (FIPS-186) seed is the XSEED quantity.
*
* @param seed the seed to use to generate the private key.
*/
BigInteger generateX(int[] seed, BigInteger q) {
// check out t in the spec.
int[] t = { 0x67452301, 0xEFCDAB89, 0x98BADCFE,
0x10325476, 0xC3D2E1F0 };
//
int[] tmp = DSA.SHA_7(seed, t);
byte[] tmpBytes = new byte[tmp.length * 4];
for (int i = 0; i < tmp.length; i++) {
int k = tmp[i];
for (int j = 0; j < 4; j++) {
tmpBytes[(i * 4) + j] = (byte) (k >>> (24 - (j * 8)));
return x;
}
}
BigInteger x = new BigInteger(1, tmpBytes).mod(q);
return x;
}
/**
......
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 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
......@@ -32,10 +32,12 @@ import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.DSAParameterSpec;
import java.security.spec.DSAGenParameterSpec;
/**
* This class generates parameters for the DSA algorithm. It uses a default
......@@ -54,8 +56,14 @@ import java.security.spec.DSAParameterSpec;
public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
// the modulus length
private int modLen = 1024; // default
// the default parameters
private static final DSAGenParameterSpec DEFAULTS =
new DSAGenParameterSpec(1024, 160, 160);
// the length of prime P, subPrime Q, and seed in bits
private int valueL = -1;
private int valueN = -1;
private int seedLen = -1;
// the source of randomness
private SecureRandom random;
......@@ -65,11 +73,7 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
private static final BigInteger ONE = BigInteger.valueOf(1);
private static final BigInteger TWO = BigInteger.valueOf(2);
// Make a SHA-1 hash function
private SHA sha;
public DSAParameterGenerator() {
this.sha = new SHA();
}
/**
......@@ -80,19 +84,18 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
* @param random the source of randomness
*/
protected void engineInit(int strength, SecureRandom random) {
/*
* Bruce Schneier, "Applied Cryptography", 2nd Edition,
* Description of DSA:
* [...] The algorithm uses the following parameter:
* p=a prime number L bits long, when L ranges from 512 to 1024 and is
* a multiple of 64. [...]
*/
if ((strength < 512) || (strength > 1024) || (strength % 64 != 0)) {
if ((strength >= 512) && (strength <= 1024) && (strength % 64 == 0)) {
this.valueN = 160;
} else if (strength == 2048) {
this.valueN = 224;
// } else if (strength == 3072) {
// this.valueN = 256;
} else {
throw new InvalidParameterException
("Prime size must range from 512 to 1024 "
+ "and be a multiple of 64");
("Prime size should be 512 - 1024, or 2048");
}
this.modLen = strength;
this.valueL = strength;
this.seedLen = valueN;
this.random = random;
}
......@@ -100,7 +103,7 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
* Initializes this parameter generator with a set of
* algorithm-specific parameter generation values.
*
* @param params the set of algorithm-specific parameter generation values
* @param genParamSpec the set of algorithm-specific parameter generation values
* @param random the source of randomness
*
* @exception InvalidAlgorithmParameterException if the given parameter
......@@ -109,7 +112,19 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
protected void engineInit(AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException {
if (!(genParamSpec instanceof DSAGenParameterSpec)) {
throw new InvalidAlgorithmParameterException("Invalid parameter");
}
DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec) genParamSpec;
if (dsaGenParams.getPrimePLength() > 2048) {
throw new InvalidParameterException
("Prime size should be 512 - 1024, or 2048");
}
// directly initialize using the already validated values
this.valueL = dsaGenParams.getPrimePLength();
this.valueN = dsaGenParams.getSubprimeQLength();
this.seedLen = dsaGenParams.getSeedLength();
this.random = random;
}
/**
......@@ -123,15 +138,21 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
if (this.random == null) {
this.random = new SecureRandom();
}
BigInteger[] pAndQ = generatePandQ(this.random, this.modLen);
if (valueL == -1) {
try {
engineInit(DEFAULTS, this.random);
} catch (InvalidAlgorithmParameterException iape) {
// should never happen
}
}
BigInteger[] pAndQ = generatePandQ(this.random, valueL,
valueN, seedLen);
BigInteger paramP = pAndQ[0];
BigInteger paramQ = pAndQ[1];
BigInteger paramG = generateG(paramP, paramQ);
DSAParameterSpec dsaParamSpec = new DSAParameterSpec(paramP,
paramQ,
paramG);
DSAParameterSpec dsaParamSpec =
new DSAParameterSpec(paramP, paramQ, paramG);
algParams = AlgorithmParameters.getInstance("DSA", "SUN");
algParams.init(dsaParamSpec);
} catch (InvalidParameterSpecException e) {
......@@ -156,102 +177,98 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
*
* @param random the source of randomness to generate the
* seed
* @param L the size of <code>p</code>, in bits.
* @param valueL the size of <code>p</code>, in bits.
* @param valueN the size of <code>q</code>, in bits.
* @param seedLen the length of <code>seed</code>, in bits.
*
* @return an array of BigInteger, with <code>p</code> at index 0 and
* <code>q</code> at index 1.
*/
BigInteger[] generatePandQ(SecureRandom random, int L) {
BigInteger[] result = null;
byte[] seed = new byte[20];
while(result == null) {
for (int i = 0; i < 20; i++) {
seed[i] = (byte)random.nextInt();
}
result = generatePandQ(seed, L);
}
return result;
}
/*
* Generates the prime and subprime parameters for DSA.
*
* <p>The seed parameter corresponds to the <code>SEED</code> parameter
* referenced in the FIPS specification of the DSA algorithm,
* and L is the size of <code>p</code>, in bits.
*
* @param seed the seed to generate the parameters
* @param L the size of <code>p</code>, in bits.
*
* @return an array of BigInteger, with <code>p</code> at index 0,
* <code>q</code> at index 1, the seed at index 2, and the counter value
* at index 3, or null if the seed does not yield suitable numbers.
* at index 3.
*/
BigInteger[] generatePandQ(byte[] seed, int L) {
/* Useful variables */
int g = seed.length * 8;
int n = (L - 1) / 160;
int b = (L - 1) % 160;
BigInteger SEED = new BigInteger(1, seed);
BigInteger TWOG = TWO.pow(2 * g);
/* Step 2 (Step 1 is getting seed). */
byte[] U1 = SHA(seed);
byte[] U2 = SHA(toByteArray((SEED.add(ONE)).mod(TWOG)));
xor(U1, U2);
byte[] U = U1;
/* Step 3: For q by setting the msb and lsb to 1 */
U[0] |= 0x80;
U[19] |= 1;
BigInteger q = new BigInteger(1, U);
/* Step 5 */
if (!q.isProbablePrime(80)) {
return null;
} else {
BigInteger V[] = new BigInteger[n + 1];
BigInteger offset = TWO;
/* Step 6 */
for (int counter = 0; counter < 4096; counter++) {
/* Step 7 */
for (int k = 0; k <= n; k++) {
BigInteger K = BigInteger.valueOf(k);
BigInteger tmp = (SEED.add(offset).add(K)).mod(TWOG);
V[k] = new BigInteger(1, SHA(toByteArray(tmp)));
}
/* Step 8 */
BigInteger W = V[0];
for (int i = 1; i < n; i++) {
W = W.add(V[i].multiply(TWO.pow(i * 160)));
}
W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * 160)));
BigInteger TWOLm1 = TWO.pow(L - 1);
BigInteger X = W.add(TWOLm1);
private static BigInteger[] generatePandQ(SecureRandom random, int valueL,
int valueN, int seedLen) {
String hashAlg = null;
if (valueN == 160) {
hashAlg = "SHA";
} else if (valueN == 224) {
hashAlg = "SHA-224";
} else if (valueN == 256) {
hashAlg = "SHA-256";
}
MessageDigest hashObj = null;
try {
hashObj = MessageDigest.getInstance(hashAlg);
} catch (NoSuchAlgorithmException nsae) {
// should never happen
nsae.printStackTrace();
}
/* Step 9 */
BigInteger c = X.mod(q.multiply(TWO));
BigInteger p = X.subtract(c.subtract(ONE));
/* Step 3, 4: Useful variables */
int outLen = hashObj.getDigestLength()*8;
int n = (valueL - 1) / outLen;
int b = (valueL - 1) % outLen;
byte[] seedBytes = new byte[seedLen/8];
BigInteger twoSl = TWO.pow(seedLen);
int primeCertainty = 80; // for 1024-bit prime P
if (valueL == 2048) {
primeCertainty = 112;
//} else if (valueL == 3072) {
// primeCertainty = 128;
}
/* Step 10 - 13 */
if (p.compareTo(TWOLm1) > -1 && p.isProbablePrime(80)) {
BigInteger[] result = {p, q, SEED,
BigInteger.valueOf(counter)};
return result;
}
offset = offset.add(BigInteger.valueOf(n)).add(ONE);
BigInteger resultP, resultQ, seed = null;
int counter;
while (true) {
do {
/* Step 5 */
random.nextBytes(seedBytes);
seed = new BigInteger(1, seedBytes);
/* Step 6 */
BigInteger U = new BigInteger(1, hashObj.digest(seedBytes)).
mod(TWO.pow(valueN - 1));
/* Step 7 */
resultQ = TWO.pow(valueN - 1).add(U).add(ONE). subtract(U.mod(TWO));
} while (!resultQ.isProbablePrime(primeCertainty));
/* Step 10 */
BigInteger offset = ONE;
/* Step 11 */
for (counter = 0; counter < 4*valueL; counter++) {
BigInteger V[] = new BigInteger[n + 1];
/* Step 11.1 */
for (int j = 0; j <= n; j++) {
BigInteger J = BigInteger.valueOf(j);
BigInteger tmp = (seed.add(offset).add(J)).mod(twoSl);
byte[] vjBytes = hashObj.digest(toByteArray(tmp));
V[j] = new BigInteger(1, vjBytes);
}
/* Step 11.2 */
BigInteger W = V[0];
for (int i = 1; i < n; i++) {
W = W.add(V[i].multiply(TWO.pow(i * outLen)));
}
W = W.add((V[n].mod(TWO.pow(b))).multiply(TWO.pow(n * outLen)));
/* Step 11.3 */
BigInteger twoLm1 = TWO.pow(valueL - 1);
BigInteger X = W.add(twoLm1);
/* Step 11.4, 11.5 */
BigInteger c = X.mod(resultQ.multiply(TWO));
resultP = X.subtract(c.subtract(ONE));
/* Step 11.6, 11.7 */
if (resultP.compareTo(twoLm1) > -1
&& resultP.isProbablePrime(primeCertainty)) {
/* Step 11.8 */
BigInteger[] result = {resultP, resultQ, seed,
BigInteger.valueOf(counter)};
return result;
}
/* Step 11.9 */
offset = offset.add(BigInteger.valueOf(n)).add(ONE);
}
return null;
}
}
}
/*
......@@ -262,31 +279,24 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
*
* @param the <code>g</code>
*/
BigInteger generateG(BigInteger p, BigInteger q) {
private static BigInteger generateG(BigInteger p, BigInteger q) {
BigInteger h = ONE;
/* Step 1 */
BigInteger pMinusOneOverQ = (p.subtract(ONE)).divide(q);
BigInteger g = ONE;
while (g.compareTo(TWO) < 0) {
g = h.modPow(pMinusOneOverQ, p);
BigInteger resultG = ONE;
while (resultG.compareTo(TWO) < 0) {
/* Step 3 */
resultG = h.modPow(pMinusOneOverQ, p);
h = h.add(ONE);
}
return g;
}
/*
* Returns the SHA-1 digest of some data
*/
private byte[] SHA(byte[] array) {
sha.engineReset();
sha.engineUpdate(array, 0, array.length);
return sha.engineDigest();
return resultG;
}
/*
* Converts the result of a BigInteger.toByteArray call to an exact
* signed magnitude representation for any positive number.
*/
private byte[] toByteArray(BigInteger bigInt) {
private static byte[] toByteArray(BigInteger bigInt) {
byte[] result = bigInt.toByteArray();
if (result[0] == 0) {
byte[] tmp = new byte[result.length - 1];
......@@ -295,13 +305,4 @@ public class DSAParameterGenerator extends AlgorithmParameterGeneratorSpi {
}
return result;
}
/*
* XORs U2 into U1
*/
private void xor(byte[] U1, byte[] U2) {
for (int i = 0; i < U1.length; i++) {
U1[i] ^= U2[i];
}
}
}
......@@ -5,7 +5,7 @@
<body>
<h1>Card Test (1.1)</h1>
<hr>
<applet code=CardTest.class width=400 height=300>
<applet code=CardTest.class width=455 height=300>
alt="Your browser understands the &lt;APPLET&gt; tag but isn't running the applet, for some reason."
Your browser is completely ignoring the &lt;APPLET&gt; tag!
</applet>
......
......@@ -5,7 +5,7 @@
<body>
<h1>Dither Test (1.1)</h1>
<hr>
<applet code=DitherTest.class width=425 height=400>
<applet code=DitherTest.class width=455 height=400>
alt="Your browser understands the &lt;APPLET&gt; tag but isn't running the applet, for some reason."
Your browser is completely ignoring the &lt;APPLET&gt; tag!
</applet>
......
此差异已折叠。
......@@ -452,7 +452,12 @@ extern CK_C_INITIALIZE_ARGS_PTR ckpGlobalInitArgs;
void *p11malloc(size_t c, char *file, int line);
void p11free(void *p, char *file, int line);
#define malloc(c) (p11malloc((c), __FILE__, __LINE__))
#define free(c) (p11free((c), __FILE__, __LINE__))
/* Use THIS_FILE when it is available. */
#ifndef THIS_FILE
#define THIS_FILE __FILE__
#endif
#define malloc(c) (p11malloc((c), THIS_FILE, __LINE__))
#define free(c) (p11free((c), THIS_FILE, __LINE__))
#endif
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册