[Android]从app的trace打桩原理回顾zygote的fork

在前面http://t.csdn.cn/X3l0a 的讨论中,我们了解到,系统中是通过获取属性值,来判断trace点记录是否需要打印(记录),

system/core/libutils/Trace.cpp

20static void traceInit() __attribute__((constructor));
21
22static void traceInit() {
23    ::android::add_sysprop_change_callback(atrace_update_tags, 0);
24}

通过这样的方式,只要引用了这个库,在main函数开始,就会执行traeInit方法,来设置属性变化的回调函数。用来监控相应的属性值。

应用中,一般可以通过Trace.traceBegin方法来进行trace打桩,

也是获取到属性的变化,判断执行的时候,是否需要处理这个打桩,

属性的获取是在这里,是从atrace_update_tags方法里调用过去的,

system/core/libcutils/trace-dev.inc

61// Check whether the given command line matches one of the comma-separated
62// values listed in the app_cmdlines property.
63static bool atrace_is_cmdline_match(const char* cmdline)
64{
65    int count = property_get_int32("debug.atrace.app_number", 0);
66
67    char buf[PROPERTY_KEY_MAX];
68    char value[PROPERTY_VALUE_MAX];
69
70    for (int i = 0; i < count; i++) {
71        snprintf(buf, sizeof(buf), "debug.atrace.app_%d", i);
72        property_get(buf, value, "");
73        if (strcmp(value, "*") == 0 || strcmp(value, cmdline) == 0) {
74            return true;
75        }
76    }
77
78    return false;
79}
80

应用中看上去并不需要设置属性变化的回调函数,为什么接收到来自AMS的属性变化binder通知后,自动的就可以执行回调函数,获取到相应的属性值变化呢?

其实在应用app诞生的时候,就已经具备了这个功能,设置了回调函数atrace_update_tags,因为这个设置是在zygote里就进行好的,zygote 进程fork出app进程后,app进程已经天然的具备这个功能。

frameworks/base/cmds/app_process/app_main.cpp 里,已经引用了trace

#include 

app_process编译中,已经添加了cutils库,包含了traceInit方法,

3app_process_common_shared_libs := \
4    libandroid_runtime \
5    libbinder \
6    libcutils \
7    libdl \
8    libhwbinder \
9    liblog \
10    libnativeloader \
11    libutils \
12

我们可以添加log来进行验证。

可以看到,在ZygoteInit里,已经可以进行trace打桩了

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

902    public static final Runnable zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader) {
903        if (RuntimeInit.DEBUG) {
904            Slog.d(RuntimeInit.TAG, "RuntimeInit: Starting application from zygote");
905        }
906
907        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ZygoteInit");
908        RuntimeInit.redirectLogStreams();
909
910        RuntimeInit.commonInit();
911        ZygoteInit.nativeZygoteInit();
912        return RuntimeInit.applicationInit(targetSdkVersion, argv, classLoader);
913    }

从app可以天生具备执行traceInit的这个角度,可以让我们加深对zygote的理解,zygote里的特性,其子进程也可以具备。

你可能感兴趣的:(Android,zygote)