Fingerprint

# 核心源码(Android_10.0)

关键类 路径
Android.bp hardware/interfaces/biometrics/fingerprint/2.1/default/Android.bp
BiometricsFingerprint.cpp hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp
service.cpp hardware/interfaces/biometrics/fingerprint/2.1/default/service.cpp
fingerprint.c hardware/libhardware/modules/fingerprint/fingerprint.c
FingerprintManager.java frameworks/base/core/java/android/hardware/fingerprint/FingerprintManager.java
PowerManager.java frameworks/base/core/java/android/os/PowerManager.java
KeyguardUpdateMonitor.java frameworks/base/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java
KeyguardViewMediator.java frameworks/base/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
SystemServer.java frameworks/base/services/java/com/android/server/SystemServer.java
SystemServiceManager.java frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
FingerprintService.java frameworks/base/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java
PhoneWindowManager.java frameworks/base/services/core/java/com/android/server/policy/PhoneWindowManager.java
KeyguardServiceDelegate.java frameworks/base/services/core/java/com/android/server/policy/keyguard/KeyguardServiceDelegate.java
KeyguardServiceWrapper.java frameworks/base/services/core/java/com/android/server/policy/keyguard/KeyguardServiceWrapper.java
Notifier.java frameworks/base/services/core/java/com/android/server/power/Notifier.java
PowerManagerService.java frameworks/base/services/core/java/com/android/server/power/PowerManagerService.java

一、SystemServer

FingerprintServicesystem server 中创建并初始化,如果检测到手机支持指纹功能就会启动这个 service

1.1 SystemServer.main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// frameworks/base/services/java/com/android/server/SystemServer.java

public final class SystemServer {

public static void main(String[] args) {
new SystemServer().run();
}

private void run() {
... ...

// Start services.
try {
startBootstrapServices();
startCoreServices();
startOtherServices(); // 启动其他服务
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
}

... ...
}

}

1.2 SystemServer.startOtherServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// frameworks/base/services/java/com/android/server/SystemServer.java

public final class SystemServer {

private SystemServiceManager mSystemServiceManager;

private void startOtherServices() {
... ...

// 判断是否系统内部集成了指纹功能,8.0 以上版本默认集成
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {

final boolean hasFeatureFingerprint
= mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT);

if (hasFeatureFingerprint) {
traceBeginAndSlog("StartFingerprintSensor");
mSystemServiceManager.startService(FingerprintService.class);
traceEnd();
}

}

... ...
}

}

1.3 SystemServiceManager.startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// frameworks/base/services/core/java/com/android/server/SystemServiceManager.java

public class SystemServiceManager {

public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart(); // 调用 FingerprintService 的 onStart() 方法
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

}

二、FingerprintService

2.1 FingerprintService.onStart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// frameworks/base/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java

public class FingerprintService extends BiometricServiceBase {

@Override
public void onStart() {
super.onStart();
// 创建了 FingerprintServiceWrapper 对象
publishBinderService(Context.FINGERPRINT_SERVICE, new FingerprintServiceWrapper());
// 调用 this::getFingerprintDaemon
SystemServerInitThreadPool.get().submit(this::getFingerprintDaemon, TAG + ".onStart");
}

}

2.2 创建 FingerprintServiceWrapper

我们先来看下 FingerprintServiceWrapper 这个类是干什么的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// frameworks/base/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java

public class FingerprintService extends BiometricServiceBase {

/**
* Receives the incoming binder calls from FingerprintManager.
*/
// FingerprintServiceWrapper 继承自 IFingerprintService.Stub
private final class FingerprintServiceWrapper extends IFingerprintService.Stub {
private static final int ENROLL_TIMEOUT_SEC = 60;

/**
* The following methods contain common code which is shared in biometrics/common.
*/
@Override // Binder call --> Binder 通信接口
public long preEnroll(IBinder token) {
checkPermission(MANAGE_FINGERPRINT);
return startPreEnroll(token);
}

@Override // Binder call --> Binder 通信接口
public int postEnroll(IBinder token) {
checkPermission(MANAGE_FINGERPRINT);
return startPostEnroll(token);
}

@Override // Binder call --> Binder 通信接口
public void enroll(final IBinder token, final byte[] cryptoToken, final int userId,
final IFingerprintServiceReceiver receiver, final int flags,
final String opPackageName) {
checkPermission(MANAGE_FINGERPRINT);

final boolean restricted = isRestricted();
final int groupId = userId; // default group for fingerprint enrollment
final EnrollClientImpl client = new EnrollClientImpl(getContext(), mDaemonWrapper,
mHalDeviceId, token, new ServiceListenerImpl(receiver), mCurrentUserId, groupId,
cryptoToken, restricted, opPackageName, new int[0] /* disabledFeatures */,
ENROLL_TIMEOUT_SEC) {
@Override
public boolean shouldVibrate() {
return true;
}

@Override
protected int statsModality() {
return FingerprintService.this.statsModality();
}
};

enrollInternal(client, userId);
}

... ...
}

}

