" 最近有一个感受,当工作完全沦为谋生的手段,让我感觉不到一丝丝的快乐。工作的意义仅仅在于工资,而与工作本身毫无关联。个人成为受控的机器,只是为了获取报酬而勉强为之 -> 穷则变,变则通,通则久 -> 找找工作的乐趣与获得感。"
前言
最近工作中有遇到Layer leak相关的问题,所以就追了下Layer LifeCycle相关的代码逻辑,Android新旧版本在code上稍有差异,但原理一致,在此也记录一下。
Layer Lifecycle
Android 13及之前版本有定义LayerCleaner & Handle,其中Handle继承自BBinder,其对象可以跨进程传递到client,SurfaceFlinger进程中不会持有Handle对象的任何引用,这样就会有: 当客户端释放Handle 后,引发LayerCleaner释放,从而调用到SurfaceFlinger::onHandleDestroyed进行资源清理工作。
Android 14后,不再有LayerCleaner这个类了,简化了逻辑,直接定义了LayerHandle class,也是继承自BBinder,可以跨进程传递给client。换汤不换药,依旧是在client不在持有handle的引用后,引发LayerHanled的析构去做一些清理工作。
关于Binder对象引用计数的原理大家可以网络上找到一些讲解,建议大家不求甚解,可以像我这样傻瓜式的理解:
BBinder Object可以传递到Client(remote process),Client就持有BBinder的引用,当Client端释放掉BBinder对象的所有引用后就会引发Server端BBinder对象的释放。
欲求甚解者可以参考:
https://www.jianshu.com/p/5a75d59c3336
https://blog.csdn.net/jltxgcy/article/details/27638717
源码中有一段关于Layer LifeCycle的注解,很有意义,大家的英文水平肯定比我高,一定可以读得懂哈!
Layer is created by a client.
// Client创建新的Surface
sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
PixelFormat format, int32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
sp<SurfaceControl> s;
createSurfaceChecked(name, w, h, format, &s, flags, parentHandle, std::move(metadata),
outTransformHint);
return s;
}
The client receives a strong binder reference to the layer handle, which will keep the layer alive as long as the client holds the reference.
// 创建新的Surface
status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h,
PixelFormat format,
sp<SurfaceControl>* outSurface, int32_t flags,
const sp<IBinder>& parentHandle,
LayerMetadata metadata,
uint32_t* outTransformHint) {
sp<SurfaceControl> sur;
status_t err = mStatus;
if (mStatus == NO_ERROR) {
gui::CreateSurfaceResult result;
// 跨进程呼叫SurfaceFlinger服务,创建新的图层
binder::Status status = mClient->createSurface(std::string(name.string()), flags,
parentHandle, std::move(metadata), &result);
err = statusTFromBinderStatus(status);
if (outTransformHint) {
*outTransformHint = result.transformHint;
}
ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err));
if (err == NO_ERROR) {// SurfaceContro中有成员sp<IBinder> mHandle
// layer的信息保存到SurfaceControl对象中,handle的类型**IBinder**
*outSurface = new SurfaceControl(this, result.handle, result.layerId,
toString(result.layerName), w, h, format,
result.transformHint, flags);
}
}
return err;
}