当前位置:网站首页>Strictmode jamming and leakage detection -strictmode principle (2)
Strictmode jamming and leakage detection -strictmode principle (2)
2022-07-01 01:28:00 【Strange uncle Lori Kong】
List of articles
2. StrictMode Turn off the detection principle
StrictMode The closing detection of is actually relatively simple , Basically, it is to bury piles when opening , Check whether the pile is closed when releasing , If it is not closed, it will be detected as leakage .
2.1 CloseGuard
Here is a preliminary knowledge , That's it CloseGuard, It's a StrictMode Classes designed to handle such things , It mainly includes three functions :
- open Start to bury piles
- close Pile removal
- warnIfOpen The explosion
SystemApi(client = MODULE_LIBRARIES)
@libcore.api.IntraCoreApi
public final class CloseGuard {
private static volatile boolean stackAndTrackingEnabled = true;
private static volatile Reporter reporter = new DefaultReporter();
private static volatile Tracker currentTracker = null; // Disabled by default.
@UnsupportedAppUsage
@SystemApi(client = MODULE_LIBRARIES)
public static void setEnabled(boolean enabled) {
CloseGuard.stackAndTrackingEnabled = enabled;
}
public static boolean isEnabled() {
return stackAndTrackingEnabled;
}
@UnsupportedAppUsage(trackingBug=111170242)
@SystemApi(client = MODULE_LIBRARIES)
@libcore.api.IntraCoreApi
public void open(String closer) {
openWithCallSite(closer, null /* callsite */);
}
// Before closing ,
@UnsupportedAppUsage
@SystemApi(client = MODULE_LIBRARIES)
@libcore.api.IntraCoreApi
public void close() {
Tracker tracker = currentTracker;
if (tracker != null && closerNameOrAllocationInfo instanceof Throwable) {
// Invoke tracker on close only if we invoked it on open. Tracker may have changed.
tracker.close((Throwable) closerNameOrAllocationInfo);
}
closerNameOrAllocationInfo = null;
}
public void warnIfOpen() {
if (closerNameOrAllocationInfo != null) {
if (closerNameOrAllocationInfo instanceof Throwable) {
reporter.report(MESSAGE, (Throwable) closerNameOrAllocationInfo);
} else if (stackAndTrackingEnabled) {
reporter.report(MESSAGE + " Callsite: " + closerNameOrAllocationInfo);
} else {
System.logW("A resource failed to call "
+ (String) closerNameOrAllocationInfo + ". ");
}
}
}
}
2.1 IO Turn off detection
Review the previous examples
findViewById<Button>(R.id.io_not_close_btn).setOnClickListener {
var outputStream = FileOutputStream(File(getExternalFilesDir("")?.path + "hello.json"))
outputStream.write("hello world".toByteArray())
outputStream = FileOutputStream(File(getExternalFilesDir("")?.path + "hello.json"))
Runtime.getRuntime().gc()
Runtime.getRuntime().gc()
}
Bury a bomb - First, let's look at the constructor :
private final CloseGuard guard = CloseGuard.get();
public FileOutputStream(File file, boolean append)
throws FileNotFoundException
{
String name = (file != null ? file.getPath() : null);
.......
// Android-added: CloseGuard support. Android Added
guard.open("close");
}
Dismantle the bomb - Close output stream
public void close() throws IOException {
synchronized (closeLock) {
if (closed) {
return;
}
closed = true;
}
// Android-added: CloseGuard support.
guard.close();
}
The explosion - There is no call close Is recycled
protected void finalize() throws IOException {
// Android-added: CloseGuard support.
if (guard != null) {
guard.warnIfOpen();
}
...
}
Similarly, it is inferred that other streams will also have other mechanisms to detect leakage .
2.2 IO Carton test
Look before Caton , We need to prepare some preliminary knowledge first ,IO Preliminary knowledge of reading and writing :
FileInputStream/FileOutputStream -> IOBridge -> ForwardingOs -> BlockGuardOS -> LibCore.OS
We need to focus on BlockGuardOS This floor , Let's look at the source code first :
public class BlockGuardOs extends ForwardingOs {
@Override public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
BlockGuard.getThreadPolicy().onReadFromDisk();// testing IO read
BlockGuard.getVmPolicy().onPathAccess(path);// testing VM Policy path access
if ((flags & O_ACCMODE) != O_RDONLY) {
BlockGuard.getThreadPolicy().onWriteToDisk(); // testing IO Write
}
....
}
@UnsupportedAppUsage
@Override public void close(FileDescriptor fd) throws ErrnoException {
try {
if (fd.isSocket$()) {
if (isLingerSocket(fd)) {
BlockGuard.getThreadPolicy().onNetwork(); // Whether the main thread accesses the network
}
}
} catch (ErrnoException ignored) {
}
super.close(fd);
}
}
Here we can see clearly ,BlockGuardOs Internal agent BlockGuard, Before each function call , Will check whether there is a stuck problem . And then finally back to StrictMode.
public void onReadFromDisk() {
if ((mThreadPolicyMask & DETECT_THREAD_DISK_READ) == 0) {
return;
}
if (tooManyViolationsThisLoop()) {
return;
}
// This function will print
startHandlingViolationException(new DiskReadViolation());
}
2.3 SqliteCursor Leak detection
location:frameworks/base/core/java/android/database/sqlite/SQLiteCursor.java
protected void finalize() {
try {
// if the cursor hasn't been closed yet, close it first
if (mWindow != null) {
// Report original sql statement
if (StrictMode.vmSqliteObjectLeaksEnabled()) {
String sql = mQuery.getSql();
int len = sql.length();
StrictMode.onSqliteObjectLeaked(
"Finalizing a Cursor that has not been deactivated or closed. "
+ "database = " + mQuery.getDatabase().getLabel()
+ ", table = " + mEditTable
+ ", query = " + sql.substring(0, (len > 1000) ? 1000 : len),
null);
}
}
} finally {
super.finalize();
}
}
It is obvious that , When mWindow Isn't empty , The leaked information will be reported . there window refer to cursor The query window of , Executed move The function assigns a value
边栏推荐
猜你喜欢

Service grid ASM year end summary: how do end users use the service grid?

解析融合学科本质的创客教育路径

Introduction and principle analysis of cluster and LVS

【go】go 实现行专列 将集合进行转列

Poor students can also play raspberry pie

ESP8266 RC522

fluttertoast

流批一体在京东的探索与实践
![[go] go implements row column conversion of sets](/img/d9/6272e55b2d9c6b6fbdf2537773bb83.png)
[go] go implements row column conversion of sets

日志 logrus第三方库的使用
随机推荐
Kongyiji's first question: how much do you know about service communication?
Solve idea:class' xxx 'not found in module' xxx‘
【学习笔记】构造
ESP8266 RC522
文件服务设计
ASCII、Unicode、GBK、UTF-8之间的关系
机器人编程的培训学科类原理
Training discipline principle of robot programming
DX-11Q信号继电器
冲击继电器ZC-23/DC220V
【Qt5-基础篇_1】从0开始,德天老师和你一起学习——窗口简介
None of the following candidates is applicable because of a receiver type mismatch
Split the linked list [take next first and then cut the linked list to prevent chain breakage]
DLS-20型双位置继电器 220VDC
2021电赛F题openmv和K210调用openmv api巡线,完全开源。
流批一体在京东的探索与实践
Looksrare team's "cash out" caused disturbance
日志 logrus第三方库的使用
【网络丢包,网络延迟?这款神器帮你搞定所有!】
Dls-20 double position relay 220VDC