如果你对 AIDL 比较了解,那么这里就很好理解了,这边搞了很多 Binder 通信的接口,那么谁来调用它?谁和 FingerprintService 通信?答案是:FingerprintManager

简单点来说,我们从上层获取到 FingerprintManager,然后可以通过 FingerprintManager 下发注册指纹或者识别等指令,这些指令会通过 AIDL 的方式传输到 FingerprintService,继而进行下面的工作。

2.3 this::getFingerprintDaemon

这个方法是干什么的?它的主要工作是 FingerprintServiceHAL 层进行通信,与底层交互。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// frameworks/base/services/core/java/com/android/server/biometrics/fingerprint/FingerprintService.java

public class FingerprintService extends BiometricServiceBase {

private IBiometricsFingerprint mDaemon;

/** Gets the fingerprint daemon */
private synchronized IBiometricsFingerprint getFingerprintDaemon() {
if (mDaemon == null) {
Slog.v(TAG, "mDaemon was null, reconnect to fingerprint");
try {
mDaemon = IBiometricsFingerprint.getService(); // 获取 IBiometricsFingerprint 服务
} catch (java.util.NoSuchElementException e) {
// Service doesn't exist or cannot be opened. Logged below.
} catch (RemoteException e) {
Slog.e(TAG, "Failed to get biometric interface", e);
}
... ...

}
return mDaemon;
}

}

2.3.1 IBiometricsFingerprint.getService

我们来看下这个服务的启动流程:

1
2
3
4
5
6
7
8
9
10
// hardware/interfaces/biometrics/fingerprint/2.1/default/android.hardware.biometrics.fingerprint@2.1-service.rc

service vendor.fps_hal /vendor/bin/hw/android.hardware.biometrics.fingerprint@2.1-service
# "class hal" causes a race condition on some devices due to files created
# in /data. As a workaround, postpone startup until later in boot once
# /data is mounted.
class late_start
user system
group system input uhid
writepid /dev/cpuset/system-background/tasks

我们可以看到,如上是启动了一个 android.hardware.biometrics.fingerprint@2.1-service,那这个服务里面是什么呢?

我们看下 Android.bp 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// hardware/interfaces/biometrics/fingerprint/2.1/default/Android.bp

cc_binary {
name: "android.hardware.biometrics.fingerprint@2.1-service",
defaults: ["hidl_defaults"],
init_rc: ["android.hardware.biometrics.fingerprint@2.1-service.rc"],
vendor: true,
relative_install_path: "hw",
srcs: [
"BiometricsFingerprint.cpp", // BiometricsFingerprint.cpp
"service.cpp", // service.cpp
],

shared_libs: [
"libcutils",
"liblog",
"libhidlbase",
"libhardware",
"libutils",
"android.hardware.biometrics.fingerprint@2.1",
],

}

跟踪 service.cpp :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// hardware/interfaces/biometrics/fingerprint/2.1/default/service.cpp

int main() {
// bio 是一个 IBiometricsFingerprint 类型的 sp 指针
android::sp<IBiometricsFingerprint> bio = BiometricsFingerprint::getInstance();

configureRpcThreadpool(1, true /*callerWillJoin*/);

if (bio != nullptr) {
if (::android::OK != bio->registerAsService()) { // 注册 BiometricsFingerprint
return 1;
}
} else {
ALOGE("Can't create instance of BiometricsFingerprint, nullptr");
}

joinRpcThreadpool();

return 0; // should never get here
}

2.3.2 mDaemon.setNotify

上面的分析,我们可以把 mDaemon 看成是 IBiometricsFingerprint 类的对象,那么这边就是调用了对象中的 setNotify 方法,但是这个方法不在 FingerprintService 中,那这个方法是怎么跳转的呢?

其实这边也是用到了 Binder(/dev/hwbinder) 通信,只不过不是 AIDL 的方法,而是 HIDL 的方式,这是 Android 8.0 新引入的 Binder 接口,使用的语言是 HIDL,后缀名为 .hal 文件。

