提交 f1d53517 编写于 作者: A asaha

Merge

......@@ -628,6 +628,10 @@ e915a408ebf7ba05b36d1b714e166a1d9e5c7edd jdk8u102-b11
901ecf04370c7c03c61e22ab87a266c355baff54 jdk8u102-b13
48c99b42383912886c005891c04b5f599adf6722 jdk8u102-b14
222d3ac3aa1f99f16e31c1c4a10f916ce83ff759 jdk8u102-b31
e3839fe291add6e0ea199457fb31c9312cc5dd77 jdk8u102-b32
275fcb7d4e3e70a37ac70c33d087a805ba182f1e jdk8u102-b33
d783f00bb04a6fff7ddf1555572c1f3cdfd21e59 jdk8u102-b34
958684c9f1e73d9310511559c770823180d33e4b jdk8u102-b35
ebc56c2e803597ef409a5296addc986b390d934d jdk8u111-b00
c4f03717831993e4658b8366810ca4682ece952d jdk8u111-b01
de1d09f09e571e38afdf1fb72984ec210e7c19e6 jdk8u111-b02
......@@ -659,6 +663,21 @@ c86d82567b1200bdb2d2a757f676179a637c4244 jdk8u112-b10
d2d8b67021a0f41e0eabd711bfd87a943dc0a8d5 jdk8u112-b14
60767ec3909b3d0cb26dd7b3f952c62053719dda jdk8u112-b15
5dd7e4bae5c2f1ee4f80c5570e7e3e2f715f7a32 jdk8u112-b16
41fac11792c1ee6945f56721ee558a7424395a81 jdk8u112-b31
ab5ff8f1e52c5e3ca02e988f4d978af63ceca5b8 jdk8u121-b00
5f0839ac7e0d25dd1ae705df496b12ca76c26d59 jdk8u121-b01
f91e3aa155b3c6774afb456db15fb358313d5771 jdk8u121-b02
ecdb635eaf4886829089b987c339e35dfb5ea0e8 jdk8u121-b03
d54219144844fb358f87f4a37255242aae9782fa jdk8u121-b04
fb4e3a7375c91e02bd1c0a764dfb53fba3839c18 jdk8u121-b05
3bc671481026decc460e636e8b2f19a36bfe89af jdk8u121-b06
a2c2fbc61674869e85d5345804cff4834cc010d1 jdk8u121-b07
392209fbe127896df2749344ea127f2c0a62da55 jdk8u121-b08
494d27357b8cfc6b6c4346a814c8717a8502d769 jdk8u121-b09
d66de7e2f672a1ff6947846818412fa899456972 jdk8u121-b10
ec72a941be0a50ab77f5375cf710bc06e4f118d3 jdk8u121-b11
9561afc12df843ef21ecd9d7b3633371e7a2bfc4 jdk8u121-b12
2974746e56192cdd14fc2dd43179bcf28e4faf4a jdk8u121-b13
1442bc728814af451e2dd1a6719a64485d27e3a0 jdk8u122-b00
f6030acfa5aec0e64d45adfac69b9e7e5c12bc74 jdk8u122-b01
6b072c3a6db7ab06804c91aab77431799dfb5d47 jdk8u122-b02
......
......@@ -121,7 +121,7 @@ class _AppMenuBarHandler {
}
// grab the pointer to the CMenuBar, and retain it in native
nativeSetDefaultMenuBar(((CMenuBar)peer).getModel());
((CMenuBar) peer).execute(_AppMenuBarHandler::nativeSetDefaultMenuBar);
}
void setAboutMenuItemVisible(final boolean present) {
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -26,29 +26,28 @@
package sun.lwawt.macosx;
import java.awt.CheckboxMenuItem;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.peer.CheckboxMenuItemPeer;
import sun.awt.SunToolkit;
public class CCheckboxMenuItem extends CMenuItem implements CheckboxMenuItemPeer {
boolean fAutoToggle = true;
boolean fIsIndeterminate = false;
volatile boolean fAutoToggle = true;
volatile boolean fIsIndeterminate = false;
private native void nativeSetState(long modelPtr, boolean state);
private native void nativeSetIsCheckbox(long modelPtr);
CCheckboxMenuItem(CheckboxMenuItem target) {
CCheckboxMenuItem(final CheckboxMenuItem target) {
super(target);
nativeSetIsCheckbox(getModel());
execute(this::nativeSetIsCheckbox);
setState(target.getState());
}
// MenuItemPeer implementation
@Override
public void setState(boolean state) {
nativeSetState(getModel(), state);
public void setState(final boolean state) {
execute(ptr -> nativeSetState(ptr, state));
}
public void handleAction(final boolean state) {
......
......@@ -23,7 +23,6 @@
* questions.
*/
package sun.lwawt.macosx;
/**
......@@ -34,6 +33,7 @@ public class CFRetainedResource {
private static native void nativeCFRelease(final long ptr, final boolean disposeOnAppKitThread);
private final boolean disposeOnAppKitThread;
// TODO this pointer should be private and accessed via CFNativeAction class
protected volatile long ptr;
/**
......@@ -70,8 +70,72 @@ public class CFRetainedResource {
nativeCFRelease(oldPtr, disposeOnAppKitThread); // perform outside of the synchronized block
}
/**
* The interface which allows to execute some native operations with
* assumption that the native pointer will be valid till the end.
*/
public interface CFNativeAction {
/**
* The native operation should be called from this method.
*
* @param ptr the pointer to the native data
*/
void run(long ptr);
}
/**
* The interface which allows to execute some native operations and get a
* result with assumption that the native pointer will be valid till the
* end.
*/
interface CFNativeActionGet {
/**
* The native operation should be called from this method.
*
* @param ptr the pointer to the native data
* @return result of the native operation
*/
long run(long ptr);
}
/**
* This is utility method which should be used instead of the direct access
* to the {@link #ptr}, because this method guaranteed that the pointer will
* not be zero and will be valid till the end of the operation.It is highly
* recomended to not use any external lock in action. If the current
* {@link #ptr} is {@code 0} then action will be ignored.
*
* @param action The native operation
*/
public final synchronized void execute(final CFNativeAction action) {
if (ptr != 0) {
action.run(ptr);
}
}
/**
* This is utility method which should be used instead of the direct access
* to the {@link #ptr}, because this method guaranteed that the pointer will
* not be zero and will be valid till the end of the operation. It is highly
* recomended to not use any external lock in action. If the current
* {@link #ptr} is {@code 0} then action will be ignored and {@code} is
* returned.
*
* @param action the native operation
* @return result of the native operation, usually the native pointer to
* some other data
*/
final synchronized long executeGet(final CFNativeActionGet action) {
if (ptr != 0) {
return action.run(ptr);
}
return 0;
}
@Override
protected void finalize() throws Throwable {
protected final void finalize() throws Throwable {
dispose();
}
}
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -25,7 +25,9 @@
package sun.lwawt.macosx;
import java.awt.*;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.peer.MenuItemPeer;
import java.awt.peer.MenuPeer;
......@@ -37,7 +39,7 @@ public class CMenu extends CMenuItem implements MenuPeer {
// This way we avoiding invocation of the setters twice
@Override
protected void initialize(MenuItem target) {
protected final void initialize(MenuItem target) {
setLabel(target.getLabel());
setEnabled(target.isEnabled());
}
......@@ -57,52 +59,50 @@ public class CMenu extends CMenuItem implements MenuPeer {
}
@Override
protected long createModel() {
long createModel() {
CMenuComponent parent = (CMenuComponent)
LWCToolkit.targetToPeer(getTarget().getParent());
if (parent instanceof CMenu ||
parent instanceof CPopupMenu)
{
return nativeCreateSubMenu(parent.getModel());
} else if (parent instanceof CMenuBar) {
if (parent instanceof CMenu) {
return parent.executeGet(this::nativeCreateSubMenu);
}
if (parent instanceof CMenuBar) {
MenuBar parentContainer = (MenuBar)getTarget().getParent();
boolean isHelpMenu = parentContainer.getHelpMenu() == getTarget();
int insertionLocation = ((CMenuBar)parent).getNextInsertionIndex();
return nativeCreateMenu(parent.getModel(),
isHelpMenu, insertionLocation);
} else {
throw new InternalError("Parent must be CMenu or CMenuBar");
return parent.executeGet(ptr -> nativeCreateMenu(ptr, isHelpMenu,
insertionLocation));
}
throw new InternalError("Parent must be CMenu or CMenuBar");
}
@Override
public void addItem(MenuItem item) {
public final void addItem(MenuItem item) {
// Nothing to do here -- we added it when we created the
// menu item's peer.
}
@Override
public void delItem(int index) {
nativeDeleteItem(getModel(), index);
public final void delItem(final int index) {
execute(ptr -> nativeDeleteItem(ptr, index));
}
@Override
public void setLabel(String label) {
nativeSetMenuTitle(getModel(), label);
public final void setLabel(final String label) {
execute(ptr->nativeSetMenuTitle(ptr, label));
super.setLabel(label);
}
// Note that addSeparator is never called directly from java.awt.Menu,
// though it is required in the MenuPeer interface.
@Override
public void addSeparator() {
nativeAddSeparator(getModel());
public final void addSeparator() {
execute(this::nativeAddSeparator);
}
// Used by ScreenMenuBar to get to the native menu for event handling.
public long getNativeMenu() {
return nativeGetNSMenu(getModel());
public final long getNativeMenu() {
return executeGet(this::nativeGetNSMenu);
}
private native long nativeCreateMenu(long parentMenuPtr,
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -29,7 +29,9 @@ import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.peer.MenuBarPeer;
public class CMenuBar extends CMenuComponent implements MenuBarPeer {
import sun.awt.AWTAccessor;
public final class CMenuBar extends CMenuComponent implements MenuBarPeer {
private int nextInsertionIndex = -1;
......@@ -38,15 +40,16 @@ public class CMenuBar extends CMenuComponent implements MenuBarPeer {
}
@Override
protected long createModel() {
long createModel() {
return nativeCreateMenuBar();
}
@Override
public void addHelpMenu(Menu m) {
CMenu cMenu = (CMenu)m.getPeer();
nativeSetHelpMenu(getModel(), cMenu.getModel());
}
public void addHelpMenu(final Menu m) {
final CMenu cMenu = AWTAccessor.getMenuComponentAccessor().getPeer(m);
execute(parentPtr -> cMenu.execute(
menuPtr -> nativeSetHelpMenu(parentPtr, menuPtr)));
}
public int getNextInsertionIndex() {
return nextInsertionIndex;
......@@ -63,8 +66,8 @@ public class CMenuBar extends CMenuComponent implements MenuBarPeer {
}
@Override
public void delMenu(int index) {
nativeDelMenu(getModel(), index);
public void delMenu(final int index) {
execute(ptr -> nativeDelMenu(ptr, index));
}
private native long nativeCreateMenuBar();
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -29,36 +29,32 @@ import java.awt.Font;
import java.awt.MenuComponent;
import java.awt.peer.MenuComponentPeer;
public abstract class CMenuComponent implements MenuComponentPeer {
abstract class CMenuComponent extends CFRetainedResource
implements MenuComponentPeer {
private MenuComponent target;
private long modelPtr;
private final MenuComponent target;
CMenuComponent(MenuComponent target) {
CMenuComponent(final MenuComponent target) {
super(0, true);
this.target = target;
this.modelPtr = createModel();
setPtr(createModel());
}
MenuComponent getTarget() {
final MenuComponent getTarget() {
return target;
}
public long getModel() {
return modelPtr;
}
protected abstract long createModel();
abstract long createModel();
public void dispose() {
@Override
public final void dispose() {
super.dispose();
LWCToolkit.targetDisposedPeer(target, this);
nativeDispose(modelPtr);
target = null;
}
private native void nativeDispose(long modelPtr);
// 1.5 peer method
public void setFont(Font f) {
@Override
public final void setFont(final Font f) {
// no-op, as we don't currently support menu fonts
// c.f. radar 4032912
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -25,16 +25,17 @@
package sun.lwawt.macosx;
import sun.awt.SunToolkit;
import sun.lwawt.LWToolkit;
import java.awt.MenuContainer;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.peer.MenuItemPeer;
import java.util.concurrent.atomic.AtomicBoolean;
import sun.awt.SunToolkit;
import sun.lwawt.LWToolkit;
public class CMenuItem extends CMenuComponent implements MenuItemPeer {
private final AtomicBoolean enabled = new AtomicBoolean(true);
......@@ -58,9 +59,9 @@ public class CMenuItem extends CMenuComponent implements MenuItemPeer {
}
@Override
protected long createModel() {
long createModel() {
CMenuComponent parent = (CMenuComponent)LWToolkit.targetToPeer(getTarget().getParent());
return nativeCreate(parent.getModel(), isSeparator());
return parent.executeGet(ptr->nativeCreate(ptr, isSeparator()));
}
public void setLabel(String label, char keyChar, int keyCode, int modifiers) {
......@@ -90,7 +91,12 @@ public class CMenuItem extends CMenuComponent implements MenuItemPeer {
keyChar = 0;
}
nativeSetLabel(getModel(), label, keyChar, keyCode, keyMask);
final String finalLabel = label;
final char finalKeyChar = keyChar;
final int finalKeyCode = keyCode;
final int finalKeyMask = keyMask;
execute(ptr -> nativeSetLabel(ptr, finalLabel, finalKeyChar,
finalKeyCode, finalKeyMask));
}
@Override
......@@ -105,16 +111,16 @@ public class CMenuItem extends CMenuComponent implements MenuItemPeer {
* There isn't a need to expose this except in a instanceof because
* it isn't defined in the peer api.
*/
public void setImage(java.awt.Image img) {
public final void setImage(final java.awt.Image img) {
CImage cimg = CImage.getCreator().createFromImage(img);
nativeSetImage(getModel(), cimg == null ? 0L : cimg.ptr);
execute(ptr -> nativeSetImage(ptr, cimg == null ? 0L : cimg.ptr));
}
/**
* New API for tooltips
*/
public void setToolTipText(String text) {
nativeSetTooltip(getModel(), text);
public final void setToolTipText(final String text) {
execute(ptr -> nativeSetTooltip(ptr, text));
}
// @Override
......@@ -138,7 +144,8 @@ public class CMenuItem extends CMenuComponent implements MenuItemPeer {
b &= ((CMenuItem) parent).isEnabled();
}
if (enabled.compareAndSet(!b, b)) {
nativeSetEnabled(getModel(), b);
final boolean finalB = b;
execute(ptr->nativeSetEnabled(ptr, finalB));
}
}
......
......@@ -426,7 +426,7 @@ public class CPlatformWindow extends CFRetainedResource implements PlatformWindo
final long nsWindowPtr = getNSWindowPtr();
CMenuBar mbPeer = (CMenuBar)LWToolkit.targetToPeer(mb);
if (mbPeer != null) {
nativeSetNSWindowMenuBar(nsWindowPtr, mbPeer.getModel());
mbPeer.execute(ptr -> nativeSetNSWindowMenuBar(nsWindowPtr, ptr));
} else {
nativeSetNSWindowMenuBar(nsWindowPtr, 0);
}
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -25,18 +25,20 @@
package sun.lwawt.macosx;
import java.awt.*;
import java.awt.Component;
import java.awt.Event;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.peer.PopupMenuPeer;
import sun.lwawt.LWWindowPeer;
final class CPopupMenu extends CMenu implements PopupMenuPeer {
public class CPopupMenu extends CMenu implements PopupMenuPeer {
CPopupMenu(PopupMenu target) {
super(target);
}
@Override
protected long createModel() {
long createModel() {
return nativeCreatePopupMenu();
}
......@@ -50,7 +52,7 @@ public class CPopupMenu extends CMenu implements PopupMenuPeer {
Point loc = origin.getLocationOnScreen();
e.x += loc.x;
e.y += loc.y;
nativeShowPopupMenu(getModel(), e.x, e.y);
execute(ptr -> nativeShowPopupMenu(ptr, e.x, e.y));
}
}
}
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -104,7 +104,10 @@ public class CTrayIcon extends CFRetainedResource implements TrayIconPeer {
return 0L;
}
}
return checkAndCreatePopupPeer().getModel();
// This method is executed on Appkit, so if ptr is not zero means that,
// it is still not deallocated(even if we call NSApp postRunnableEvent)
// and sent CFRelease to the native queue
return checkAndCreatePopupPeer().ptr;
}
/**
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -103,8 +103,6 @@ JNF_COCOA_ENTER(env);
CALayer *windowLayer = jlong_to_ptr(windowLayerPtr);
surfaceLayers = [[AWTSurfaceLayers alloc] initWithWindowLayer: windowLayer];
CFRetain(surfaceLayers);
[surfaceLayers release];
}];
JNF_COCOA_EXIT(env);
......
......@@ -114,9 +114,9 @@ AWT_ASSERT_APPKIT_THREAD;
remoteLayer.parentLayer = parentLayer;
remoteLayer.remoteLayer = NULL;
remoteLayer.jrsRemoteLayer = [remoteLayer createRemoteLayerBoundTo:JRSRemotePort];
CFRetain(remoteLayer); // REMIND
[remoteLayer retain]; // REMIND
remoteLayer.frame = CGRectMake(0, 0, 720, 500); // REMIND
CFRetain(remoteLayer.jrsRemoteLayer); // REMIND
[remoteLayer.jrsRemoteLayer retain]; // REMIND
int layerID = [remoteLayer.jrsRemoteLayer layerID];
NSLog(@"layer id to send = %d", layerID);
sendLayerID(layerID);
......@@ -1341,12 +1341,9 @@ JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
CALayer *windowLayer = jlong_to_ptr(windowLayerPtr);
AWTView *view = [[AWTView alloc] initWithRect:rect
platformView:cPlatformView
windowLayer:windowLayer];
CFRetain(view);
[view release]; // GC
newView = view;
newView = [[AWTView alloc] initWithRect:rect
platformView:cPlatformView
windowLayer:windowLayer];
}];
JNF_COCOA_EXIT(env);
......
......@@ -979,7 +979,7 @@ JNF_COCOA_ENTER(env);
contentView:contentView];
// the window is released is CPlatformWindow.nativeDispose()
if (window) CFRetain(window.nsWindow);
if (window) [window.nsWindow retain];
}];
JNF_COCOA_EXIT(env);
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -255,8 +255,6 @@ AWT_ASSERT_APPKIT_THREAD;
[super dealloc];
}
//- (void)finalize { [super finalize]; } // GC
#pragma mark Callbacks from AppKit
......@@ -623,8 +621,7 @@ JNIEXPORT jlong JNICALL Java_com_apple_eawt__1AppDockIconHandler_nativeGetDockIc
JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
image = [ApplicationDelegate _dockIconImage];
CFRetain(image);
image = [[ApplicationDelegate _dockIconImage] retain];
}];
JNF_COCOA_EXIT(env);
......
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -72,7 +72,6 @@ static CClipboard *sClipboard = nil;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (NSData *)data {
return fData;
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -79,7 +79,7 @@ JNF_COCOA_ENTER(env);
LSApplicationParameters params = {0, flags, NULL, NULL, NULL, NULL, NULL};
status = LSOpenURLsWithRole((CFArrayRef)[NSArray arrayWithObject:url], kLSRolesAll, NULL, &params, NULL, 0);
CFRelease(url);
[url release];
JNF_COCOA_EXIT(env);
return status;
......
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -193,7 +193,7 @@ static BOOL sNeedsEnter;
fFormatMap = NULL;
}
CFRelease(self); // GC
[self release];
}
- (void)dealloc
......@@ -209,8 +209,6 @@ static BOOL sNeedsEnter;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
// Appropriated from Windows' awt_DataTransferer.cpp:
//
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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,6 @@ JNF_COCOA_ENTER(env);
}];
JNF_COCOA_EXIT(env);
if (dragSource) {
CFRetain(dragSource); // GC
[dragSource release];
}
return ptr_to_jlong(dragSource);
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -171,7 +171,7 @@ extern JNFClassInfo jc_CDropTargetContextPeer;
fDropTargetContextPeer = NULL;
}
CFRelease(self);
[self release];
}
- (void)dealloc
......@@ -187,7 +187,6 @@ extern JNFClassInfo jc_CDropTargetContextPeer;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (NSInteger) getDraggingSequenceNumber
{
......@@ -724,10 +723,6 @@ JNF_COCOA_ENTER(env);
dropTarget = [[CDropTarget alloc] init:jdroptarget component:jcomponent peer:jpeer control:controlObj];
JNF_COCOA_EXIT(env);
if (dropTarget) {
CFRetain(dropTarget); // GC
[dropTarget release];
}
return ptr_to_jlong(dropTarget);
}
......
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -88,7 +88,6 @@ canChooseDirectories:(BOOL)inChooseDirectories
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (void)safeSaveOrLoad {
NSSavePanel *thePanel = nil;
......@@ -168,9 +167,9 @@ canChooseDirectories:(BOOL)inChooseDirectories
}
// ask the file filter up in Java
CFStringRef filePath = CFURLCopyFileSystemPath((CFURLRef)url, kCFURLPOSIXPathStyle);
BOOL shouldEnableFile = [self askFilenameFilter:(NSString *)filePath];
CFRelease(filePath);
NSString* filePath = (NSString*)CFURLCopyFileSystemPath((CFURLRef)url, kCFURLPOSIXPathStyle);
BOOL shouldEnableFile = [self askFilenameFilter:filePath];
[filePath release];
return shouldEnableFile;
}
......
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -164,8 +164,7 @@ Java_sun_awt_CGraphicsEnvironment_registerDisplayReconfiguration
JNF_COCOA_ENTER(env);
JNFWeakJObjectWrapper *wrapper = [JNFWeakJObjectWrapper wrapperWithJObject:this withEnv:env];
CFRetain(wrapper); // pin from ObjC-GC
JNFWeakJObjectWrapper *wrapper = [[JNFWeakJObjectWrapper wrapperWithJObject:this withEnv:env] retain];
/* Register the callback */
if (CGDisplayRegisterReconfigurationCallback(&displaycb_handle, wrapper) != kCGErrorSuccess) {
......@@ -205,8 +204,7 @@ JNF_COCOA_ENTER(env);
}
[wrapper setJObject:NULL withEnv:env]; // more efficiant to pre-clear
CFRelease(wrapper);
[wrapper release];
JNF_COCOA_EXIT(env);
}
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -115,14 +115,9 @@ JNF_COCOA_ENTER(env);
NSBitmapImageRep* imageRep = CImage_CreateImageRep(env, buffer, width, height);
if (imageRep) {
NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];
NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(width, height)] retain];
[nsImage addRepresentation:imageRep];
[imageRep release];
if (nsImage != nil) {
CFRetain(nsImage); // GC
}
result = ptr_to_jlong(nsImage);
}
......@@ -165,13 +160,8 @@ JNF_COCOA_ENTER(env);
(*env)->ReleaseIntArrayElements(env, widths, ws, JNI_ABORT);
}
if ([reps count]) {
NSImage *nsImage = [[NSImage alloc] initWithSize:NSMakeSize(0, 0)];
NSImage *nsImage = [[[NSImage alloc] initWithSize:NSMakeSize(0, 0)] retain];
[nsImage addRepresentations: reps];
if (nsImage != nil) {
CFRetain(nsImage); // GC
}
result = ptr_to_jlong(nsImage);
}
......@@ -194,8 +184,7 @@ JNF_COCOA_ENTER(env);
IconRef iconRef;
if (noErr == GetIconRef(kOnSystemDisk, kSystemIconsCreator, selector, &iconRef)) {
image = [[NSImage alloc] initWithIconRef:iconRef];
if (image) CFRetain(image); // GC
image = [[[NSImage alloc] initWithIconRef:iconRef] retain];
ReleaseIconRef(iconRef);
}
......@@ -217,8 +206,7 @@ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CImage_nativeCreateNSImageFromFile
JNF_COCOA_ENTER(env);
NSString *path = JNFNormalizedNSStringForPath(env, file);
image = [[NSImage alloc] initByReferencingFile:path];
if (image) CFRetain(image); // GC
image = [[[NSImage alloc] initByReferencingFile:path] retain];
JNF_COCOA_EXIT(env);
......@@ -239,9 +227,8 @@ JNF_COCOA_ENTER(env);
NSString *path = JNFNormalizedNSStringForPath(env, file);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
image = [[NSWorkspace sharedWorkspace] iconForFile:path];
image = [[[NSWorkspace sharedWorkspace] iconForFile:path] retain];
[image setScalesWhenResized:TRUE];
if (image) CFRetain(image); // GC
}];
JNF_COCOA_EXIT(env);
......@@ -261,8 +248,7 @@ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_CImage_nativeCreateNSImageFromImag
JNF_COCOA_ENTER(env);
image = [NSImage imageNamed:JNFJavaToNSString(env, name)];
if (image) CFRetain(image); // GC
image = [[NSImage imageNamed:JNFJavaToNSString(env, name)] retain];
JNF_COCOA_EXIT(env);
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -38,7 +38,7 @@
- (id)initWithPeer:(jobject)peer {
AWT_ASSERT_APPKIT_THREAD;
// Create the new NSMenu
self = [super initWithPeer:peer asSeparator:[NSNumber numberWithBool:NO]];
self = [super initWithPeer:peer asSeparator:NO];
if (self) {
fMenu = [NSMenu javaMenuWithTitle:@""];
[fMenu retain];
......@@ -52,7 +52,6 @@ AWT_ASSERT_APPKIT_THREAD;
fMenu = nil;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (void)addJavaSubmenu:(CMenu *)submenu {
[ThreadUtilities performOnMainThread:@selector(addNativeItem_OnAppKitThread:) on:self withObject:submenu waitUntilDone:YES];
......@@ -134,14 +133,13 @@ AWT_ASSERT_APPKIT_THREAD;
CMenu * createCMenu (jobject cPeerObjGlobal) {
CMenu *aCMenu = nil;
// We use an array here only to be able to get a return value
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
__block CMenu *aCMenu = nil;
[ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenu alloc] withObject:args waitUntilDone:YES];
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
aCMenu = (CMenu *)[args objectAtIndex: 0];
aCMenu = [[CMenu alloc] initWithPeer:cPeerObjGlobal];
// the aCMenu is released in CMenuComponent.dispose()
}];
if (aCMenu == nil) {
return 0L;
......@@ -169,10 +167,6 @@ JNF_COCOA_ENTER(env);
// Add it to the parent menu
[((CMenu *)jlong_to_ptr(parentMenu)) addJavaSubmenu: aCMenu];
if (aCMenu) {
CFRetain(aCMenu); // GC
[aCMenu release];
}
JNF_COCOA_EXIT(env);
......@@ -209,10 +203,6 @@ JNF_COCOA_ENTER(env);
[parent javaSetHelpMenu: aCMenu];
}
if (aCMenu) {
CFRetain(aCMenu); // GC
[aCMenu release];
}
JNF_COCOA_EXIT(env);
return ptr_to_jlong(aCMenu);
}
......@@ -275,13 +265,9 @@ Java_sun_lwawt_macosx_CMenu_nativeGetNSMenu
NSMenu* nsMenu = NULL;
JNF_COCOA_ENTER(env);
nsMenu = [((CMenu *)jlong_to_ptr(menuObject)) menu];
JNF_COCOA_EXIT(env);
// Strong retain this menu; it'll get released in Java_apple_laf_ScreenMenu_addMenuListeners
if (nsMenu) {
CFRetain(nsMenu); // GC
}
nsMenu = [[((CMenu *)jlong_to_ptr(menuObject)) menu] retain];
JNF_COCOA_EXIT(env);
return ptr_to_jlong(nsMenu);
}
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -383,32 +383,21 @@ JNIEXPORT jlong JNICALL
Java_sun_lwawt_macosx_CMenuBar_nativeCreateMenuBar
(JNIEnv *env, jobject peer)
{
CMenuBar *aCMenuBar = nil;
__block CMenuBar *aCMenuBar = nil;
JNF_COCOA_ENTER(env);
jobject cPeerObjGlobal = (*env)->NewGlobalRef(env, peer);
// We use an array here only to be able to get a return value
NSMutableArray *args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], nil];
[ThreadUtilities performOnMainThread:@selector(_create_OnAppKitThread:) on:[CMenuBar alloc] withObject:args waitUntilDone:YES];
aCMenuBar = (CMenuBar *)[args objectAtIndex: 0];
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
aCMenuBar = [[CMenuBar alloc] initWithPeer:cPeerObjGlobal];
// the aCMenuBar is released in CMenuComponent.dispose()
}];
if (aCMenuBar == nil) {
return 0L;
}
// [args release];
// A strange memory managment after that.
JNF_COCOA_EXIT(env);
if (aCMenuBar) {
CFRetain(aCMenuBar); // GC
[aCMenuBar release];
}
return ptr_to_jlong(aCMenuBar);
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -41,49 +41,11 @@
return self;
}
-(void) cleanup {
// Used by subclasses
}
-(void) disposer {
-(void) dealloc {
JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
JNFDeleteGlobalRef(env, fPeer);
fPeer = NULL;
[self cleanup];
CFRelease(self); // GC
[super dealloc];
}
// The method is used by all subclasses, since the process of the creation
// is the same. The only exception is the CMenuItem class.
- (void) _create_OnAppKitThread: (NSMutableArray *)argValue {
jobject cPeerObjGlobal = (jobject)[[argValue objectAtIndex: 0] pointerValue];
CMenuItem *aCMenuItem = [self initWithPeer:cPeerObjGlobal];
[argValue removeAllObjects];
[argValue addObject: aCMenuItem];
}
//-(void) dealloc { [super dealloc]; }
//- (void)finalize { [super finalize]; }
@end
/*
* Class: sun_lwawt_macosx_CMenuComponent
* Method: nativeDispose
* Signature: (J)V
*/
JNIEXPORT void JNICALL
Java_sun_lwawt_macosx_CMenuComponent_nativeDispose
(JNIEnv *env, jobject peer, jlong menuItemObj)
{
JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(disposer)
on:((id)jlong_to_ptr(menuItemObj))
withObject:nil
waitUntilDone:NO];
JNF_COCOA_EXIT(env);
}
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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,7 +32,7 @@
}
// Setup
- (id) initWithPeer:(jobject)peer asSeparator: (NSNumber *) asSeparator;
- (id) initWithPeer:(jobject)peer asSeparator: (BOOL) asSeparator;
- (void) setIsCheckbox;
// Events
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
......@@ -39,11 +39,11 @@
@implementation CMenuItem
- (id) initWithPeer:(jobject)peer asSeparator: (NSNumber *) asSeparator{
- (id) initWithPeer:(jobject)peer asSeparator: (BOOL) asSeparator{
AWT_ASSERT_APPKIT_THREAD;
self = [super initWithPeer:peer];
if (self) {
if ([asSeparator boolValue]) {
if (asSeparator) {
fMenuItem = (NSMenuItem*)[NSMenuItem separatorItem];
[fMenuItem retain];
} else {
......@@ -199,12 +199,9 @@ JNF_COCOA_EXIT(env);
}];
}
- (void)cleanup {
- (void)dealloc {
[fMenuItem setAction:NULL];
[fMenuItem setTarget:nil];
}
- (void)dealloc {
[fMenuItem release];
fMenuItem = nil;
......@@ -223,14 +220,6 @@ JNF_COCOA_EXIT(env);
fIsCheckbox = YES;
}
- (void) _createMenuItem_OnAppKitThread: (NSMutableArray *)argValue {
jobject cPeerObjGlobal = (jobject)[[argValue objectAtIndex: 0] pointerValue];
NSNumber * asSeparator = (NSNumber *)[argValue objectAtIndex: 1];
CMenuItem *aCMenuItem = [self initWithPeer: cPeerObjGlobal asSeparator: asSeparator];
[argValue removeAllObjects];
[argValue addObject: aCMenuItem];
}
- (NSString *)description {
return [NSString stringWithFormat:@"CMenuItem[ %@ ]", fMenuItem];
}
......@@ -392,24 +381,18 @@ Java_sun_lwawt_macosx_CMenuItem_nativeCreate
(JNIEnv *env, jobject peer, jlong parentCMenuObj, jboolean isSeparator)
{
CMenuItem *aCMenuItem = nil;
__block CMenuItem *aCMenuItem = nil;
BOOL asSeparator = (isSeparator == JNI_TRUE) ? YES: NO;
CMenu *parentCMenu = (CMenu *)jlong_to_ptr(parentCMenuObj);
JNF_COCOA_ENTER(env);
jobject cPeerObjGlobal = (*env)->NewGlobalRef(env, peer);
NSMutableArray *args = nil;
// Create a new item....
if (isSeparator == JNI_TRUE) {
args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:YES], nil];
} else {
args = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithBytes:&cPeerObjGlobal objCType:@encode(jobject)], [NSNumber numberWithBool:NO], nil];
}
[ThreadUtilities performOnMainThread:@selector(_createMenuItem_OnAppKitThread:) on:[CMenuItem alloc] withObject:args waitUntilDone:YES];
aCMenuItem = (CMenuItem *)[args objectAtIndex: 0];
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
aCMenuItem = [[CMenuItem alloc] initWithPeer: cPeerObjGlobal
asSeparator: asSeparator];
// the CMenuItem is released in CMenuComponent.dispose()
}];
if (aCMenuItem == nil) {
return 0L;
......@@ -420,11 +403,6 @@ JNF_COCOA_ENTER(env);
// setLabel will be called after creation completes.
if (aCMenuItem) {
CFRetain(aCMenuItem); // GC
[aCMenuItem release];
}
JNF_COCOA_EXIT(env);
return ptr_to_jlong(aCMenuItem);
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -66,8 +66,6 @@ JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThreadWaiting:YES block:^(){
aCPopupMenu = [[CPopupMenu alloc] initWithPeer:cPeerObjGlobal];
CFRetain(aCPopupMenu);
[aCPopupMenu release];
}];
JNF_COCOA_EXIT(env);
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -469,8 +469,6 @@ JNF_COCOA_ENTER(env);
// safety is assured by the java side of this call.
NSPrintInfo* printInfo = createDefaultNSPrintInfo(env, NULL);
if (printInfo) CFRetain(printInfo); // GC
[printInfo release];
result = ptr_to_jlong(printInfo);
......@@ -490,7 +488,7 @@ JNF_COCOA_ENTER(env);
if (nsPrintInfo != -1)
{
NSPrintInfo* printInfo = (NSPrintInfo*)jlong_to_ptr(nsPrintInfo);
if (printInfo) CFRelease(printInfo); // GC
[printInfo release];
}
JNF_COCOA_EXIT(env);
}
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -75,7 +75,7 @@ static JNF_STATIC_MEMBER_CACHE(jm_systemColorsChanged, jc_LWCToolkit, "systemCol
sColors = (NSColor**)malloc(sizeof(NSColor*) * java_awt_SystemColor_NUM_COLORS);
} else {
for (i = 0; i < java_awt_SystemColor_NUM_COLORS; i++) {
if (sColors[i] != NULL) CFRelease(sColors[i]); // GC
if (sColors[i] != NULL) [sColors[i] release];
}
}
......@@ -108,14 +108,14 @@ static JNF_STATIC_MEMBER_CACHE(jm_systemColorsChanged, jc_LWCToolkit, "systemCol
sColors[java_awt_SystemColor_INFO_TEXT] = [NSColor textColor];
for (i = 0; i < java_awt_SystemColor_NUM_COLORS; i++) {
if (sColors[i] != NULL) CFRetain(sColors[i]); // GC
[sColors[i] retain];
}
if (appleColors == nil) {
appleColors = (NSColor**)malloc(sizeof(NSColor*) * sun_lwawt_macosx_LWCToolkit_NUM_APPLE_COLORS);
} else {
for (i = 0; i < sun_lwawt_macosx_LWCToolkit_NUM_APPLE_COLORS; i++) {
if (appleColors[i] != NULL) CFRelease(appleColors[i]); // GC
if (appleColors[i] != NULL) [appleColors[i] release];
}
}
......@@ -124,7 +124,7 @@ static JNF_STATIC_MEMBER_CACHE(jm_systemColorsChanged, jc_LWCToolkit, "systemCol
appleColors[sun_lwawt_macosx_LWCToolkit_INACTIVE_SELECTION_FOREGROUND_COLOR] = [NSColor controlDarkShadowColor];
for (i = 0; i < sun_lwawt_macosx_LWCToolkit_NUM_APPLE_COLORS; i++) {
if (appleColors[i] != NULL) CFRetain(appleColors[i]); // GC
[appleColors[i] retain];
}
}
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -1497,7 +1497,7 @@ PRINT("ImageSD_dispose")
}
if (isdo->nsRef) {
CFRelease(isdo->nsRef); // GC
[isdo->nsRef release];
isdo->nsRef = nil;
}
......
......@@ -55,19 +55,6 @@
[super dealloc];
}
- (void)finalize
{
JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
JNFDeleteWeakGlobalRef(env, fAccessibleAction);
fAccessibleAction = NULL;
JNFDeleteWeakGlobalRef(env, fComponent);
fComponent = NULL;
[super finalize];
}
- (NSString *)getDescription
{
......@@ -131,19 +118,6 @@
[super dealloc];
}
- (void)finalize
{
JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
JNFDeleteWeakGlobalRef(env, fTabGroup);
fTabGroup = NULL;
JNFDeleteWeakGlobalRef(env, fComponent);
fComponent = NULL;
[super finalize];
}
- (NSString *)getDescription
{
return @"click";
......
......@@ -194,20 +194,6 @@ static NSObject *sAttributeNamesLOCK = nil;
[super dealloc];
}
- (void)finalize
{
[self unregisterFromCocoaAXSystem];
JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
(*env)->DeleteWeakGlobalRef(env, fAccessible);
fAccessible = NULL;
(*env)->DeleteWeakGlobalRef(env, fComponent);
fComponent = NULL;
[super finalize];
}
- (void)postValueChanged
{
......@@ -382,8 +368,8 @@ static NSObject *sAttributeNamesLOCK = nil;
// must init freshly -alloc'd object
[newChild initWithParent:parent withEnv:env withAccessible:jCAX withIndex:index withView:view withJavaRole:javaRole]; // must init new instance
// must hard CFRetain() pointer poked into Java object
CFRetain(newChild);
// must hard retain pointer poked into Java object
[newChild retain];
JNFSetLongField(env, jCAX, jf_ptr, ptr_to_jlong(newChild));
(*env)->DeleteLocalRef(env, jCAX);
......@@ -1596,18 +1582,6 @@ static BOOL ObjectEquals(JNIEnv *env, jobject a, jobject b, jobject component);
[super dealloc];
}
- (void)finalize
{
JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
if (fTabGroupAxContext != NULL) {
JNFDeleteWeakGlobalRef(env, fTabGroupAxContext);
fTabGroupAxContext = NULL;
}
[super finalize];
}
- (id)accessibilityValueAttribute
{
JNIEnv *env = [ThreadUtilities getJNIEnv];
......
/*
* Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -273,17 +273,15 @@ JNIEXPORT jlong JNICALL Java_sun_lwawt_macosx_LWCToolkit_createAWTRunLoopMediato
{
AWT_ASSERT_APPKIT_THREAD;
AWTRunLoopObject *o = nil;
jlong result;
JNF_COCOA_ENTER(env);
// We double retain because this object is owned by both main thread and "other" thread
// We release in both doAWTRunLoop and stopAWTRunLoop
o = [[AWTRunLoopObject alloc] init];
if (o) {
CFRetain(o); // GC
CFRetain(o); // GC
[o release];
}
return ptr_to_jlong(o);
result = ptr_to_jlong([[[AWTRunLoopObject alloc] init] retain]);
JNF_COCOA_EXIT(env);
return result;
}
/*
......@@ -320,10 +318,7 @@ JNF_COCOA_ENTER(env);
}
}
CFRelease(mediatorObject);
[mediatorObject release];
JNF_COCOA_EXIT(env);
}
......@@ -341,7 +336,7 @@ JNF_COCOA_ENTER(env);
[ThreadUtilities performOnMainThread:@selector(endRunLoop) on:mediatorObject withObject:nil waitUntilDone:NO];
CFRelease(mediatorObject);
[mediatorObject release];
JNF_COCOA_EXIT(env);
}
......
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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,7 +48,6 @@
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (BOOL)runPageSetup {
__block BOOL fResult = NO;
......@@ -86,8 +85,8 @@ AWT_ASSERT_NOT_APPKIT_THREAD;
fResult = [self safePrintLoop:printerView withEnv:env];
} else {
// Retain these so they don't go away while we're in Java
CFRetain(self); // GC
if (printerView) CFRetain(printerView); // GC
[self retain];
[printerView retain];
static JNF_CLASS_CACHE(jc_CPrinterJob, "sun/lwawt/macosx/CPrinterJob");
static JNF_STATIC_MEMBER_CACHE(jm_detachPrintLoop, jc_CPrinterJob, "detachPrintLoop", "(JJ)V");
......@@ -134,8 +133,8 @@ JNF_COCOA_ENTER(env);
[model safePrintLoop:arg withEnv:env];
// These are to match the retains in runPrintLoopWithView:
if (model) CFRelease(model); // GC
if (arg) CFRelease(arg); // GC
[model release];
[arg release];
JNF_COCOA_EXIT(env);
}
......
/*
* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2011, 2016, 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
......@@ -71,7 +71,6 @@ AWT_ASSERT_APPKIT_THREAD;
[super dealloc];
}
//- (void)finalize { [super finalize]; }
- (void)finishLaunching
{
......
......@@ -729,7 +729,11 @@ public class PNGImageReader extends ImageReader {
parse_iCCP_chunk(chunkLength);
break;
case iTXt_TYPE:
parse_iTXt_chunk(chunkLength);
if (ignoreMetadata) {
stream.skipBytes(chunkLength);
} else {
parse_iTXt_chunk(chunkLength);
}
break;
case pHYs_TYPE:
parse_pHYs_chunk();
......@@ -753,7 +757,11 @@ public class PNGImageReader extends ImageReader {
parse_tRNS_chunk(chunkLength);
break;
case zTXt_TYPE:
parse_zTXt_chunk(chunkLength);
if (ignoreMetadata) {
stream.skipBytes(chunkLength);
} else {
parse_zTXt_chunk(chunkLength);
}
break;
default:
// Read an unknown chunk
......
......@@ -33,6 +33,8 @@ import java.util.Hashtable;
import org.omg.CosNaming.*;
import com.sun.jndi.toolkit.corba.CorbaUtils;
/**
* Implements the JNDI NamingEnumeration interface for COS
* Naming. Gets hold of a list of bindings from the COS Naming Server
......@@ -212,7 +214,10 @@ final class CNBindingEnumeration
Name cname = CNNameParser.cosNameToName(bndg.binding_name);
try {
// Check whether object factory codebase is trusted
if (CorbaUtils.isObjectFactoryTrusted(obj)) {
obj = NamingManager.getObjectInstance(obj, cname, _ctx, _env);
}
} catch (NamingException e) {
throw e;
} catch (Exception e) {
......
......@@ -36,6 +36,8 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
......@@ -82,6 +84,19 @@ public class CNCtx implements javax.naming.Context {
private static final String FED_PROP = "com.sun.jndi.cosnaming.federation";
boolean federation = false;
/**
* Determines whether classes may be loaded from an arbitrary URL code base.
*/
public static final boolean trustURLCodebase;
static {
// System property to control whether classes may be loaded from an
// arbitrary URL code base
PrivilegedAction<String> act = () -> System.getProperty(
"com.sun.jndi.cosnaming.object.trustURLCodebase", "false");
String trust = AccessController.doPrivileged(act);
trustURLCodebase = "true".equalsIgnoreCase(trust);
}
// Reference counter for tracking _orb references
OrbReuseTracker orbTracker = null;
int enumCount;
......@@ -534,12 +549,16 @@ public class CNCtx implements javax.naming.Context {
if (name.size() == 0 )
return this; // %%% should clone() so that env can be changed
NameComponent[] path = CNNameParser.nameToCosName(name);
java.lang.Object answer = null;
try {
java.lang.Object answer = callResolve(path);
answer = callResolve(path);
try {
return NamingManager.getObjectInstance(answer, name, this, _env);
// Check whether object factory codebase is trusted
if (CorbaUtils.isObjectFactoryTrusted(answer)) {
answer = NamingManager.getObjectInstance(
answer, name, this, _env);
}
} catch (NamingException e) {
throw e;
} catch (Exception e) {
......@@ -552,6 +571,7 @@ public class CNCtx implements javax.naming.Context {
javax.naming.Context cctx = getContinuationContext(cpe);
return cctx.lookup(cpe.getRemainingName());
}
return answer;
}
/**
......
......@@ -33,6 +33,8 @@ import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;
import com.sun.jndi.toolkit.corba.CorbaUtils;
/**
* A convenience class to map the COS Naming exceptions to the JNDI exceptions.
* @author Raj Krishnamurthy
......@@ -202,10 +204,13 @@ public final class ExceptionMapper {
// Not a context, use object factory to transform object.
Name cname = CNNameParser.cosNameToName(resolvedName);
java.lang.Object resolvedObj2;
java.lang.Object resolvedObj2 = null;
try {
// Check whether object factory codebase is trusted
if (CorbaUtils.isObjectFactoryTrusted(resolvedObj)) {
resolvedObj2 = NamingManager.getObjectInstance(resolvedObj,
cname, ctx, ctx._env);
}
} catch (NamingException ge) {
throw ge;
} catch (Exception ge) {
......
......@@ -32,6 +32,8 @@ import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.naming.*;
import javax.naming.spi.NamingManager;
......@@ -52,6 +54,18 @@ public class RegistryContext implements Context, Referenceable {
private int port;
private static final NameParser nameParser = new AtomicNameParser();
private static final String SOCKET_FACTORY = "com.sun.jndi.rmi.factory.socket";
/**
* Determines whether classes may be loaded from an arbitrary URL code base.
*/
static final boolean trustURLCodebase;
static {
// System property to control whether classes may be loaded from an
// arbitrary URL codebase
PrivilegedAction<String> act = () -> System.getProperty(
"com.sun.jndi.rmi.object.trustURLCodebase", "false");
String trust = AccessController.doPrivileged(act);
trustURLCodebase = "true".equalsIgnoreCase(trust);
}
Reference reference = null; // ref used to create this context, if any
......@@ -461,6 +475,27 @@ public class RegistryContext implements Context, Referenceable {
Object obj = (r instanceof RemoteReference)
? ((RemoteReference)r).getReference()
: (Object)r;
/*
* Classes may only be loaded from an arbitrary URL codebase when
* the system property com.sun.jndi.rmi.object.trustURLCodebase
* has been set to "true".
*/
// Use reference if possible
Reference ref = null;
if (obj instanceof Reference) {
ref = (Reference) obj;
} else if (obj instanceof Referenceable) {
ref = ((Referenceable)(obj)).getReference();
}
if (ref != null && ref.getFactoryClassLocation() != null &&
!trustURLCodebase) {
throw new ConfigurationException(
"The object factory is untrusted. Set the system property" +
" 'com.sun.jndi.rmi.object.trustURLCodebase' to 'true'.");
}
return NamingManager.getObjectInstance(obj, name, this,
environment);
} catch (NamingException e) {
......
......@@ -36,8 +36,9 @@ import java.util.Enumeration;
import org.omg.CORBA.ORB;
import javax.naming.Context;
import javax.naming.ConfigurationException;
import javax.naming.*;
import com.sun.jndi.cosnaming.CNCtx;
/**
* Contains utilities for performing CORBA-related tasks:
......@@ -203,6 +204,32 @@ public class CorbaUtils {
return ORB.init(new String[0], orbProp);
}
/**
* Check whether object factory code base is trusted.
* Classes may only be loaded from an arbitrary URL code base when
* the system property com.sun.jndi.rmi.object.trustURLCodebase
* has been set to "true".
*/
public static boolean isObjectFactoryTrusted(Object obj)
throws NamingException {
// Extract Reference, if possible
Reference ref = null;
if (obj instanceof Reference) {
ref = (Reference) obj;
} else if (obj instanceof Referenceable) {
ref = ((Referenceable)(obj)).getReference();
}
if (ref != null && ref.getFactoryClassLocation() != null &&
!CNCtx.trustURLCodebase) {
throw new ConfigurationException(
"The object factory is untrusted. Set the system property" +
" 'com.sun.jndi.cosnaming.object.trustURLCodebase' to 'true'.");
}
return true;
}
/**
* This method returns a new ORB instance for the given applet
* without creating a static dependency on java.applet.
......
......@@ -426,7 +426,6 @@ public class LdapLoginModule implements LoginModule {
constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(new String[0]); //return no attrs
constraints.setReturningObjFlag(true); // to get the full DN
}
authzIdentity = (String)options.get(AUTHZ_IDENTITY);
......@@ -886,11 +885,7 @@ public class LdapLoginModule implements LoginModule {
// (Use the first entry if more than one is returned)
if (results.hasMore()) {
SearchResult entry = results.next();
// %%% - use the SearchResult.getNameInNamespace method
// available in JDK 1.5 and later.
// (can remove call to constraints.setReturningObjFlag)
userDN = ((Context)entry.getObject()).getNameInNamespace();
userDN = entry.getNameInNamespace();
if (debug) {
System.out.println("\t\t[LdapLoginModule] found entry: " +
......
......@@ -145,6 +145,10 @@ public abstract class MenuComponent implements java.io.Serializable {
public Font getFont_NoClientCode(MenuComponent menuComp) {
return menuComp.getFont_NoClientCode();
}
@SuppressWarnings("unchecked")
public <T extends MenuComponentPeer> T getPeer(MenuComponent menuComp) {
return (T) menuComp.peer;
}
});
}
......
......@@ -37,13 +37,18 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static java.io.ObjectStreamClass.processQueue;
import sun.misc.ObjectInputFilter;
import sun.misc.ObjectStreamClassValidator;
import sun.misc.SharedSecrets;
import sun.misc.Unsafe;
import sun.reflect.misc.ReflectUtil;
import sun.misc.JavaOISAccess;
import sun.util.logging.PlatformLogger;
/**
* An ObjectInputStream deserializes primitive data and objects previously
......@@ -239,12 +244,48 @@ public class ObjectInputStream
new ReferenceQueue<>();
}
static {
/* Setup access so sun.misc can invoke package private functions. */
sun.misc.SharedSecrets.setJavaOISAccess(new JavaOISAccess() {
public void setObjectInputFilter(ObjectInputStream stream, ObjectInputFilter filter) {
stream.setInternalObjectInputFilter(filter);
}
public ObjectInputFilter getObjectInputFilter(ObjectInputStream stream) {
return stream.getInternalObjectInputFilter();
}
});
}
/*
* Separate class to defer initialization of logging until needed.
*/
private static class Logging {
/*
* Logger for ObjectInputFilter results.
* Setup the filter logger if it is set to INFO or WARNING.
* (Assuming it will not change).
*/
private static final PlatformLogger traceLogger;
private static final PlatformLogger infoLogger;
static {
PlatformLogger filterLog = PlatformLogger.getLogger("java.io.serialization");
infoLogger = (filterLog != null &&
filterLog.isLoggable(PlatformLogger.Level.INFO)) ? filterLog : null;
traceLogger = (filterLog != null &&
filterLog.isLoggable(PlatformLogger.Level.FINER)) ? filterLog : null;
}
}
/** filter stream for handling block data conversion */
private final BlockDataInputStream bin;
/** validation callback list */
private final ValidationList vlist;
/** recursion depth */
private int depth;
private long depth;
/** Total number of references to any type of object, class, enum, proxy, etc. */
private long totalObjectRefs;
/** whether stream is closed */
private boolean closed;
......@@ -270,6 +311,12 @@ public class ObjectInputStream
*/
private SerialCallbackContext curContext;
/**
* Filter of class descriptors and classes read from the stream;
* may be null.
*/
private ObjectInputFilter serialFilter;
/**
* Creates an ObjectInputStream that reads from the specified InputStream.
* A serialization stream header is read from the stream and verified.
......@@ -297,6 +344,7 @@ public class ObjectInputStream
bin = new BlockDataInputStream(in);
handles = new HandleTable(10);
vlist = new ValidationList();
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = false;
readStreamHeader();
bin.setBlockDataMode(true);
......@@ -327,6 +375,7 @@ public class ObjectInputStream
bin = null;
handles = null;
vlist = null;
serialFilter = ObjectInputFilter.Config.getSerialFilter();
enableOverride = true;
}
......@@ -334,7 +383,7 @@ public class ObjectInputStream
* Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overriden using the writeObject
* Default deserializing for a class can be overridden using the writeObject
* and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is
* reconstructed by readObject.
......@@ -1075,6 +1124,138 @@ public class ObjectInputStream
return bin.readUTF();
}
/**
* Returns the serialization filter for this stream.
* The serialization filter is the most recent filter set in
* {@link #setInternalObjectInputFilter setInternalObjectInputFilter} or
* the initial process-wide filter from
* {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}.
*
* @return the serialization filter for the stream; may be null
*/
private final ObjectInputFilter getInternalObjectInputFilter() {
return serialFilter;
}
/**
* Set the serialization filter for the stream.
* The filter's {@link ObjectInputFilter#checkInput checkInput} method is called
* for each class and reference in the stream.
* The filter can check any or all of the class, the array length, the number
* of references, the depth of the graph, and the size of the input stream.
* <p>
* If the filter returns {@link ObjectInputFilter.Status#REJECTED Status.REJECTED},
* {@code null} or throws a {@link RuntimeException},
* the active {@code readObject} or {@code readUnshared}
* throws {@link InvalidClassException}, otherwise deserialization
* continues uninterrupted.
* <p>
* The serialization filter is initialized to the value of
* {@link ObjectInputFilter.Config#getSerialFilter() ObjectInputFilter.Config.getSerialFilter}
* when the {@code ObjectInputStream} is constructed and can be set
* to a custom filter only once.
*
* @implSpec
* The filter, when not {@code null}, is invoked during {@link #readObject readObject}
* and {@link #readUnshared readUnshared} for each object
* (regular or class) in the stream including the following:
* <ul>
* <li>each object reference previously deserialized from the stream
* (class is {@code null}, arrayLength is -1),
* <li>each regular class (class is not {@code null}, arrayLength is -1),
* <li>each interface of a dynamic proxy and the dynamic proxy class itself
* (class is not {@code null}, arrayLength is -1),
* <li>each array is filtered using the array type and length of the array
* (class is the array type, arrayLength is the requested length),
* <li>each object replaced by its class' {@code readResolve} method
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1,
* <li>and each object replaced by {@link #resolveObject resolveObject}
* is filtered using the replacement object's class, if not {@code null},
* and if it is an array, the arrayLength, otherwise -1.
* </ul>
*
* When the {@link ObjectInputFilter#checkInput checkInput} method is invoked
* it is given access to the current class, the array length,
* the current number of references already read from the stream,
* the depth of nested calls to {@link #readObject readObject} or
* {@link #readUnshared readUnshared},
* and the implementation dependent number of bytes consumed from the input stream.
* <p>
* Each call to {@link #readObject readObject} or
* {@link #readUnshared readUnshared} increases the depth by 1
* before reading an object and decreases by 1 before returning
* normally or exceptionally.
* The depth starts at {@code 1} and increases for each nested object and
* decrements when each nested call returns.
* The count of references in the stream starts at {@code 1} and
* is increased before reading an object.
*
* @param filter the filter, may be null
* @throws SecurityException if there is security manager and the
* {@code SerializablePermission("serialFilter")} is not granted
* @throws IllegalStateException if the {@linkplain #getInternalObjectInputFilter() current filter}
* is not {@code null} and is not the process-wide filter
*/
private final void setInternalObjectInputFilter(ObjectInputFilter filter) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new SerializablePermission("serialFilter"));
}
// Allow replacement of the process-wide filter if not already set
if (serialFilter != null &&
serialFilter != ObjectInputFilter.Config.getSerialFilter()) {
throw new IllegalStateException("filter can not be set more than once");
}
this.serialFilter = filter;
}
/**
* Invoke the serialization filter if non-null.
* If the filter rejects or an exception is thrown, throws InvalidClassException.
*
* @param clazz the class; may be null
* @param arrayLength the array length requested; use {@code -1} if not creating an array
* @throws InvalidClassException if it rejected by the filter or
* a {@link RuntimeException} is thrown
*/
private void filterCheck(Class<?> clazz, int arrayLength)
throws InvalidClassException {
if (serialFilter != null) {
RuntimeException ex = null;
ObjectInputFilter.Status status;
try {
status = serialFilter.checkInput(new FilterValues(clazz, arrayLength,
totalObjectRefs, depth, bin.getBytesRead()));
} catch (RuntimeException e) {
// Preventive interception of an exception to log
status = ObjectInputFilter.Status.REJECTED;
ex = e;
}
if (status == null ||
status == ObjectInputFilter.Status.REJECTED) {
// Debug logging of filter checks that fail
if (Logging.infoLogger != null) {
Logging.infoLogger.info(
"ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
status, clazz, arrayLength, totalObjectRefs, depth, bin.getBytesRead(),
Objects.toString(ex, "n/a"));
}
InvalidClassException ice = new InvalidClassException("filter status: " + status);
ice.initCause(ex);
throw ice;
} else {
// Trace logging for those that succeed
if (Logging.traceLogger != null) {
Logging.traceLogger.finer(
"ObjectInputFilter {0}: {1}, array length: {2}, nRefs: {3}, depth: {4}, bytes: {5}, ex: {6}",
status, clazz, arrayLength, totalObjectRefs, depth, bin.getBytesRead(),
Objects.toString(ex, "n/a"));
}
}
}
}
/**
* Provide access to the persistent fields read from the input stream.
*/
......@@ -1324,6 +1505,7 @@ public class ObjectInputStream
}
depth++;
totalObjectRefs++;
try {
switch (tc) {
case TC_NULL:
......@@ -1400,6 +1582,15 @@ public class ObjectInputStream
}
Object rep = resolveObject(obj);
if (rep != obj) {
// The type of the original object has been filtered but resolveObject
// may have replaced it; filter the replacement's type
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, rep);
}
return rep;
......@@ -1470,6 +1661,7 @@ public class ObjectInputStream
throw new InvalidObjectException(
"cannot read back reference to unshared object");
}
filterCheck(null, -1); // just a check for number of references, depth, no class
return obj;
}
......@@ -1574,6 +1766,10 @@ public class ObjectInputStream
ReflectUtil.checkProxyPackageAccess(
getClass().getClassLoader(),
cl.getInterfaces());
// Filter the interfaces
for (Class<?> clazz : cl.getInterfaces()) {
filterCheck(clazz, -1);
}
}
} catch (ClassNotFoundException ex) {
resolveEx = ex;
......@@ -1582,6 +1778,9 @@ public class ObjectInputStream
desc.initProxy(cl, resolveEx, readClassDesc(false));
// Call filterCheck on the definition
filterCheck(desc.forClass(), -1);
handles.finish(descHandle);
passHandle = descHandle;
return desc;
......@@ -1629,8 +1828,12 @@ public class ObjectInputStream
desc.initNonProxy(readDesc, cl, resolveEx, readClassDesc(false));
// Call filterCheck on the definition
filterCheck(desc.forClass(), -1);
handles.finish(descHandle);
passHandle = descHandle;
return desc;
}
......@@ -1671,6 +1874,8 @@ public class ObjectInputStream
ObjectStreamClass desc = readClassDesc(false);
int len = bin.readInt();
filterCheck(desc.forClass(), len);
Object array = null;
Class<?> cl, ccl = null;
if ((cl = desc.forClass()) != null) {
......@@ -1819,6 +2024,14 @@ public class ObjectInputStream
rep = cloneArray(rep);
}
if (rep != obj) {
// Filter the replacement object
if (rep != null) {
if (rep.getClass().isArray()) {
filterCheck(rep.getClass(), Array.getLength(rep));
} else {
filterCheck(rep.getClass(), -1);
}
}
handles.setObject(passHandle, obj = rep);
}
}
......@@ -2009,22 +2222,22 @@ public class ObjectInputStream
desc.setPrimFieldValues(obj, primVals);
}
int objHandle = passHandle;
ObjectStreamField[] fields = desc.getFields(false);
int objHandle = passHandle;
ObjectStreamField[] fields = desc.getFields(false);
Object[] objVals = new Object[desc.getNumObjFields()];
int numPrimFields = fields.length - objVals.length;
for (int i = 0; i < objVals.length; i++) {
ObjectStreamField f = fields[numPrimFields + i];
objVals[i] = readObject0(f.isUnshared());
if (f.getField() != null) {
handles.markDependency(objHandle, passHandle);
}
int numPrimFields = fields.length - objVals.length;
for (int i = 0; i < objVals.length; i++) {
ObjectStreamField f = fields[numPrimFields + i];
objVals[i] = readObject0(f.isUnshared());
if (f.getField() != null) {
handles.markDependency(objHandle, passHandle);
}
}
if (obj != null) {
desc.setObjFieldValues(obj, objVals);
}
passHandle = objHandle;
}
passHandle = objHandle;
}
/**
* Reads in and returns IOException that caused serialization to abort.
......@@ -2296,6 +2509,51 @@ public class ObjectInputStream
}
}
/**
* Hold a snapshot of values to be passed to an ObjectInputFilter.
*/
static class FilterValues implements ObjectInputFilter.FilterInfo {
final Class<?> clazz;
final long arrayLength;
final long totalObjectRefs;
final long depth;
final long streamBytes;
public FilterValues(Class<?> clazz, long arrayLength, long totalObjectRefs,
long depth, long streamBytes) {
this.clazz = clazz;
this.arrayLength = arrayLength;
this.totalObjectRefs = totalObjectRefs;
this.depth = depth;
this.streamBytes = streamBytes;
}
@Override
public Class<?> serialClass() {
return clazz;
}
@Override
public long arrayLength() {
return arrayLength;
}
@Override
public long references() {
return totalObjectRefs;
}
@Override
public long depth() {
return depth;
}
@Override
public long streamBytes() {
return streamBytes;
}
}
/**
* Input stream supporting single-byte peek operations.
*/
......@@ -2305,6 +2563,8 @@ public class ObjectInputStream
private final InputStream in;
/** peeked byte */
private int peekb = -1;
/** total bytes read from the stream */
private long totalBytesRead = 0;
/**
* Creates new PeekInputStream on top of given underlying stream.
......@@ -2318,7 +2578,12 @@ public class ObjectInputStream
* that it does not consume the read value.
*/
int peek() throws IOException {
return (peekb >= 0) ? peekb : (peekb = in.read());
if (peekb >= 0) {
return peekb;
}
peekb = in.read();
totalBytesRead += peekb >= 0 ? 1 : 0;
return peekb;
}
public int read() throws IOException {
......@@ -2327,21 +2592,27 @@ public class ObjectInputStream
peekb = -1;
return v;
} else {
return in.read();
int nbytes = in.read();
totalBytesRead += nbytes >= 0 ? 1 : 0;
return nbytes;
}
}
public int read(byte[] b, int off, int len) throws IOException {
int nbytes;
if (len == 0) {
return 0;
} else if (peekb < 0) {
return in.read(b, off, len);
nbytes = in.read(b, off, len);
totalBytesRead += nbytes >= 0 ? nbytes : 0;
return nbytes;
} else {
b[off++] = (byte) peekb;
len--;
peekb = -1;
int n = in.read(b, off, len);
return (n >= 0) ? (n + 1) : 1;
nbytes = in.read(b, off, len);
totalBytesRead += nbytes >= 0 ? nbytes : 0;
return (nbytes >= 0) ? (nbytes + 1) : 1;
}
}
......@@ -2366,7 +2637,9 @@ public class ObjectInputStream
skipped++;
n--;
}
return skipped + skip(n);
n = skipped + in.skip(n);
totalBytesRead += n;
return n;
}
public int available() throws IOException {
......@@ -2376,6 +2649,10 @@ public class ObjectInputStream
public void close() throws IOException {
in.close();
}
public long getBytesRead() {
return totalBytesRead;
}
}
/**
......@@ -3231,6 +3508,14 @@ public class ObjectInputStream
throw new UTFDataFormatException();
}
}
/**
* Returns the number of bytes read from the input stream.
* @return the number of bytes read from the input stream
*/
long getBytesRead() {
return in.getBytesRead();
}
}
/**
......
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2016, 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
......@@ -155,11 +155,12 @@ class SocketInputStream extends FileInputStream
}
// bounds check
if (length <= 0 || off < 0 || off + length > b.length) {
if (length <= 0 || off < 0 || length > b.length - off) {
if (length == 0) {
return 0;
}
throw new ArrayIndexOutOfBoundsException();
throw new ArrayIndexOutOfBoundsException("length == " + length
+ " off == " + off + " buffer length == " + b.length);
}
boolean gotReset = false;
......
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995, 2016, 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
......@@ -97,11 +97,13 @@ class SocketOutputStream extends FileOutputStream
*/
private void socketWrite(byte b[], int off, int len) throws IOException {
if (len <= 0 || off < 0 || off + len > b.length) {
if (len <= 0 || off < 0 || len > b.length - off) {
if (len == 0) {
return;
}
throw new ArrayIndexOutOfBoundsException();
throw new ArrayIndexOutOfBoundsException("len == " + len
+ " off == " + off + " buffer length == " + b.length);
}
FileDescriptor fd = impl.acquireFD();
......
......@@ -1364,9 +1364,6 @@ public final class URL implements java.io.Serializable {
path = file;
}
if (port == -1) {
port = 0;
}
// Set the object fields.
this.protocol = protocol;
this.host = host;
......
......@@ -103,8 +103,8 @@ public class URLClassLoader extends SecureClassLoader implements Closeable {
if (security != null) {
security.checkCreateClassLoader();
}
ucp = new URLClassPath(urls);
this.acc = AccessController.getContext();
ucp = new URLClassPath(urls, acc);
}
URLClassLoader(URL[] urls, ClassLoader parent,
......@@ -115,8 +115,8 @@ public class URLClassLoader extends SecureClassLoader implements Closeable {
if (security != null) {
security.checkCreateClassLoader();
}
ucp = new URLClassPath(urls);
this.acc = acc;
ucp = new URLClassPath(urls, acc);
}
/**
......@@ -147,8 +147,8 @@ public class URLClassLoader extends SecureClassLoader implements Closeable {
if (security != null) {
security.checkCreateClassLoader();
}
ucp = new URLClassPath(urls);
this.acc = AccessController.getContext();
ucp = new URLClassPath(urls, acc);
}
URLClassLoader(URL[] urls, AccessControlContext acc) {
......@@ -158,8 +158,8 @@ public class URLClassLoader extends SecureClassLoader implements Closeable {
if (security != null) {
security.checkCreateClassLoader();
}
ucp = new URLClassPath(urls);
this.acc = acc;
ucp = new URLClassPath(urls, acc);
}
/**
......@@ -191,8 +191,8 @@ public class URLClassLoader extends SecureClassLoader implements Closeable {
if (security != null) {
security.checkCreateClassLoader();
}
ucp = new URLClassPath(urls, factory);
acc = AccessController.getContext();
ucp = new URLClassPath(urls, factory, acc);
}
/* A map (used as a set) to keep track of closeable local resources
......
......@@ -161,9 +161,9 @@ public abstract class URLStreamHandler {
(spec.charAt(start + 1) == '/')) {
start += 2;
i = spec.indexOf('/', start);
if (i < 0) {
if (i < 0 || i > limit) {
i = spec.indexOf('?', start);
if (i < 0)
if (i < 0 || i > limit)
i = limit;
}
......@@ -171,8 +171,14 @@ public abstract class URLStreamHandler {
int ind = authority.indexOf('@');
if (ind != -1) {
userInfo = authority.substring(0, ind);
host = authority.substring(ind+1);
if (ind != authority.lastIndexOf('@')) {
// more than one '@' in authority. This is not server based
userInfo = null;
host = null;
} else {
userInfo = authority.substring(0, ind);
host = authority.substring(ind+1);
}
} else {
userInfo = null;
}
......
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2016, 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
......@@ -34,9 +34,14 @@ import java.io.ObjectOutputStream;
import java.io.ObjectStreamConstants;
import java.io.OutputStream;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.rmi.server.MarshalInputStream;
import sun.rmi.server.MarshalOutputStream;
import sun.misc.ObjectInputFilter;
/**
* A <code>MarshalledObject</code> contains a byte stream with the serialized
* representation of an object given to its constructor. The <code>get</code>
......@@ -90,6 +95,9 @@ public final class MarshalledObject<T> implements Serializable {
*/
private int hash;
/** Filter used when creating the instance from a stream; may be null. */
private transient ObjectInputFilter objectInputFilter = null;
/** Indicate compatibility with 1.2 version of class. */
private static final long serialVersionUID = 8988374069173025854L;
......@@ -132,6 +140,20 @@ public final class MarshalledObject<T> implements Serializable {
hash = h;
}
/**
* Reads in the state of the object and saves the stream's
* serialization filter to be used when the object is deserialized.
*
* @param stream the stream
* @throws IOException if an I/O error occurs
* @throws ClassNotFoundException if a class cannot be found
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject(); // read in all fields
objectInputFilter = ObjectInputFilter.Config.getObjectInputFilter(stream);
}
/**
* Returns a new copy of the contained marshalledobject. The internal
* representation is deserialized with the semantics used for
......@@ -155,7 +177,7 @@ public final class MarshalledObject<T> implements Serializable {
ByteArrayInputStream lin =
(locBytes == null ? null : new ByteArrayInputStream(locBytes));
MarshalledObjectInputStream in =
new MarshalledObjectInputStream(bin, lin);
new MarshalledObjectInputStream(bin, lin, objectInputFilter);
@SuppressWarnings("unchecked")
T obj = (T) in.readObject();
in.close();
......@@ -295,11 +317,24 @@ public final class MarshalledObject<T> implements Serializable {
* <code>null</code>, then all annotations will be
* <code>null</code>.
*/
MarshalledObjectInputStream(InputStream objIn, InputStream locIn)
MarshalledObjectInputStream(InputStream objIn, InputStream locIn,
ObjectInputFilter filter)
throws IOException
{
super(objIn);
this.locIn = (locIn == null ? null : new ObjectInputStream(locIn));
if (filter != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this, filter);
if (MarshalledObjectInputStream.this.locIn != null) {
ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this.locIn, filter);
}
return null;
}
});
}
}
/**
......
......@@ -40,6 +40,7 @@ import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Objects;
import java.util.function.IntBinaryOperator;
import java.util.function.IntUnaryOperator;
import sun.reflect.CallerSensitive;
......@@ -410,7 +411,17 @@ public abstract class AtomicIntegerFieldUpdater<T> {
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
......@@ -431,6 +442,21 @@ public abstract class AtomicIntegerFieldUpdater<T> {
return false;
}
/**
* Returns true if the two classes have the same class loader and
* package qualifier
*/
private static boolean isSamePackage(Class<?> class1, Class<?> class2) {
return class1.getClassLoader() == class2.getClassLoader()
&& Objects.equals(getPackageName(class1), getPackageName(class2));
}
private static String getPackageName(Class<?> cls) {
String cn = cls.getName();
int dot = cn.lastIndexOf('.');
return (dot != -1) ? cn.substring(0, dot) : "";
}
/**
* Checks that target argument is instance of cclass. On
* failure, throws cause.
......
......@@ -40,6 +40,7 @@ import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Objects;
import java.util.function.LongBinaryOperator;
import java.util.function.LongUnaryOperator;
import sun.reflect.CallerSensitive;
......@@ -408,7 +409,17 @@ public abstract class AtomicLongFieldUpdater<T> {
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
......@@ -539,7 +550,17 @@ public abstract class AtomicLongFieldUpdater<T> {
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.offset = U.objectFieldOffset(field);
}
......@@ -620,4 +641,19 @@ public abstract class AtomicLongFieldUpdater<T> {
} while (acl != null);
return false;
}
/**
* Returns true if the two classes have the same class loader and
* package qualifier
*/
private static boolean isSamePackage(Class<?> class1, Class<?> class2) {
return class1.getClassLoader() == class2.getClassLoader()
&& Objects.equals(getPackageName(class1), getPackageName(class2));
}
private static String getPackageName(Class<?> cls) {
String cn = cls.getName();
int dot = cn.lastIndexOf('.');
return (dot != -1) ? cn.substring(0, dot) : "";
}
}
......@@ -40,6 +40,7 @@ import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Objects;
import java.util.function.BinaryOperator;
import java.util.function.UnaryOperator;
import sun.reflect.CallerSensitive;
......@@ -346,7 +347,17 @@ public abstract class AtomicReferenceFieldUpdater<T,V> {
if (!Modifier.isVolatile(modifiers))
throw new IllegalArgumentException("Must be volatile type");
this.cclass = (Modifier.isProtected(modifiers)) ? caller : tclass;
// Access to protected field members is restricted to receivers only
// of the accessing class, or one of its subclasses, and the
// accessing class must in turn be a subclass (or package sibling)
// of the protected member's defining class.
// If the updater refers to a protected field of a declaring class
// outside the current package, the receiver argument will be
// narrowed to the type of the accessing class.
this.cclass = (Modifier.isProtected(modifiers) &&
tclass.isAssignableFrom(caller) &&
!isSamePackage(tclass, caller))
? caller : tclass;
this.tclass = tclass;
this.vclass = vclass;
this.offset = U.objectFieldOffset(field);
......@@ -368,6 +379,21 @@ public abstract class AtomicReferenceFieldUpdater<T,V> {
return false;
}
/**
* Returns true if the two classes have the same class loader and
* package qualifier
*/
private static boolean isSamePackage(Class<?> class1, Class<?> class2) {
return class1.getClassLoader() == class2.getClassLoader()
&& Objects.equals(getPackageName(class1), getPackageName(class2));
}
private static String getPackageName(Class<?> cls) {
String cn = cls.getName();
int dot = cn.lastIndexOf('.');
return (dot != -1) ? cn.substring(0, dot) : "";
}
/**
* Checks that target argument is instance of cclass. On
* failure, throws cause.
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2016, 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
......@@ -599,11 +599,14 @@ public class Level implements java.io.Serializable {
if (list != null) {
for (KnownLevel level : list) {
Level other = level.mirroredLevel;
Class<? extends Level> type = level.levelObject.getClass();
if (l.value == other.value &&
(l.resourceBundleName == other.resourceBundleName ||
(l.resourceBundleName != null &&
l.resourceBundleName.equals(other.resourceBundleName)))) {
return level;
if (type == l.getClass()) {
return level;
}
}
}
}
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2016, 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
......@@ -502,13 +502,21 @@ public class LogRecord implements java.io.Serializable {
throw new IOException("LogRecord: bad version: " + major + "." + minor);
}
int len = in.readInt();
if (len == -1) {
if (len < -1) {
throw new NegativeArraySizeException();
} else if (len == -1) {
parameters = null;
} else {
} else if (len < 255) {
parameters = new Object[len];
for (int i = 0; i < parameters.length; i++) {
parameters[i] = in.readObject();
}
} else {
List<Object> params = new ArrayList<>(Math.min(len, 1024));
for (int i = 0; i < len; i++) {
params.add(in.readObject());
}
parameters = params.toArray(new Object[params.size()]);
}
// If necessary, try to regenerate the resource bundle.
if (resourceBundleName != null) {
......
/*
* Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2002, 2016, 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
......@@ -349,7 +349,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
+", unwrapping parameters using classLoaderWithRepository.");
values =
nullIsEmpty(unwrap(params, classLoaderWithRepository, Object[].class));
nullIsEmpty(unwrap(params, classLoaderWithRepository, Object[].class,delegationSubject));
try {
final Object params2[] =
......@@ -413,7 +413,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
values = nullIsEmpty(unwrap(params,
getClassLoader(loaderName),
defaultClassLoader,
Object[].class));
Object[].class,delegationSubject));
try {
final Object params2[] =
......@@ -524,7 +524,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class);
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class, delegationSubject);
try {
final Object params[] = new Object[] { name, queryValue };
......@@ -559,7 +559,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
"connectionId=" + connectionId
+" unwrapping query with defaultClassLoader.");
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class);
queryValue = unwrap(query, defaultContextClassLoader, QueryExp.class, delegationSubject);
try {
final Object params[] = new Object[] { name, queryValue };
......@@ -709,7 +709,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
attr = unwrap(attribute,
getClassLoaderFor(name),
defaultClassLoader,
Attribute.class);
Attribute.class, delegationSubject);
try {
final Object params[] = new Object[] { name, attr };
......@@ -760,7 +760,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
unwrap(attributes,
getClassLoaderFor(name),
defaultClassLoader,
AttributeList.class);
AttributeList.class, delegationSubject);
try {
final Object params[] = new Object[] { name, attrlist };
......@@ -812,7 +812,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
values = nullIsEmpty(unwrap(params,
getClassLoaderFor(name),
defaultClassLoader,
Object[].class));
Object[].class, delegationSubject));
try {
final Object params2[] =
......@@ -992,7 +992,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
filterValues[i] =
unwrap(filters[i], targetCl, defaultClassLoader,
NotificationFilter.class);
NotificationFilter.class, sbjs[i]);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,NotificationFilter)",
......@@ -1060,7 +1060,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
+" unwrapping filter with target extended ClassLoader.");
filterValue =
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class);
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class, delegationSubject);
if (debug) logger.debug("addNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
......@@ -1068,7 +1068,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
+" unwrapping handback with target extended ClassLoader.");
handbackValue =
unwrap(handback, targetCl, defaultClassLoader, Object.class);
unwrap(handback, targetCl, defaultClassLoader, Object.class, delegationSubject);
try {
final Object params[] =
......@@ -1199,7 +1199,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
+" unwrapping filter with target extended ClassLoader.");
filterValue =
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class);
unwrap(filter, targetCl, defaultClassLoader, NotificationFilter.class, delegationSubject);
if (debug) logger.debug("removeNotificationListener"+
"(ObjectName,ObjectName,NotificationFilter,Object)",
......@@ -1207,7 +1207,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
+" unwrapping handback with target extended ClassLoader.");
handbackValue =
unwrap(handback, targetCl, defaultClassLoader, Object.class);
unwrap(handback, targetCl, defaultClassLoader, Object.class, delegationSubject);
try {
final Object params[] =
......@@ -1551,20 +1551,38 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
}
}
private static <T> T unwrap(final MarshalledObject<?> mo,
private <T> T unwrap(final MarshalledObject<?> mo,
final ClassLoader cl,
final Class<T> wrappedClass)
final Class<T> wrappedClass,
Subject delegationSubject)
throws IOException {
if (mo == null) {
return null;
}
try {
final ClassLoader old = AccessController.doPrivileged(new SetCcl(cl));
try {
return wrappedClass.cast(mo.get());
} catch (ClassNotFoundException cnfe) {
throw new UnmarshalException(cnfe.toString(), cnfe);
} finally {
try{
final AccessControlContext reqACC;
if (delegationSubject == null)
reqACC = acc;
else {
if (subject == null) {
final String msg =
"Subject delegation cannot be enabled unless " +
"an authenticated subject is put in place";
throw new SecurityException(msg);
}
reqACC = subjectDelegator.delegatedContext(
acc, delegationSubject, removeCallerContext);
}
if(reqACC != null){
return AccessController.doPrivileged(
(PrivilegedExceptionAction<T>) () ->
wrappedClass.cast(mo.get()), reqACC);
}else{
return wrappedClass.cast(mo.get());
}
}finally{
AccessController.doPrivileged(new SetCcl(old));
}
} catch (PrivilegedActionException pe) {
......@@ -1577,14 +1595,19 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
}
logger.warning("unwrap", "Failed to unmarshall object: " + e);
logger.debug("unwrap", e);
}catch (ClassNotFoundException ex) {
logger.warning("unwrap", "Failed to unmarshall object: " + ex);
logger.debug("unwrap", ex);
throw new UnmarshalException(ex.toString(), ex);
}
return null;
}
private static <T> T unwrap(final MarshalledObject<?> mo,
private <T> T unwrap(final MarshalledObject<?> mo,
final ClassLoader cl1,
final ClassLoader cl2,
final Class<T> wrappedClass)
final Class<T> wrappedClass,
Subject delegationSubject)
throws IOException {
if (mo == null) {
return null;
......@@ -1598,7 +1621,7 @@ public class RMIConnectionImpl implements RMIConnection, Unreferenced {
}
}
);
return unwrap(mo, orderCL, wrappedClass);
return unwrap(mo, orderCL, wrappedClass,delegationSubject);
} catch (PrivilegedActionException pe) {
Exception e = extractException(pe);
if (e instanceof IOException) {
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: ApacheTransform.java 1333869 2012-05-04 10:42:44Z coheigea $
......@@ -38,7 +38,6 @@ import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.transforms.Transform;
import com.sun.org.apache.xml.internal.security.transforms.Transforms;
import javax.xml.crypto.*;
import javax.xml.crypto.dom.DOMCryptoContext;
......@@ -150,7 +149,7 @@ public abstract class ApacheTransform extends TransformService {
if (Utils.secureValidation(xc)) {
String algorithm = getAlgorithm();
if (Transforms.TRANSFORM_XSLT.equals(algorithm)) {
if (Policy.restrictAlg(algorithm)) {
throw new TransformException(
"Transform " + algorithm + " is forbidden when secure validation is enabled"
);
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: DOMManifest.java 1333415 2012-05-03 12:03:51Z coheigea $
......@@ -113,9 +113,10 @@ public final class DOMManifest extends DOMStructure implements Manifest {
localName + ", expected Reference");
}
refs.add(new DOMReference(refElem, context, provider));
if (secVal && (refs.size() > DOMSignedInfo.MAXIMUM_REFERENCE_COUNT)) {
String error = "A maxiumum of " + DOMSignedInfo.MAXIMUM_REFERENCE_COUNT + " "
+ "references per Manifest are allowed with secure validation";
if (secVal && Policy.restrictNumReferences(refs.size())) {
String error = "A maximum of " + Policy.maxReferences()
+ " references per Manifest are allowed when"
+ " secure validation is enabled";
throw new MarshalException(error);
}
refElem = DOMUtils.getNextSiblingElement(refElem);
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* ===========================================================================
......@@ -51,7 +51,6 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.jcp.xml.dsig.internal.DigesterOutputStream;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Base64;
......@@ -66,11 +65,6 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream
public final class DOMReference extends DOMStructure
implements Reference, DOMURIReference {
/**
* The maximum number of transforms per reference, if secure validation is enabled.
*/
public static final int MAXIMUM_TRANSFORM_COUNT = 5;
/**
* Look up useC14N11 system property. If true, an explicit C14N11 transform
* will be added if necessary when generating the signature. See section
......@@ -217,9 +211,10 @@ public final class DOMReference extends DOMStructure
}
transforms.add
(new DOMTransform(transformElem, context, provider));
if (secVal && (transforms.size() > MAXIMUM_TRANSFORM_COUNT)) {
String error = "A maxiumum of " + MAXIMUM_TRANSFORM_COUNT + " "
+ "transforms per Reference are allowed with secure validation";
if (secVal && Policy.restrictNumTransforms(transforms.size())) {
String error = "A maximum of " + Policy.maxTransforms()
+ " transforms per Reference are allowed when"
+ " secure validation is enabled";
throw new MarshalException(error);
}
transformElem = DOMUtils.getNextSiblingElement(transformElem);
......@@ -236,10 +231,10 @@ public final class DOMReference extends DOMStructure
Element dmElem = nextSibling;
this.digestMethod = DOMDigestMethod.unmarshal(dmElem);
String digestMethodAlgorithm = this.digestMethod.getAlgorithm();
if (secVal
&& MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(digestMethodAlgorithm)) {
if (secVal && Policy.restrictAlg(digestMethodAlgorithm)) {
throw new MarshalException(
"It is forbidden to use algorithm " + digestMethod + " when secure validation is enabled"
"It is forbidden to use algorithm " + digestMethodAlgorithm +
" when secure validation is enabled"
);
}
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* ===========================================================================
......@@ -154,9 +154,10 @@ public final class DOMRetrievalMethod extends DOMStructure
}
transforms.add
(new DOMTransform(transformElem, context, provider));
if (secVal && (transforms.size() > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
+ "transforms per Reference are allowed with secure validation";
if (secVal && Policy.restrictNumTransforms(transforms.size())) {
String error = "A maximum of " + Policy.maxTransforms()
+ " transforms per Reference are allowed when"
+ " secure validation is enabled";
throw new MarshalException(error);
}
transformElem = DOMUtils.getNextSiblingElement(transformElem);
......@@ -243,7 +244,8 @@ public final class DOMRetrievalMethod extends DOMStructure
}
// guard against RetrievalMethod loops
if ((data instanceof NodeSetData) && Utils.secureValidation(context)) {
if ((data instanceof NodeSetData) && Utils.secureValidation(context)
&& Policy.restrictRetrievalMethodLoops()) {
NodeSetData nsd = (NodeSetData)data;
Iterator i = nsd.iterator();
if (i.hasNext()) {
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: DOMSignatureMethod.java 1333415 2012-05-03 12:03:51Z coheigea $
......@@ -41,6 +41,7 @@ import org.w3c.dom.Element;
import com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureECDSA;
import com.sun.org.apache.xml.internal.security.utils.JavaUtils;
import org.jcp.xml.dsig.internal.SignerOutputStream;
import sun.security.util.KeyUtil;
/**
* DOM-based abstract implementation of SignatureMethod.
......@@ -162,6 +163,7 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
if (!(key instanceof PublicKey)) {
throw new InvalidKeyException("key must be PublicKey");
}
checkKeySize(context, key);
if (signature == null) {
try {
Provider p = (Provider)context.getProperty
......@@ -197,6 +199,37 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
}
}
/**
* If secure validation mode is enabled, checks that the key size is
* restricted.
*
* @param context the context
* @param key the key to check
* @throws XMLSignatureException if the key size is restricted
*/
private static void checkKeySize(XMLCryptoContext context, Key key)
throws XMLSignatureException {
if (Utils.secureValidation(context)) {
int size = KeyUtil.getKeySize(key);
if (size == -1) {
// key size cannot be determined, so we cannot check against
// restrictions. Note that a DSA key w/o params will be
// rejected later if the certificate chain is validated.
if (log.isLoggable(java.util.logging.Level.FINE)) {
log.log(java.util.logging.Level.FINE, "Size for " +
key.getAlgorithm() + " key cannot be determined");
}
return;
}
if (Policy.restrictKey(key.getAlgorithm(), size)) {
throw new XMLSignatureException(key.getAlgorithm() +
" keys less than " +
Policy.minKeySize(key.getAlgorithm()) + " bits are" +
" forbidden when secure validation is enabled");
}
}
}
byte[] sign(Key key, SignedInfo si, XMLSignContext context)
throws InvalidKeyException, XMLSignatureException
{
......@@ -207,6 +240,7 @@ public abstract class DOMSignatureMethod extends AbstractDOMSignatureMethod {
if (!(key instanceof PrivateKey)) {
throw new InvalidKeyException("key must be PrivateKey");
}
checkKeySize(context, key);
if (signature == null) {
try {
Provider p = (Provider)context.getProperty
......
......@@ -21,7 +21,7 @@
* under the License.
*/
/*
* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
*/
/*
* $Id: DOMSignedInfo.java 1333415 2012-05-03 12:03:51Z coheigea $
......@@ -45,7 +45,6 @@ import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
/**
......@@ -55,22 +54,9 @@ import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream
*/
public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
/**
* The maximum number of references per Manifest, if secure validation is enabled.
*/
public static final int MAXIMUM_REFERENCE_COUNT = 30;
private static java.util.logging.Logger log =
java.util.logging.Logger.getLogger("org.jcp.xml.dsig.internal.dom");
/** Signature - NOT Recommended RSAwithMD5 */
private static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 =
Constants.MoreAlgorithmsSpecNS + "rsa-md5";
/** HMAC - NOT Recommended HMAC-MD5 */
private static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 =
Constants.MoreAlgorithmsSpecNS + "hmac-md5";
private List<Reference> references;
private CanonicalizationMethod canonicalizationMethod;
private SignatureMethod signatureMethod;
......@@ -163,10 +149,10 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
boolean secVal = Utils.secureValidation(context);
String signatureMethodAlgorithm = signatureMethod.getAlgorithm();
if (secVal && ((ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5.equals(signatureMethodAlgorithm)
|| ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5.equals(signatureMethodAlgorithm)))) {
if (secVal && Policy.restrictAlg(signatureMethodAlgorithm)) {
throw new MarshalException(
"It is forbidden to use algorithm " + signatureMethod + " when secure validation is enabled"
"It is forbidden to use algorithm " + signatureMethodAlgorithm +
" when secure validation is enabled"
);
}
......@@ -184,9 +170,10 @@ public final class DOMSignedInfo extends DOMStructure implements SignedInfo {
}
refList.add(new DOMReference(refElem, context, provider));
if (secVal && (refList.size() > MAXIMUM_REFERENCE_COUNT)) {
String error = "A maxiumum of " + MAXIMUM_REFERENCE_COUNT + " "
+ "references per Manifest are allowed with secure validation";
if (secVal && Policy.restrictNumReferences(refList.size())) {
String error = "A maximum of " + Policy.maxReferences()
+ " references per Manifest are allowed when"
+ " secure validation is enabled";
throw new MarshalException(error);
}
refElem = DOMUtils.getNextSiblingElement(refElem);
......
......@@ -73,6 +73,11 @@ public class DOMURIDereferencer implements URIDereferencer {
boolean secVal = Utils.secureValidation(context);
if (secVal && Policy.restrictReferenceUriScheme(uri)) {
throw new URIReferenceException(
"Uri " + uri + " is forbidden when secure validation is enabled");
}
// Check if same-document URI and already registered on the context
if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
String id = uri.substring(1);
......@@ -83,12 +88,19 @@ public class DOMURIDereferencer implements URIDereferencer {
id = id.substring(i1+1, i2);
}
Node referencedElem = dcc.getElementById(id);
// check if element is registered by Id
Node referencedElem = uriAttr.getOwnerDocument().getElementById(id);
if (referencedElem == null) {
// see if element is registered in DOMCryptoContext
referencedElem = dcc.getElementById(id);
}
if (referencedElem != null) {
if (secVal) {
if (secVal && Policy.restrictDuplicateIds()) {
Element start = referencedElem.getOwnerDocument().getDocumentElement();
if (!XMLUtils.protectAgainstWrappingAttack(start, (Element)referencedElem, id)) {
String error = "Multiple Elements with the same ID " + id + " were detected";
String error = "Multiple Elements with the same ID "
+ id + " detected when secure validation"
+ " is enabled";
throw new URIReferenceException(error);
}
}
......@@ -110,9 +122,9 @@ public class DOMURIDereferencer implements URIDereferencer {
try {
ResourceResolver apacheResolver =
ResourceResolver.getInstance(uriAttr, baseURI, secVal);
ResourceResolver.getInstance(uriAttr, baseURI, false);
XMLSignatureInput in = apacheResolver.resolve(uriAttr,
baseURI, secVal);
baseURI, false);
if (in.isOctetStream()) {
return new ApacheOctetStreamData(in);
} else {
......
/*
* Copyright (c) 2016, 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 org.jcp.xml.dsig.internal.dom;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.Security;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* The secure validation policy as specified by the
* jdk.xml.dsig.secureValidationPolicy security property.
*/
public final class Policy {
// all restrictions are initialized to be unconstrained
private static Set<URI> disallowedAlgs = new HashSet<>();
private static int maxTrans = Integer.MAX_VALUE;
private static int maxRefs = Integer.MAX_VALUE;
private static Set<String> disallowedRefUriSchemes = new HashSet<>();
private static Map<String, Integer> minKeyMap = new HashMap<>();
private static boolean noDuplicateIds = false;
private static boolean noRMLoops = false;
static {
try {
initialize();
} catch (Exception e) {
throw new SecurityException(
"Cannot initialize the secure validation policy", e);
}
}
private Policy() {}
private static void initialize() {
String prop =
AccessController.doPrivileged((PrivilegedAction<String>) () ->
Security.getProperty("jdk.xml.dsig.secureValidationPolicy"));
if (prop == null || prop.isEmpty()) {
// no policy specified, so don't enforce any restrictions
return;
}
String[] entries = prop.split(",");
for (String entry : entries) {
String[] tokens = entry.split("\\s");
String type = tokens[0];
switch(type) {
case "disallowAlg":
if (tokens.length != 2) {
error(entry);
}
disallowedAlgs.add(URI.create(tokens[1]));
break;
case "maxTransforms":
if (tokens.length != 2) {
error(entry);
}
maxTrans = Integer.parseUnsignedInt(tokens[1]);
break;
case "maxReferences":
if (tokens.length != 2) {
error(entry);
}
maxRefs = Integer.parseUnsignedInt(tokens[1]);
break;
case "disallowReferenceUriSchemes":
if (tokens.length == 1) {
error(entry);
}
for (int i = 1; i < tokens.length; i++) {
String scheme = tokens[i];
disallowedRefUriSchemes.add(
scheme.toLowerCase(Locale.ROOT));
}
break;
case "minKeySize":
if (tokens.length != 3) {
error(entry);
}
minKeyMap.put(tokens[1],
Integer.parseUnsignedInt(tokens[2]));
break;
case "noDuplicateIds":
if (tokens.length != 1) {
error(entry);
}
noDuplicateIds = true;
break;
case "noRetrievalMethodLoops":
if (tokens.length != 1) {
error(entry);
}
noRMLoops = true;
break;
default:
error(entry);
}
}
}
public static boolean restrictAlg(String alg) {
try {
URI uri = new URI(alg);
return disallowedAlgs.contains(uri);
} catch (URISyntaxException use) {
return false;
}
}
public static boolean restrictNumTransforms(int numTrans) {
return (numTrans > maxTrans);
}
public static boolean restrictNumReferences(int numRefs) {
return (numRefs > maxRefs);
}
public static boolean restrictReferenceUriScheme(String uri) {
if (uri != null) {
String scheme = java.net.URI.create(uri).getScheme();
if (scheme != null) {
return disallowedRefUriSchemes.contains(
scheme.toLowerCase(Locale.ROOT));
}
}
return false;
}
public static boolean restrictKey(String type, int size) {
return (size < minKeyMap.getOrDefault(type, 0));
}
public static boolean restrictDuplicateIds() {
return noDuplicateIds;
}
public static boolean restrictRetrievalMethodLoops() {
return noRMLoops;
}
public static Set<URI> disabledAlgs() {
return Collections.<URI>unmodifiableSet(disallowedAlgs);
}
public static int maxTransforms() {
return maxTrans;
}
public static int maxReferences() {
return maxRefs;
}
public static Set<String> disabledReferenceUriSchemes() {
return Collections.<String>unmodifiableSet(disallowedRefUriSchemes);
}
public static int minKeySize(String type) {
return minKeyMap.getOrDefault(type, 0);
}
private static void error(String entry) {
throw new IllegalArgumentException(
"Invalid jdk.xml.dsig.secureValidationPolicy entry: " + entry);
}
}
......@@ -36,6 +36,7 @@ import java.awt.event.InvocationEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.awt.peer.ComponentPeer;
import java.awt.peer.MenuComponentPeer;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessControlContext;
......@@ -469,6 +470,11 @@ public final class AWTAccessor {
* Gets the font used for this menu component.
*/
Font getFont_NoClientCode(MenuComponent menuComp);
/**
* Returns the peer of the menu component.
*/
<T extends MenuComponentPeer> T getPeer(MenuComponent menuComp);
}
/**
......
/*
* Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2016, 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
......@@ -26,9 +26,11 @@
package sun.misc;
import java.io.*;
import java.security.AccessController;
import java.util.*;
import java.util.jar.*;
import java.util.zip.*;
import sun.security.action.GetPropertyAction;
/**
* This class is used to maintain mappings from packages, classes
......@@ -72,7 +74,8 @@ public class JarIndex {
* be added to the index. Otherwise, just the directory names are added.
*/
private static final boolean metaInfFilenames =
"true".equals(System.getProperty("sun.misc.JarIndex.metaInfFilenames"));
"true".equals(AccessController.doPrivileged(
new GetPropertyAction("sun.misc.JarIndex.metaInfFilenames")));
/**
* Constructs a new, empty jar index.
......
/*
* Copyright (c) 2016, 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.misc;
import java.io.ObjectInputStream;
public interface JavaOISAccess {
void setObjectInputFilter(ObjectInputStream stream, ObjectInputFilter filter);
ObjectInputFilter getObjectInputFilter(ObjectInputStream stream);
}
......@@ -408,7 +408,7 @@ public class Launcher {
} else {
urls = new URL[0];
}
bcp = new URLClassPath(urls, factory);
bcp = new URLClassPath(urls, factory, null);
bcp.initLookupCache(null);
}
}
......
此差异已折叠。
......@@ -25,6 +25,7 @@
package sun.misc;
import java.io.ObjectInputStream;
import java.util.jar.JarFile;
import java.io.Console;
import java.io.FileDescriptor;
......@@ -56,6 +57,7 @@ public class SharedSecrets {
private static JavaSecurityAccess javaSecurityAccess;
private static JavaUtilZipFileAccess javaUtilZipFileAccess;
private static JavaAWTAccess javaAWTAccess;
private static JavaOISAccess javaOISAccess;
private static JavaObjectInputStreamAccess javaObjectInputStreamAccess;
public static JavaUtilJarAccess javaUtilJarAccess() {
......@@ -141,6 +143,18 @@ public class SharedSecrets {
return javaIOFileDescriptorAccess;
}
public static void setJavaOISAccess(JavaOISAccess access) {
javaOISAccess = access;
}
public static JavaOISAccess getJavaOISAccess() {
if (javaOISAccess == null)
unsafe.ensureClassInitialized(ObjectInputStream.class);
return javaOISAccess;
}
public static void setJavaSecurityProtectionDomainAccess
(JavaSecurityProtectionDomainAccess jspda) {
javaSecurityProtectionDomainAccess = jspda;
......
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2016, 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
......@@ -44,6 +44,7 @@ import java.net.HttpURLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.io.*;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.AccessControlException;
import java.security.CodeSigner;
......@@ -67,6 +68,7 @@ public class URLClassPath {
private static final boolean DEBUG;
private static final boolean DEBUG_LOOKUP_CACHE;
private static final boolean DISABLE_JAR_CHECKING;
private static final boolean DISABLE_ACC_CHECKING;
static {
JAVA_VERSION = java.security.AccessController.doPrivileged(
......@@ -78,6 +80,10 @@ public class URLClassPath {
String p = java.security.AccessController.doPrivileged(
new GetPropertyAction("sun.misc.URLClassPath.disableJarChecking"));
DISABLE_JAR_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
p = AccessController.doPrivileged(
new GetPropertyAction("jdk.net.URLClassPath.disableRestrictedPermissions"));
DISABLE_ACC_CHECKING = p != null ? p.equals("true") || p.equals("") : false;
}
/* The original search path of URLs. */
......@@ -98,6 +104,11 @@ public class URLClassPath {
/* Whether this URLClassLoader has been closed yet */
private boolean closed = false;
/* The context to be used when loading classes and resources. If non-null
* this is the context that was captured during the creation of the
* URLClassLoader. null implies no additional security restrictions. */
private final AccessControlContext acc;
/**
* Creates a new URLClassPath for the given URLs. The URLs will be
* searched in the order specified for classes and resources. A URL
......@@ -107,8 +118,12 @@ public class URLClassPath {
* @param urls the directory and JAR file URLs to search for classes
* and resources
* @param factory the URLStreamHandlerFactory to use when creating new URLs
* @param acc the context to be used when loading classes and resources, may
* be null
*/
public URLClassPath(URL[] urls, URLStreamHandlerFactory factory) {
public URLClassPath(URL[] urls,
URLStreamHandlerFactory factory,
AccessControlContext acc) {
for (int i = 0; i < urls.length; i++) {
path.add(urls[i]);
}
......@@ -116,10 +131,22 @@ public class URLClassPath {
if (factory != null) {
jarHandler = factory.createURLStreamHandler("jar");
}
if (DISABLE_ACC_CHECKING)
this.acc = null;
else
this.acc = acc;
}
/**
* Constructs a URLClassPath with no additional security restrictions.
* Used by code that implements the class path.
*/
public URLClassPath(URL[] urls) {
this(urls, null);
this(urls, null, null);
}
public URLClassPath(URL[] urls, AccessControlContext acc) {
this(urls, null, acc);
}
public synchronized List<IOException> closeLoaders() {
......@@ -499,6 +526,14 @@ public class URLClassPath {
} catch (IOException e) {
// Silently ignore for now...
continue;
} catch (SecurityException se) {
// Always silently ignore. The context, if there is one, that
// this URLClassPath was given during construction will never
// have permission to access the URL.
if (DEBUG) {
System.err.println("Failed to access " + url + ", " + se );
}
continue;
}
// Finally, add the Loader to the search path.
validateLookupCache(loaders.size(), urlNoFragString);
......@@ -527,10 +562,10 @@ public class URLClassPath {
return new Loader(url);
}
} else {
return new JarLoader(url, jarHandler, lmap);
return new JarLoader(url, jarHandler, lmap, acc);
}
}
});
}, acc);
} catch (java.security.PrivilegedActionException pae) {
throw (IOException)pae.getException();
}
......@@ -755,11 +790,12 @@ public class URLClassPath {
*/
static class JarLoader extends Loader {
private JarFile jar;
private URL csu;
private final URL csu;
private JarIndex index;
private MetaIndex metaIndex;
private URLStreamHandler handler;
private HashMap<String, Loader> lmap;
private final HashMap<String, Loader> lmap;
private final AccessControlContext acc;
private boolean closed = false;
private static final sun.misc.JavaUtilZipFileAccess zipAccess =
sun.misc.SharedSecrets.getJavaUtilZipFileAccess();
......@@ -769,13 +805,15 @@ public class URLClassPath {
* a JAR file.
*/
JarLoader(URL url, URLStreamHandler jarHandler,
HashMap<String, Loader> loaderMap)
HashMap<String, Loader> loaderMap,
AccessControlContext acc)
throws IOException
{
super(new URL("jar", "", -1, url + "!/", jarHandler));
csu = url;
handler = jarHandler;
lmap = loaderMap;
this.acc = acc;
if (!isOptimizable(url)) {
ensureOpen();
......@@ -859,8 +897,7 @@ public class URLClassPath {
}
return null;
}
}
);
}, acc);
} catch (java.security.PrivilegedActionException pae) {
throw (IOException)pae.getException();
}
......@@ -1054,9 +1091,9 @@ public class URLClassPath {
new PrivilegedExceptionAction<JarLoader>() {
public JarLoader run() throws IOException {
return new JarLoader(url, handler,
lmap);
lmap, acc);
}
});
}, acc);
/* this newly opened jar file has its own index,
* merge it into the parent's index, taking into
......
/*
* Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2016, 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
......@@ -30,11 +30,9 @@ import java.util.Hashtable;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.io.FilePermission;
import java.io.IOException;
import java.net.*;
import java.rmi.*;
import java.rmi.server.ObjID;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
......@@ -47,14 +45,18 @@ import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.Security;
import java.text.MessageFormat;
import sun.rmi.server.LoaderHandler;
import sun.misc.ObjectInputFilter;
import sun.rmi.runtime.Log;
import sun.rmi.server.UnicastRef;
import sun.rmi.server.UnicastServerRef;
import sun.rmi.server.UnicastServerRef2;
import sun.rmi.transport.LiveRef;
import sun.rmi.transport.ObjectTable;
import sun.rmi.transport.Target;
/**
* A "registry" exists on every node that allows RMI connections to
......@@ -85,6 +87,47 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
private static ResourceBundle resources = null;
/**
* Property name of the RMI Registry serial filter to augment
* the built-in list of allowed types.
* Setting the property in the {@code lib/security/java.security} file
* will enable the augmented filter.
*/
private static final String REGISTRY_FILTER_PROPNAME = "sun.rmi.registry.registryFilter";
/** Registry max depth of remote invocations. **/
private static int REGISTRY_MAX_DEPTH = 5;
/** Registry maximum array size in remote invocations. **/
private static int REGISTRY_MAX_ARRAY_SIZE = 10000;
/**
* The registryFilter created from the value of the {@code "sun.rmi.registry.registryFilter"}
* property.
*/
private static final ObjectInputFilter registryFilter =
AccessController.doPrivileged((PrivilegedAction<ObjectInputFilter>)RegistryImpl::initRegistryFilter);
/**
* Initialize the registryFilter from the security properties or system property; if any
* @return an ObjectInputFilter, or null
*/
private static ObjectInputFilter initRegistryFilter() {
ObjectInputFilter filter = null;
String props = System.getProperty(REGISTRY_FILTER_PROPNAME);
if (props == null) {
props = Security.getProperty(REGISTRY_FILTER_PROPNAME);
}
if (props != null) {
filter = ObjectInputFilter.Config.createFilter(props);
Log regLog = Log.getLog("sun.rmi.registry", "registry", -1);
if (regLog.isLoggable(Log.BRIEF)) {
regLog.log(Log.BRIEF, "registryFilter = " + filter);
}
}
return filter;
}
/**
* Construct a new RegistryImpl on the specified port with the
* given custom socket factory pair.
......@@ -100,7 +143,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws RemoteException {
LiveRef lref = new LiveRef(id, port, csf, ssf);
setup(new UnicastServerRef2(lref));
setup(new UnicastServerRef2(lref, RegistryImpl::registryFilter));
return null;
}
}, null, new SocketPermission("localhost:"+port, "listen,accept"));
......@@ -109,7 +152,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
}
} else {
LiveRef lref = new LiveRef(id, port, csf, ssf);
setup(new UnicastServerRef2(lref));
setup(new UnicastServerRef2(lref, RegistryImpl::registryFilter));
}
}
......@@ -125,7 +168,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
public Void run() throws RemoteException {
LiveRef lref = new LiveRef(id, port);
setup(new UnicastServerRef(lref));
setup(new UnicastServerRef(lref, RegistryImpl::registryFilter));
return null;
}
}, null, new SocketPermission("localhost:"+port, "listen,accept"));
......@@ -134,7 +177,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
}
} else {
LiveRef lref = new LiveRef(id, port);
setup(new UnicastServerRef(lref));
setup(new UnicastServerRef(lref, RegistryImpl::registryFilter));
}
}
......@@ -155,7 +198,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
/**
* Returns the remote object for specified name in the registry.
* @exception RemoteException If remote operation failed.
* @exception NotBound If name is not currently bound.
* @exception NotBoundException If name is not currently bound.
*/
public Remote lookup(String name)
throws RemoteException, NotBoundException
......@@ -188,7 +231,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
/**
* Unbind the name.
* @exception RemoteException If remote operation failed.
* @exception NotBound If name is not currently bound.
* @exception NotBoundException If name is not currently bound.
*/
public void unbind(String name)
throws RemoteException, NotBoundException, AccessException
......@@ -332,6 +375,60 @@ public class RegistryImpl extends java.rmi.server.RemoteServer
}
}
/**
* ObjectInputFilter to filter Registry input objects.
* The list of acceptable classes is limited to classes normally
* stored in a registry.
*
* @param filterInfo access to the class, array length, etc.
* @return {@link ObjectInputFilter.Status#ALLOWED} if allowed,
* {@link ObjectInputFilter.Status#REJECTED} if rejected,
* otherwise {@link ObjectInputFilter.Status#UNDECIDED}
*/
private static ObjectInputFilter.Status registryFilter(ObjectInputFilter.FilterInfo filterInfo) {
if (registryFilter != null) {
ObjectInputFilter.Status status = registryFilter.checkInput(filterInfo);
if (status != ObjectInputFilter.Status.UNDECIDED) {
// The Registry filter can override the built-in white-list
return status;
}
}
if (filterInfo.depth() > REGISTRY_MAX_DEPTH) {
return ObjectInputFilter.Status.REJECTED;
}
Class<?> clazz = filterInfo.serialClass();
if (clazz != null) {
if (clazz.isArray()) {
if (filterInfo.arrayLength() >= 0 && filterInfo.arrayLength() > REGISTRY_MAX_ARRAY_SIZE) {
return ObjectInputFilter.Status.REJECTED;
}
do {
// Arrays are allowed depending on the component type
clazz = clazz.getComponentType();
} while (clazz.isArray());
}
if (clazz.isPrimitive()) {
// Arrays of primitives are allowed
return ObjectInputFilter.Status.ALLOWED;
}
if (String.class == clazz
|| java.lang.Number.class.isAssignableFrom(clazz)
|| Remote.class.isAssignableFrom(clazz)
|| java.lang.reflect.Proxy.class.isAssignableFrom(clazz)
|| UnicastRef.class.isAssignableFrom(clazz)
|| RMIClientSocketFactory.class.isAssignableFrom(clazz)
|| RMIServerSocketFactory.class.isAssignableFrom(clazz)
|| java.rmi.activation.ActivationID.class.isAssignableFrom(clazz)
|| java.rmi.server.UID.class.isAssignableFrom(clazz)) {
return ObjectInputFilter.Status.ALLOWED;
} else {
return ObjectInputFilter.Status.REJECTED;
}
}
return ObjectInputFilter.Status.UNDECIDED;
}
/**
* Main program to start a registry. <br>
* The port number can be specified on the command line.
......
......@@ -27,6 +27,7 @@ package sun.rmi.server;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectStreamClass;
import java.lang.reflect.InvocationTargetException;
......@@ -53,8 +54,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import sun.misc.ObjectInputFilter;
import sun.rmi.runtime.Log;
import static sun.rmi.server.UnicastRef.marshalValue;
import sun.rmi.transport.LiveRef;
import sun.rmi.transport.Target;
import sun.rmi.transport.tcp.TCPTransport;
......@@ -64,6 +65,10 @@ import sun.security.action.GetBooleanAction;
* UnicastServerRef implements the remote reference layer server-side
* behavior for remote objects exported with the "UnicastRef" reference
* type.
* If an {@link ObjectInputFilter ObjectInputFilter} is supplied it is
* invoked during deserialization to filter the arguments,
* otherwise the default filter of {@link ObjectInputStream ObjectInputStream}
* applies.
*
* @author Ann Wollrath
* @author Roger Riggs
......@@ -106,6 +111,9 @@ public class UnicastServerRef extends UnicastRef
*/
private transient Skeleton skel;
// The ObjectInputFilter for checking the invocation arguments
private final transient ObjectInputFilter filter;
/** maps method hash to Method object for each remote method */
private transient Map<Long,Method> hashToMethod_Map = null;
......@@ -124,16 +132,29 @@ public class UnicastServerRef extends UnicastRef
/**
* Create a new (empty) Unicast server remote reference.
* The filter is null to defer to the default ObjectInputStream filter, if any.
*/
public UnicastServerRef() {
this.filter = null;
}
/**
* Construct a Unicast server remote reference for a specified
* liveRef.
* The filter is null to defer to the default ObjectInputStream filter, if any.
*/
public UnicastServerRef(LiveRef ref) {
super(ref);
this.filter = null;
}
/**
* Construct a Unicast server remote reference for a specified
* liveRef and filter.
*/
public UnicastServerRef(LiveRef ref, ObjectInputFilter filter) {
super(ref);
this.filter = filter;
}
/**
......@@ -142,6 +163,7 @@ public class UnicastServerRef extends UnicastRef
*/
public UnicastServerRef(int port) {
super(new LiveRef(port));
this.filter = null;
}
/**
......@@ -366,9 +388,26 @@ public class UnicastServerRef extends UnicastRef
}
}
/**
* Sets a filter for invocation arguments, if a filter has been set.
* Called by dispatch before the arguments are read.
*/
protected void unmarshalCustomCallData(ObjectInput in)
throws IOException, ClassNotFoundException
{}
throws IOException, ClassNotFoundException {
if (filter != null &&
in instanceof ObjectInputStream) {
// Set the filter on the stream
ObjectInputStream ois = (ObjectInputStream) in;
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
return null;
}
});
}
}
/**
* Handle server-side dispatch using the RMI 1.1 stub/skeleton
......
......@@ -25,12 +25,15 @@
package sun.rmi.server;
import java.io.IOException;
import java.io.ObjectOutput;
import java.rmi.*;
import java.rmi.server.*;
import sun.rmi.transport.*;
import sun.rmi.transport.tcp.*;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.RemoteRef;
import sun.misc.ObjectInputFilter;
import sun.rmi.transport.LiveRef;
/**
* Server-side ref for a remote impl that uses a custom socket factory.
......@@ -58,6 +61,16 @@ public class UnicastServerRef2 extends UnicastServerRef
super(ref);
}
/**
* Construct a Unicast server remote reference for a specified
* liveRef and filter.
*/
public UnicastServerRef2(LiveRef ref,
ObjectInputFilter filter)
{
super(ref, filter);
}
/**
* Construct a Unicast server remote reference to be exported
* on the specified port.
......@@ -69,6 +82,18 @@ public class UnicastServerRef2 extends UnicastServerRef
super(new LiveRef(port, csf, ssf));
}
/**
* Construct a Unicast server remote reference to be exported
* on the specified port.
*/
public UnicastServerRef2(int port,
RMIClientSocketFactory csf,
RMIServerSocketFactory ssf,
ObjectInputFilter filter)
{
super(new LiveRef(port, csf, ssf), filter);
}
/**
* Returns the class of the ref type to be serialized
*/
......
/*
* Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2016, 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
......@@ -34,11 +34,13 @@ import java.rmi.server.LogStream;
import java.rmi.server.ObjID;
import java.rmi.server.RemoteServer;
import java.rmi.server.ServerNotActiveException;
import java.rmi.server.UID;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.Security;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
......@@ -49,6 +51,9 @@ import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import sun.misc.ObjectInputFilter;
import sun.rmi.runtime.Log;
import sun.rmi.runtime.RuntimeUtil;
import sun.rmi.server.UnicastRef;
......@@ -101,6 +106,45 @@ final class DGCImpl implements DGC {
return dgc;
}
/**
* Property name of the DGC serial filter to augment
* the built-in list of allowed types.
* Setting the property in the {@code lib/security/java.security} file
* will enable the augmented filter.
*/
private static final String DGC_FILTER_PROPNAME = "sun.rmi.transport.dgcFilter";
/** Registry max depth of remote invocations. **/
private static int DGC_MAX_DEPTH = 5;
/** Registry maximum array size in remote invocations. **/
private static int DGC_MAX_ARRAY_SIZE = 10000;
/**
* The dgcFilter created from the value of the {@code "sun.rmi.transport.dgcFilter"}
* property.
*/
private static final ObjectInputFilter dgcFilter =
AccessController.doPrivileged((PrivilegedAction<ObjectInputFilter>)DGCImpl::initDgcFilter);
/**
* Initialize the dgcFilter from the security properties or system property; if any
* @return an ObjectInputFilter, or null
*/
private static ObjectInputFilter initDgcFilter() {
ObjectInputFilter filter = null;
String props = System.getProperty(DGC_FILTER_PROPNAME);
if (props == null) {
props = Security.getProperty(DGC_FILTER_PROPNAME);
}
if (props != null) {
filter = ObjectInputFilter.Config.createFilter(props);
if (dgcLog.isLoggable(Log.BRIEF)) {
dgcLog.log(Log.BRIEF, "dgcFilter = " + filter);
}
}
return filter;
}
/**
* Construct a new server-side remote object collector at
* a particular port. Disallow construction from outside.
......@@ -295,7 +339,8 @@ final class DGCImpl implements DGC {
dgc = new DGCImpl();
ObjID dgcID = new ObjID(ObjID.DGC_ID);
LiveRef ref = new LiveRef(dgcID, 0);
UnicastServerRef disp = new UnicastServerRef(ref);
UnicastServerRef disp = new UnicastServerRef(ref,
DGCImpl::checkInput);
Remote stub =
Util.createProxy(DGCImpl.class,
new UnicastRef(ref), true);
......@@ -326,6 +371,53 @@ final class DGCImpl implements DGC {
});
}
/**
* ObjectInputFilter to filter DGC input objects.
* The list of acceptable classes is very short and explicit.
* The depth and array sizes are limited.
*
* @param filterInfo access to class, arrayLength, etc.
* @return {@link ObjectInputFilter.Status#ALLOWED} if allowed,
* {@link ObjectInputFilter.Status#REJECTED} if rejected,
* otherwise {@link ObjectInputFilter.Status#UNDECIDED}
*/
private static ObjectInputFilter.Status checkInput(ObjectInputFilter.FilterInfo filterInfo) {
if (dgcFilter != null) {
ObjectInputFilter.Status status = dgcFilter.checkInput(filterInfo);
if (status != ObjectInputFilter.Status.UNDECIDED) {
// The DGC filter can override the built-in white-list
return status;
}
}
if (filterInfo.depth() > DGC_MAX_DEPTH) {
return ObjectInputFilter.Status.REJECTED;
}
Class<?> clazz = filterInfo.serialClass();
if (clazz != null) {
while (clazz.isArray()) {
if (filterInfo.arrayLength() >= 0 && filterInfo.arrayLength() > DGC_MAX_ARRAY_SIZE) {
return ObjectInputFilter.Status.REJECTED;
}
// Arrays are allowed depending on the component type
clazz = clazz.getComponentType();
}
if (clazz.isPrimitive()) {
// Arrays of primitives are allowed
return ObjectInputFilter.Status.ALLOWED;
}
return (clazz == ObjID.class ||
clazz == UID.class ||
clazz == VMID.class ||
clazz == Lease.class)
? ObjectInputFilter.Status.ALLOWED
: ObjectInputFilter.Status.REJECTED;
}
// Not a class, not size limited
return ObjectInputFilter.Status.UNDECIDED;
}
private static class LeaseInfo {
VMID vmid;
long expiration;
......
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2016, 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
......@@ -25,6 +25,7 @@
package sun.security.ec;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.math.BigInteger;
......@@ -363,13 +364,22 @@ abstract class ECDSASignature extends SignatureSpi {
}
// Convert the DER encoding of R and S into a concatenation of R and S
private byte[] decodeSignature(byte[] signature) throws SignatureException {
private byte[] decodeSignature(byte[] sig) throws SignatureException {
try {
DerInputStream in = new DerInputStream(signature);
// Enforce strict DER checking for signatures
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
DerValue[] values = in.getSequence(2);
// check number of components in the read sequence
// and trailing data
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("Invalid encoding for signature");
}
BigInteger r = values[0].getPositiveBigInteger();
BigInteger s = values[1].getPositiveBigInteger();
// trim leading zeroes
byte[] rBytes = trimZeroes(r.toByteArray());
byte[] sBytes = trimZeroes(s.toByteArray());
......@@ -383,7 +393,7 @@ abstract class ECDSASignature extends SignatureSpi {
return result;
} catch (Exception e) {
throw new SignatureException("Could not decode signature", e);
throw new SignatureException("Invalid encoding for signature", e);
}
}
......
/*
* Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2003, 2016, 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
......@@ -705,12 +705,21 @@ final class P11Signature extends SignatureSpi {
}
}
private static byte[] asn1ToDSA(byte[] signature) throws SignatureException {
private static byte[] asn1ToDSA(byte[] sig) throws SignatureException {
try {
DerInputStream in = new DerInputStream(signature);
// Enforce strict DER checking for signatures
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
DerValue[] values = in.getSequence(2);
// check number of components in the read sequence
// and trailing data
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("Invalid encoding for signature");
}
BigInteger r = values[0].getPositiveBigInteger();
BigInteger s = values[1].getPositiveBigInteger();
byte[] br = toByteArray(r, 20);
byte[] bs = toByteArray(s, 20);
if ((br == null) || (bs == null)) {
......@@ -720,16 +729,25 @@ final class P11Signature extends SignatureSpi {
} catch (SignatureException e) {
throw e;
} catch (Exception e) {
throw new SignatureException("invalid encoding for signature", e);
throw new SignatureException("Invalid encoding for signature", e);
}
}
private byte[] asn1ToECDSA(byte[] signature) throws SignatureException {
private byte[] asn1ToECDSA(byte[] sig) throws SignatureException {
try {
DerInputStream in = new DerInputStream(signature);
// Enforce strict DER checking for signatures
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
DerValue[] values = in.getSequence(2);
// check number of components in the read sequence
// and trailing data
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("Invalid encoding for signature");
}
BigInteger r = values[0].getPositiveBigInteger();
BigInteger s = values[1].getPositiveBigInteger();
// trim leading zeroes
byte[] br = KeyUtil.trimZeroes(r.toByteArray());
byte[] bs = KeyUtil.trimZeroes(s.toByteArray());
......@@ -740,7 +758,7 @@ final class P11Signature extends SignatureSpi {
System.arraycopy(bs, 0, res, res.length - bs.length, bs.length);
return res;
} catch (Exception e) {
throw new SignatureException("invalid encoding for signature", e);
throw new SignatureException("Invalid encoding for signature", e);
}
}
......
/*
* Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1996, 2016, 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
......@@ -267,14 +267,20 @@ abstract class DSA extends SignatureSpi {
BigInteger s = null;
// first decode the signature.
try {
DerInputStream in = new DerInputStream(signature, offset, length);
// Enforce strict DER checking for signatures
DerInputStream in =
new DerInputStream(signature, offset, length, false);
DerValue[] values = in.getSequence(2);
// check number of components in the read sequence
// and trailing data
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("Invalid encoding for signature");
}
r = values[0].getBigInteger();
s = values[1].getBigInteger();
} catch (IOException e) {
throw new SignatureException("invalid encoding for signature");
throw new SignatureException("Invalid encoding for signature", e);
}
// some implementations do not correctly encode values in the ASN.1
......@@ -366,13 +372,49 @@ abstract class DSA extends SignatureSpi {
return t5.mod(q);
}
// NOTE: This following impl is defined in FIPS 186-4 AppendixB.2.1.
protected BigInteger generateK(BigInteger q) {
// Implementation defined in FIPS 186-4 AppendixB.2.1.
SecureRandom random = getSigningRandom();
byte[] kValue = new byte[(q.bitLength() + 7)/8 + 8];
random.nextBytes(kValue);
return new BigInteger(1, kValue).mod(q.subtract(BigInteger.ONE)).add(BigInteger.ONE);
BigInteger k = new BigInteger(1, kValue).mod(
q.subtract(BigInteger.ONE)).add(BigInteger.ONE);
// Using an equivalent exponent of fixed length (same as q or 1 bit
// less than q) to keep the kG timing relatively constant.
//
// Note that this is an extra step on top of the approach defined in
// FIPS 186-4 AppendixB.2.1 so as to make a fixed length K.
k = k.add(q).divide(BigInteger.valueOf(2));
// An alternative implementation based on FIPS 186-4 AppendixB2.2
// with fixed-length K.
//
// Please keep it here as we may need to switch to it in the future.
//
// SecureRandom random = getSigningRandom();
// byte[] kValue = new byte[(q.bitLength() + 7)/8];
// BigInteger d = q.subtract(BigInteger.TWO);
// BigInteger k;
// do {
// random.nextBytes(kValue);
// BigInteger c = new BigInteger(1, kValue);
// if (c.compareTo(d) <= 0) {
// k = c.add(BigInteger.ONE);
// // Using an equivalent exponent of fixed length to keep
// // the g^k timing relatively constant.
// //
// // Note that this is an extra step on top of the approach
// // defined in FIPS 186-4 AppendixB.2.2 so as to make a
// // fixed length K.
// if (k.bitLength() >= q.bitLength()) {
// break;
// }
// }
// } while (true);
return k;
}
// Use the application-specified SecureRandom Object if provided.
......
/*
* Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2009, 2016, 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
......@@ -31,12 +31,10 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.EnumSet;
import java.util.HashSet;
import java.math.BigInteger;
import java.security.PublicKey;
import java.security.KeyFactory;
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.GeneralSecurityException;
import java.security.cert.Certificate;
import java.security.cert.X509CRL;
......@@ -48,10 +46,13 @@ import java.security.cert.CertificateException;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertPathValidatorException.BasicReason;
import java.security.cert.PKIXReason;
import java.io.IOException;
import java.security.interfaces.*;
import java.security.spec.*;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import sun.security.util.AnchorCertificates;
import sun.security.util.CertConstraintParameters;
import sun.security.util.Debug;
import sun.security.util.DisabledAlgorithmConstraints;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CRLImpl;
......@@ -69,6 +70,7 @@ import sun.security.x509.AlgorithmId;
* @see PKIXParameters
*/
final public class AlgorithmChecker extends PKIXCertPathChecker {
private static final Debug debug = Debug.getInstance("certpath");
private final AlgorithmConstraints constraints;
private final PublicKey trustedPubKey;
......@@ -88,6 +90,14 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
certPathDefaultConstraints = new DisabledAlgorithmConstraints(
DisabledAlgorithmConstraints.PROPERTY_CERTPATH_DISABLED_ALGS);
// If there is no "cacerts" keyword, then disable anchor checking
private static final boolean publicCALimits =
certPathDefaultConstraints.checkProperty("jdkCA");
// If anchor checking enabled, this will be true if the trust anchor
// has a match in the cacerts file
private boolean trustedMatch = false;
/**
* Create a new <code>AlgorithmChecker</code> with the algorithm
* constraints specified in security property
......@@ -136,6 +146,11 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
if (anchor.getTrustedCert() != null) {
this.trustedPubKey = anchor.getTrustedCert().getPublicKey();
// Check for anchor certificate restrictions
trustedMatch = checkFingerprint(anchor.getTrustedCert());
if (trustedMatch && debug != null) {
debug.println("trustedMatch = true");
}
} else {
this.trustedPubKey = anchor.getCAPublicKey();
}
......@@ -144,6 +159,19 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
this.constraints = constraints;
}
// Check this 'cert' for restrictions in the AnchorCertificates
// trusted certificates list
private static boolean checkFingerprint(X509Certificate cert) {
if (!publicCALimits) {
return false;
}
if (debug != null) {
debug.println("AlgorithmChecker.contains: " + cert.getSigAlgName());
}
return AnchorCertificates.contains(cert);
}
@Override
public void init(boolean forward) throws CertPathValidatorException {
// Note that this class does not support forward mode.
......@@ -181,36 +209,8 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
return;
}
X509CertImpl x509Cert = null;
try {
x509Cert = X509CertImpl.toImpl((X509Certificate)cert);
} catch (CertificateException ce) {
throw new CertPathValidatorException(ce);
}
PublicKey currPubKey = x509Cert.getPublicKey();
String currSigAlg = x509Cert.getSigAlgName();
AlgorithmId algorithmId = null;
try {
algorithmId = (AlgorithmId)x509Cert.get(X509CertImpl.SIG_ALG);
} catch (CertificateException ce) {
throw new CertPathValidatorException(ce);
}
AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
// Check the current signature algorithm
if (!constraints.permits(
SIGNATURE_PRIMITIVE_SET,
currSigAlg, currSigAlgParams)) {
throw new CertPathValidatorException(
"Algorithm constraints check failed: " + currSigAlg,
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
// check the key usage and key size
boolean[] keyUsage = x509Cert.getKeyUsage();
boolean[] keyUsage = ((X509Certificate) cert).getKeyUsage();
if (keyUsage != null && keyUsage.length < 9) {
throw new CertPathValidatorException(
"incorrect KeyUsage extension",
......@@ -248,28 +248,69 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
if (primitives.isEmpty()) {
throw new CertPathValidatorException(
"incorrect KeyUsage extension",
"incorrect KeyUsage extension bits",
null, null, -1, PKIXReason.INVALID_KEY_USAGE);
}
}
PublicKey currPubKey = cert.getPublicKey();
if (constraints instanceof DisabledAlgorithmConstraints) {
// Check against DisabledAlgorithmConstraints certpath constraints.
// permits() will throw exception on failure.
((DisabledAlgorithmConstraints)constraints).permits(primitives,
new CertConstraintParameters((X509Certificate)cert,
trustedMatch));
// If there is no previous key, set one and exit
if (prevPubKey == null) {
prevPubKey = currPubKey;
return;
}
}
X509CertImpl x509Cert;
AlgorithmId algorithmId;
try {
x509Cert = X509CertImpl.toImpl((X509Certificate)cert);
algorithmId = (AlgorithmId)x509Cert.get(X509CertImpl.SIG_ALG);
} catch (CertificateException ce) {
throw new CertPathValidatorException(ce);
}
AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
String currSigAlg = x509Cert.getSigAlgName();
// If 'constraints' is not of DisabledAlgorithmConstraints, check all
// everything individually
if (!(constraints instanceof DisabledAlgorithmConstraints)) {
// Check the current signature algorithm
if (!constraints.permits(
SIGNATURE_PRIMITIVE_SET,
currSigAlg, currSigAlgParams)) {
throw new CertPathValidatorException(
"Algorithm constraints check failed on signature " +
"algorithm: " + currSigAlg, null, null, -1,
BasicReason.ALGORITHM_CONSTRAINED);
}
if (!constraints.permits(primitives, currPubKey)) {
throw new CertPathValidatorException(
"algorithm constraints check failed",
"Algorithm constraints check failed on keysize: " +
sun.security.util.KeyUtil.getKeySize(currPubKey),
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
// Check with previous cert for signature algorithm and public key
if (prevPubKey != null) {
if (currSigAlg != null) {
if (!constraints.permits(
SIGNATURE_PRIMITIVE_SET,
currSigAlg, prevPubKey, currSigAlgParams)) {
throw new CertPathValidatorException(
"Algorithm constraints check failed: " + currSigAlg,
"Algorithm constraints check failed on " +
"signature algorithm: " + currSigAlg,
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
// Inherit key parameters from previous key
if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
......@@ -282,7 +323,7 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
DSAParams params = ((DSAPublicKey)prevPubKey).getParams();
if (params == null) {
throw new CertPathValidatorException(
"Key parameters missing");
"Key parameters missing from public key.");
}
try {
......@@ -330,6 +371,11 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
// Don't bother to change the trustedPubKey.
if (anchor.getTrustedCert() != null) {
prevPubKey = anchor.getTrustedCert().getPublicKey();
// Check for anchor certificate restrictions
trustedMatch = checkFingerprint(anchor.getTrustedCert());
if (trustedMatch && debug != null) {
debug.println("trustedMatch = true");
}
} else {
prevPubKey = anchor.getCAPublicKey();
}
......@@ -370,7 +416,8 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
if (!certPathDefaultConstraints.permits(
SIGNATURE_PRIMITIVE_SET, sigAlgName, key, sigAlgParams)) {
throw new CertPathValidatorException(
"algorithm check failed: " + sigAlgName + " is disabled",
"Algorithm constraints check failed on signature algorithm: " +
sigAlgName + " is disabled",
null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
}
}
......
......@@ -131,8 +131,8 @@ class PKIXMasterCertPathValidator {
} catch (CertPathValidatorException cpve) {
throw new CertPathValidatorException(cpve.getMessage(),
cpve.getCause(), cpOriginal, cpSize - (i + 1),
cpve.getReason());
(cpve.getCause() != null) ? cpve.getCause() : cpve,
cpOriginal, cpSize - (i + 1), cpve.getReason());
}
}
......
......@@ -223,9 +223,10 @@ public abstract class RSASignature extends SignatureSpi {
* Decode the signature data. Verify that the object identifier matches
* and return the message digest.
*/
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] signature)
public static byte[] decodeSignature(ObjectIdentifier oid, byte[] sig)
throws IOException {
DerInputStream in = new DerInputStream(signature);
// Enforce strict DER checking for signatures
DerInputStream in = new DerInputStream(sig, 0, sig.length, false);
DerValue[] values = in.getSequence(2);
if ((values.length != 2) || (in.available() != 0)) {
throw new IOException("SEQUENCE length error");
......
/*
* Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2006, 2016, 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
......@@ -56,10 +56,11 @@ final class ECDHCrypt {
}
// Called by ServerHandshaker for ephemeral ECDH
ECDHCrypt(String curveName, SecureRandom random) {
ECDHCrypt(int curveId, SecureRandom random) {
try {
KeyPairGenerator kpg = JsseJce.getKeyPairGenerator("EC");
ECGenParameterSpec params = new ECGenParameterSpec(curveName);
ECGenParameterSpec params =
SupportedEllipticCurvesExtension.getECGenParamSpec(curveId);
kpg.initialize(params, random);
KeyPair kp = kpg.generateKeyPair();
privateKey = kp.getPrivate();
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册