- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Java中的魔法类:sun.misc.Unsafe示例详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
前言 。
unsafe类在jdk 源码的多个类中用到,这个类的提供了一些绕开jvm的更底层功能,基于它的实现可以提高效率。但是,它是一把双刃剑:正如它的名字所预示的那样,它是unsafe的,它所分配的内存需要手动free(不被gc回收)。unsafe类,提供了jni某些功能的简单替代:确保高效性的同时,使事情变得更简单.
这个类是属于sun.* api中的类,并且它不是j2se中真正的一部份,因此你可能找不到任何的官方文档,更可悲的是,它也没有比较好的代码文档.
这篇文章主要是以下文章的整理、翻译.
http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/ 。
1. unsafe api的大部分方法都是native实现,它由105个方法组成,主要包括以下几类:
(1)info相关。主要返回某些低级别的内存信息:addresssize(), pagesize() 。
(2)objects相关。主要提供object和它的域操纵方法:allocateinstance(),objectfieldoffset() 。
(3)class相关。主要提供class和它的静态域操纵方法:staticfieldoffset(),defineclass(),defineanonymousclass(),ensureclassinitialized() 。
(4)arrays相关。数组操纵方法:arraybaseoffset(),arrayindexscale() 。
(5)synchronization相关。主要提供低级别同步原语(如基于cpu的cas(compare-and-swap)原语):monitorenter(),trymonitorenter(),monitorexit(),compareandswapint(),putorderedint() 。
(6)memory相关。直接内存访问方法(绕过jvm堆直接操纵本地内存):allocatememory(),copymemory(),freememory(),getaddress(),getint(),putint() 。
2. unsafe类实例的获取 。
unsafe类设计只提供给jvm信任的启动类加载器所使用,是一个典型的单例模式类。它的实例获取方法如下:
1
2
3
4
5
6
|
public
static
unsafe getunsafe() {
class
cc = sun.reflect.reflection.getcallerclass(
2
);
if
(cc.getclassloader() !=
null
)
throw
new
securityexception(
"unsafe"
);
return
theunsafe;
}
|
非启动类加载器直接调用unsafe.getunsafe()方法会抛出securityexception(具体原因涉及jvm类的双亲加载机制).
解决办法有两个,其一是通过jvm参数-xbootclasspath指定要使用的类为启动类,另外一个办法就是java反射了.
1
2
3
|
field f = unsafe.
class
.getdeclaredfield(
"theunsafe"
);
f.setaccessible(
true
);
unsafe unsafe = (unsafe) f.get(
null
);
|
通过将private单例实例暴力设置accessible为true,然后通过field的get方法,直接获取一个object强制转换为unsafe。在ide中,这些方法会被标志为error,可以通过以下设置解决:
1
2
|
preferences -> java -> compiler -> errors/warnings ->
deprecated and restricted api -> forbidden reference -> warning
|
3. unsafe类“有趣”的应用场景 。
(1)绕过类初始化方法。当你想要绕过对象构造方法、安全检查器或者没有public的构造方法时,allocateinstance()方法变得非常有用.
1
2
3
4
5
6
7
|
class
a {
private
long
a;
// not initialized value
public
a() {
this
.a =
1
;
// initialization
}
public
long
a() {
return
this
.a; }
}
|
以下是构造方法、反射方法和allocateinstance()的对照 。
1
2
3
4
5
6
7
8
|
a o1 =
new
a();
// constructor
o1.a();
// prints 1
a o2 = a.
class
.newinstance();
// reflection
o2.a();
// prints 1
a o3 = (a) unsafe.allocateinstance(a.
class
);
// unsafe
o3.a();
// prints 0
|
allocateinstance()根本没有进入构造方法,在单例模式时,我们似乎看到了危机.
(2)内存修改 。
内存修改在c语言中是比较常见的,在java中,可以用它绕过安全检查器.
考虑以下简单准入检查规则:
1
2
3
4
5
6
7
|
class
guard {
private
int
access_allowed =
1
;
public
boolean
giveaccess() {
return
42
== access_allowed;
}
}
|
在正常情况下,giveaccess总会返回false,但事情不总是这样 。
1
2
3
4
5
6
7
8
9
|
guard guard =
new
guard();
guard.giveaccess();
// false, no access
// bypass
unsafe unsafe = getunsafe();
field f = guard.getclass().getdeclaredfield(
"access_allowed"
);
unsafe.putint(guard, unsafe.objectfieldoffset(f),
42
);
// memory corruption
guard.giveaccess();
// true, access granted
|
通过计算内存偏移,并使用putint()方法,类的access_allowed被修改。在已知类结构的时候,数据的偏移总是可以计算出来(与c++中的类中数据的偏移计算是一致的).
(3)实现类似c语言的sizeof()函数 。
通过结合java反射和objectfieldoffset()函数实现一个c-like sizeof()函数.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
static
long
sizeof(object o) {
unsafe u = getunsafe();
hashset fields =
new
hashset();
class
c = o.getclass();
while
(c != object.
class
) {
for
(field f : c.getdeclaredfields()) {
if
((f.getmodifiers() & modifier.
static
) ==
0
) {
fields.add(f);
}
}
c = c.getsuperclass();
}
// get offset
long
maxsize =
0
;
for
(field f : fields) {
long
offset = u.objectfieldoffset(f);
if
(offset > maxsize) {
maxsize = offset;
}
}
return
((maxsize/
8
) +
1
) *
8
;
// padding
}
|
算法的思路非常清晰:从底层子类开始,依次取出它自己和它的所有超类的非静态域,放置到一个hashset中(重复的只计算一次,java是单继承),然后使用objectfieldoffset()获得一个最大偏移,最后还考虑了对齐.
在32位的jvm中,可以通过读取class文件偏移为12的long来获取size.
1
2
3
4
|
public
static
long
sizeof(object object){
return
getunsafe().getaddress(
normalize(getunsafe().getint(object, 4l)) + 12l);
}
|
其中normalize()函数是一个将有符号int转为无符号long的方法 。
1
2
3
4
|
private
static
long
normalize(
int
value) {
if
(value >=
0
)
return
value;
return
(0l >>>
32
) & value;
}
|
两个sizeof()计算的类的尺寸是一致的。最标准的sizeof()实现是使用java.lang.instrument,但是,它需要指定命令行参数-javaagent.
(4)实现java浅复制 。
标准的浅复制方案是实现cloneable接口或者自己实现的复制函数,它们都不是多用途的函数。通过结合sizeof()方法,可以实现浅复制.
1
2
3
4
5
6
7
|
static
object shallowcopy(object obj) {
long
size = sizeof(obj);
long
start = toaddress(obj);
long
address = getunsafe().allocatememory(size);
getunsafe().copymemory(start, address, size);
return
fromaddress(address);
}
|
以下的toaddress()和fromaddress()分别将对象转换到它的地址以及相反操作.
1
2
3
4
5
6
7
8
9
10
11
12
|
static
long
toaddress(object obj) {
object[] array =
new
object[] {obj};
long
baseoffset = getunsafe().arraybaseoffset(object[].
class
);
return
normalize(getunsafe().getint(array, baseoffset));
}
static
object fromaddress(
long
address) {
object[] array =
new
object[] {
null
};
long
baseoffset = getunsafe().arraybaseoffset(object[].
class
);
getunsafe().putlong(array, baseoffset, address);
return
array[
0
];
}
|
以上的浅复制函数可以应用于任意java对象,它的尺寸是动态计算的.
(5)消去内存中的密码 。
密码字段存储在string中,但是,string的回收是受到jvm管理的。最安全的做法是,在密码字段使用完之后,将它的值覆盖.
1
2
3
4
5
6
|
field stringvalue = string.
class
.getdeclaredfield(
"value"
);
stringvalue.setaccessible(
true
);
char
[] mem = (
char
[]) stringvalue.get(password);
for
(
int
i=
0
; i < mem.length; i++) {
mem[i] =
'?'
;
}
|
(6)动态加载类 。
标准的动态加载类的方法是class.forname()(在编写jdbc程序时,记忆深刻),使用unsafe也可以动态加载java 的class文件.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
byte
[] classcontents = getclasscontent();
class
c = getunsafe().defineclass(
null
, classcontents,
0
, classcontents.length);
c.getmethod(
"a"
).invoke(c.newinstance(),
null
);
// 1
getclasscontent()方法,将一个
class
文件,读取到一个
byte
数组。
private
static
byte
[] getclasscontent()
throws
exception {
file f =
new
file(
"/home/mishadoff/tmp/a.class"
);
fileinputstream input =
new
fileinputstream(f);
byte
[] content =
new
byte
[(
int
)f.length()];
input.read(content);
input.close();
return
content;
}
|
动态加载、代理、切片等功能中可以应用.
(7)包装受检异常为运行时异常.
1
|
getunsafe().throwexception(
new
ioexception());
|
当你不希望捕获受检异常时,可以这样做(并不推荐).
(8)快速序列化 。
标准的java serializable速度很慢,它还限制类必须有public无参构造函数。externalizable好些,它需要为要序列化的类指定模式。流行的高效序列化库,比如kryo依赖于第三方库,会增加内存的消耗。可以通过getint(),getlong(),getobject()等方法获取类中的域的实际值,将类名称等信息一起持久化到文件。kryo有使用unsafe的尝试,但是没有具体的性能提升的数据。(http://code.google.com/p/kryo/issues/detail?id=75) 。
(9)在非java堆中分配内存 。
使用java 的new会在堆中为对象分配内存,并且对象的生命周期内,会被jvm gc管理.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class
superarray {
private
final
static
int
byte
=
1
;
private
long
size;
private
long
address;
public
superarray(
long
size) {
this
.size = size;
address = getunsafe().allocatememory(size *
byte
);
}
public
void
set(
long
i,
byte
value) {
getunsafe().putbyte(address + i *
byte
, value);
}
public
int
get(
long
idx) {
return
getunsafe().getbyte(address + idx *
byte
);
}
public
long
size() {
return
size;
}
}
|
unsafe分配的内存,不受integer.max_value的限制,并且分配在非堆内存,使用它时,需要非常谨慎:忘记手动回收时,会产生内存泄露;非法的地址访问时,会导致jvm崩溃。在需要分配大的连续区域、实时编程(不能容忍jvm延迟)时,可以使用它。java.nio使用这一技术.
(10)java并发中的应用 。
通过使用unsafe.compareandswap()可以用来实现高效的无锁数据结构.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class
cascounter
implements
counter {
private
volatile
long
counter =
0
;
private
unsafe unsafe;
private
long
offset;
public
cascounter()
throws
exception {
unsafe = getunsafe();
offset = unsafe.objectfieldoffset(cascounter.
class
.getdeclaredfield(
"counter"
));
}
@override
public
void
increment() {
long
before = counter;
while
(!unsafe.compareandswaplong(
this
, offset, before, before +
1
)) {
before = counter;
}
}
@override
public
long
getcounter() {
return
counter;
}
}
|
通过测试,以上数据结构与java的原子变量的效率基本一致,java原子变量也使用unsafe的compareandswap()方法,而这个方法最终会对应到cpu的对应原语,因此,它的效率非常高。这里有一个实现无锁hashmap的方案(http://www.azulsystems.com/about_us/presentations/lock-free-hash ,这个方案的思路是:分析各个状态,创建拷贝,修改拷贝,使用cas原语,自旋锁),在普通的服务器机器(核心<32),使用concurrenthashmap(jdk8以前,默认16路分离锁实现,jdk8中concurrenthashmap已经使用无锁实现)明显已经够用.
总结 。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对我的支持.
原文链接:https://www.cnblogs.com/suxuan/p/4948608.html 。
最后此篇关于Java中的魔法类:sun.misc.Unsafe示例详解的文章就讲到这里了,如果你想了解更多关于Java中的魔法类:sun.misc.Unsafe示例详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
已结束。此问题不符合 Stack Overflow guidelines .它目前不接受答案。 我们不允许提出有关书籍、工具、软件库等方面的建议的问题。您可以编辑问题,以便用事实和引用来回答它。 关闭
在我正在开发的 crate 中,我有几个 unsafe 函数,由于某些原因它们被标记为 explained in this answer .在 unsafe 函数中,我可以执行 unsafe 操作,就
我一直在尝试在我的网络应用程序中设置文本编辑器。在哪里访问文本编辑器我必须允许 script-src 'self' 'unsafe-inline' 'unsafe-eval' 和 style-src
我是后端开发人员,正在帮助前端团队部署 Web 服务器,同时我正在研究遇到内容安全策略的漏洞,如果我将 CSP header 设置为“内容安全策略:默认源代码‘自我’数据: {own_domain_1
Unsafe.putAddress(long address, long x) 之间有什么区别?方法和Unsafe.putLong(long address, long x)方法? 最佳答案 Java
考虑以下代码: const defaultState = () => { return { profile: { id: '', displayName: '',
上面有一条评论 public native void unpark(对象线程); “取消阻塞在park上阻塞的给定线程,或者,如果它没有阻塞,则导致后续对park的调用不阻塞。注意:此操作“不安全”,
我已将 unsafe.cpp 和 Unsafe.java 克隆到自定义版本。我要构建新的 JVM,但似乎我的 UnsafeNew.java 内联了 unsafe.cpp 方法,而不是新的 unsafe
为什么会出现以下错误? Unsafe code may only appear if compiling with /unsafe"? 我使用 C# 和 Visual Studio 2008 在 Wi
我正在用 C# 做一个项目,它可以从线性代数包中获益。我看过外面的那些,但我真的不想付钱,或者我发现它们不是很好。所以我决定自己写。 我读到 C++ 数组比 C# 数组快得多,但在 C# 中使用指针数
在 Java 中,java.lang.unsafe 包中有 Unsafe 类,它提供对操作的低级访问。 现在在我看来,JVM 需要支持Unsafe 类中可用的所有 方法,以便与 JLS 兼容,示例方法
我正在尝试将选项卡存储在本地存储中并在刷新页面上获取前面的选项卡,数据存储在本地但是在控制台上的时候我得到错误 Error: [$sce:unsafe] Attempting to use an un
导入类型化函数时,我收到 no-unsafe-call 和 no-unsafe-assignment eslint 错误。如果函数在同一个文件中声明,错误就会消失。 eslint 似乎无法获取导入函数
我正在尝试在 Visual Studio App Center 中构建 Xamarin iOS 应用程序。该解决方案包含两个项目。一个是 Xamarin iOS 项目。另一个是绑定(bind)库项目。
Unsafe Fileupload 1.client check 标题叫客户端check,文件校验应该是在客户端进行的。 可以先把一句话木马改成图片格式,然后再抓包修改回PHP格式。 一句话木马内容:
我想问一下第一个例子是否比第二个例子慢。 例子1:for, unsafe, unsafe, unsafe, etc for (var i = 0; i ' { } // end of class .
我尝试通过在 Controller 中生成链接将书签按钮添加到我的网站。 模板部分: + Add Controller 部分: $scope.getCode = fun
我注意到在 Java 7 中,集合类(在我的例子中是 ConcurrentLinkedQueue)使用 UNSAFE 类进行交换和查找操作。 偏移量似乎是在编译时声明中计算的: itemOffset
我有一张图片: 在 html 上我得到的结果是: unsafe:c:/var/vci/images/fleetImages/IMG_20150912_091552.jpg 我已经在app.js中添加
这是实现原生pinvok代码的类 虽然我无法验证它是否正确使用了 unsafe,但它似乎可以工作 不安全的签名 struct IO_COUNTERS { public
我是一名优秀的程序员,十分优秀!