通信双方路径如下:

1
2
// frameworks/base/services/core/java/com/android/server/fingerprint/FingerprintService.java
// hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp

HAL 文件路径如下:

1
2
// hardware/interfaces/biometrics/fingerprint/2.1/IBiometricsFingerprint.hal
// hardware/interfaces/biometrics/fingerprint/2.1/IBiometricsFingerprintClientCallback.hal

我们看下 IBiometricsFingerprint.hal 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// hardware/interfaces/biometrics/fingerprint/2.1/IBiometricsFingerprint.hal

package android.hardware.biometrics.fingerprint@2.1;

import IBiometricsFingerprintClientCallback;

interface IBiometricsFingerprint {
/**
* Set notification callback:
* Registers a user function that must receive notifications from the HAL
* This call must block if the HAL state machine is in busy state until HAL
* leaves the busy state.
*
* @return deviceId is a unique handle for this fingerprint device
*/
@callflow(next={"setActiveGroup"})
@entry
setNotify(IBiometricsFingerprintClientCallback clientCallback) // 看到了我们需要的接口
generates (uint64_t deviceId);

所以,FingerprintService 就是这样通过 hwbinder 与 HAL 层也就是 BiometricsFingerprint 进行通信。从 C/S 模型角度来看的话,FingerprintService 就相当于客户端,调用接口与服务端通信,而 BiometricsFingerprint 就相当于服务端,对相应的接口进行实现。

我们看看 BiometricsFingerprint 实现这个接口的源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
// hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp

// 具体实现
Return<uint64_t> BiometricsFingerprint::setNotify(
const sp<IBiometricsFingerprintClientCallback>& clientCallback) {
std::lock_guard<std::mutex> lock(mClientCallbackMutex);
mClientCallback = clientCallback;
// This is here because HAL 2.1 doesn't have a way to propagate a
// unique token for its driver. Subsequent versions should send a unique
// token for each call to setNotify(). This is fine as long as there's only
// one fingerprint device on the platform.
return reinterpret_cast<uint64_t>(mDevice);
}

2.3.3 mDaemon.setNotify(mDaemonCallback)

不知道你有没有发现,这个方法里面有个 mDaemonCallback 参数,这个参数干嘛用的?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// hardware/interfaces/biometrics/fingerprint/2.1/IBiometricsFingerprint.hal

package android.hardware.biometrics.fingerprint@2.1;

import IBiometricsFingerprintClientCallback;

interface IBiometricsFingerprint {
/**
* Set notification callback:
* Registers a user function that must receive notifications from the HAL
* This call must block if the HAL state machine is in busy state until HAL
* leaves the busy state.
*
* @return deviceId is a unique handle for this fingerprint device
*/
@callflow(next={"setActiveGroup"})
@entry
setNotify(IBiometricsFingerprintClientCallback clientCallback) // clientCallback 有什么用?
generates (uint64_t deviceId);

我可以直接告诉你它是用作 回调 用的。回调?干嘛要回调?

我们先来看下指纹录入正常流程:APP 下发注册命令 -> FingerprintManager 收到命令 -> FingerprintService 收到命令 -> BiometricsFingerprint 收到命令 -> Fingerprint.cpp 收到命令 -> 指纹 CA 收到命令 -> 指纹 TA 收到命令 -> SPI 采集数据\算法进行注册等。

从上到下的流程清清楚楚,但是有个问题,上层怎么知道底层的流程有没有走完了呢,我得通过某种方式告知上层我这边的任务完成了啊?所以,这就是 clientCallback 的作用,回调告知上层底层处理完毕!

2.4 BiometricsFingerprint::getInstance

我们回头来分析 BiometricsFingerprint::getInstance() 的具体操作细节:

1
2
3
4
5
6
7
8
// hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp

IBiometricsFingerprint* BiometricsFingerprint::getInstance() {
if (!sInstance) {
sInstance = new BiometricsFingerprint(); // 构造了一个 BiometricsFingerprint 类
}
return sInstance;
}

2.4.1 new BiometricsFingerprint

1
2
3
4
5
6
7
8
9
// hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp

BiometricsFingerprint::BiometricsFingerprint() : mClientCallback(nullptr), mDevice(nullptr) {
sInstance = this; // sInstance 就是 BiometricsFingerprint 对象本身
mDevice = openHal(); // mDevice 就是 HAL 里面的设备
if (!mDevice) {
ALOGE("Can't open HAL module");
}
}

2.4.2 BiometricsFingerprint.openHal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// hardware/interfaces/biometrics/fingerprint/2.1/default/BiometricsFingerprint.cpp

fingerprint_device_t* BiometricsFingerprint::openHal() {
int err;
const hw_module_t *hw_mdl = nullptr;
ALOGD("Opening fingerprint hal library...");
// 通过查找模块 FINGERPRINT_HARDWARE_MODULE_ID 找到,然后调用里面的 open 方法得到设备
if (0 != (err = hw_get_module(FINGERPRINT_HARDWARE_MODULE_ID, &hw_mdl))) {
ALOGE("Can't open fingerprint HW Module, error: %d", err);
return nullptr;
}

if (hw_mdl == nullptr) {
ALOGE("No valid fingerprint module");
return nullptr;
}

fingerprint_module_t const *module =
reinterpret_cast<const fingerprint_module_t*>(hw_mdl);
if (module->common.methods->open == nullptr) {
ALOGE("No valid open method");
return nullptr;
}

hw_device_t *device = nullptr;

if (0 != (err = module->common.methods->open(hw_mdl, nullptr, &device))) {
ALOGE("Can't open fingerprint methods, error: %d", err);
return nullptr;
}

if (kVersion != device->version) {
// enforce version on new devices because of HIDL@2.1 translation layer
ALOGE("Wrong fp version. Expected %d, got %d", kVersion, device->version);
return nullptr;
}

fingerprint_device_t* fp_device =
reinterpret_cast<fingerprint_device_t*>(device);

if (0 != (err =
fp_device->set_notify(fp_device, BiometricsFingerprint::notify))) {
ALOGE("Can't register fingerprint module callback, error: %d", err);
return nullptr;
}

return fp_device;
}

2.4.3 fingerprint.FINGERPRINT_HARDWARE_MODULE_ID

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// hardware/libhardware/modules/fingerprint/fingerprint.c

static struct hw_module_methods_t fingerprint_module_methods = {
.open = fingerprint_open, // 定义了open方法
};

fingerprint_module_t HAL_MODULE_INFO_SYM = {
.common = {
.tag = HARDWARE_MODULE_TAG,
.module_api_version = FINGERPRINT_MODULE_API_VERSION_2_0,
.hal_api_version = HARDWARE_HAL_API_VERSION,
.id = FINGERPRINT_HARDWARE_MODULE_ID,
.name = "Demo Fingerprint HAL",
.author = "The Android Open Source Project",
.methods = &fingerprint_module_methods,
},
};

2.4.4 fingerprint.fingerprint_open

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// hardware/libhardware/modules/fingerprint/fingerprint.c

static int fingerprint_open(const hw_module_t* module, const char __unused *id,
hw_device_t** device)
{
if (device == NULL) {
ALOGE("NULL device on open");
return -EINVAL;
}

// 这里创建好了设备,并且对注册、识别等接口都进行了定义
fingerprint_device_t *dev = malloc(sizeof(fingerprint_device_t));
memset(dev, 0, sizeof(fingerprint_device_t));

dev->common.tag = HARDWARE_DEVICE_TAG;
dev->common.version = FINGERPRINT_MODULE_API_VERSION_2_0;
dev->common.module = (struct hw_module_t*) module;
dev->common.close = fingerprint_close;

dev->pre_enroll = fingerprint_pre_enroll;
dev->enroll = fingerprint_enroll;
dev->get_authenticator_id = fingerprint_get_auth_id;
dev->cancel = fingerprint_cancel;
dev->remove = fingerprint_remove;
dev->set_active_group = fingerprint_set_active_group;
dev->authenticate = fingerprint_authenticate;
dev->set_notify = set_notify_callback;
dev->notify = NULL;

*device = (hw_device_t*) dev;
return 0;
}

综上,我们可以看出指纹的注册流程:FingerprintService.java->BiometricsFingerprint.cpp->fingerprint.c

2.4.5 fingerprint_enroll

我们举个例子,看下指纹注册的方法:

1
2
3
4
5
6
7
8
// hardware/libhardware/modules/fingerprint/fingerprint.c

static int fingerprint_enroll(struct fingerprint_device __unused *dev,
const hw_auth_token_t __unused *hat,
uint32_t __unused gid,
uint32_t __unused timeout_sec) {
return FINGERPRINT_ERROR; // 这边默认直接返回 error,需要指纹厂商自行实现相关功能
}