Android 系统属性 Property

最近调试zygote进程的镜像恢复,发现重新设置系统语言或情景模式后,再开机不起作用。经调试发现是用get_property的到的值与实际文件中的值不符。

只能分析下property的过程。

Android开机后的init.c的主要工作:

queue_builtin_action(property_init_action, "property_init");

queue_builtin_action(set_init_properties_action, "set_init_properties");

queue_builtin_action(property_service_init_action, "property_service_init");

queue_builtin_action(queue_property_triggers_action, "queue_propety_triggers");

上面是几个跟property相关的初始化动作加入队列中,

接着在init.cfor循环里有下面的代码

 

int property_set_fd_init = 0;

。。。

for(;;) {

             execute_one_command();

            。。。

        if (!property_set_fd_init && get_property_set_fd() > 0) {

            ufds[fd_count].fd = get_property_set_fd();

            ufds[fd_count].events = POLLIN;

            ufds[fd_count].revents = 0;

            fd_count++;

            property_set_fd_init = 1;

        }

        。。。

 

        for (i = 0; i < fd_count; i++) {

            if (ufds[i].revents == POLLIN) {

                if (ufds[i].fd == get_property_set_fd())

                    handle_property_set_fd();

                else 。。。。

            }

        }

}

在这个for循环里会用execute_one_command();去执行队列中的代码,可以看到会去执行上面已经提到的这几个。

queue_builtin_action(property_init_action, "property_init");

queue_builtin_action(set_init_properties_action, "set_init_properties");

queue_builtin_action(property_service_init_action, "property_service_init");

queue_builtin_action(queue_property_triggers_action, "queue_propety_triggers");

其实是依次执行

property_init_action

set_init_properties_action

property_service_init_action

queue_property_triggers_action

并且当get_property_set_fd条件满足(property_service_init_action被执行)后,会去处理handle_property_set_fd(),也就是init最后充当ufds[]里那几个句柄的server

现在来逐步分析

A.      property_init_action

里面调的是property_service.c里的

   property_init

           init_property_area

           load_properties_from_file(“/default.prop”);

其中init_property_area是初始化一块内存,

load _properties_from_file则读取一些默认的属性

init_property_area初始化一块内存进行共享,而load_properties_from_file则读取一些默认的属性。

init_property_area

 

static int init_property_area(void)
{
    prop_area *pa;
 
    if(pa_info_array)
        return -1;
 
    if(init_workspace(&pa_workspace, PA_SIZE))//PA_SIZE = 32168
        return -1;
 
    fcntl(pa_workspace.fd, F_SETFD, FD_CLOEXEC);
 
    pa_info_array = (void*) (((char*) pa_workspace.data) + PA_INFO_START);//PA_INFO_START = 1024
 
    pa = pa_workspace.data;
    memset(pa, 0, PA_SIZE);
    pa->magic = PROP_AREA_MAGIC;
    pa->version = PROP_AREA_VERSION;
 
        /* plug into the lib property services */
    __system_property_area__ = pa;
    property_area_inited = 1;
    return 0;
}

可以看到init_workspace()后,将__system_property_area__作为prop_area,以后属性就从内存中读取了。出错的关键肯定是init_workspace里做了文件映射到内存的动作,导致镜像恢复后内存和文件中的内容不符合

static int init_workspace(workspace *w, size_t size)
{
    void *data;
    int fd;

        /* dev is a tmpfs that we can use to carve a shared workspace
         * out of, so let's do that...
         */
    fd = open("/dev/__properties__", O_RDWR | O_CREAT, 0600);
    if (fd < 0)
        return -1;

    if (ftruncate(fd, size) < 0)
        goto out;

    data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(data == MAP_FAILED)
        goto out;

    close(fd);

    fd = open("/dev/__properties__", O_RDONLY);
    if (fd < 0)
        return -1;

    unlink("/dev/__properties__");

    w->data = data;
    w->size = size;
    w->fd = fd;
    return 0;

out:
    close(fd);
    return -1;
}


果然init_workspace里有mmap的动作,但是这个是init进程的,怎么传递给zygote进程的呢?带会儿再注意下。

unlink("/dev/__properties__")会删除文件。如果该文件名为最后连接点,但有其他进程打开了此文件,则在所有关于此文件的描述符皆关闭后才会删除。如果参数/dev/__properties__为一符号连接,则此连接会被删除,在本函数中返回0的时候不会被删除

init_property_area()完成之后,就会调用load_properties_from_file(PROP_PATH_RAMDISK_DEFAULT);//"/default.prop"装载默认的属性值

static void load_properties_from_file(const char *fn)
{
    char *data;
    unsigned sz;

    data = read_file(fn, &sz);

    if(data != 0) {
        load_properties(data);
        free(data);
    }
}

看看default.prop中的内容: cat /dafult.prope
persist.msms.phone_count=1
ro.secure=0
ro.allow.mock.location=1
ro.debuggable=1
persist.service.adb.enable=1

先用read_file读出来,然后用load_properties加载属性,恢复zygote进程镜像后是否可以用load_properties重新加载一次呢,

难点是不确定哪些文件改动了要重新记载。

static void load_properties(char *data)
{
    char *key, *value, *eol, *sol, *tmp;

    sol = data;
    while((eol = strchr(sol, '\n'))) {
        key = sol;
        *eol++ = 0;
        sol = eol;

        value = strchr(key, '=');
        if(value == 0) continue;
        *value++ = 0;

        while(isspace(*key)) key++;
        if(*key == '#') continue;
        tmp = value - 2;
        while((tmp > key) && isspace(*tmp)) *tmp-- = 0;

        while(isspace(*value)) value++;
        tmp = eol - 2;
        while((tmp > value) && isspace(*tmp)) *tmp-- = 0;

        property_set(key, value);
    }
}
上面的property_set调的是本文件property_service.c中的property_set,而不是libcutils中Properties.c中的property_set
int property_set(const char *name, const char *value)
{
    prop_area *pa;
    prop_info *pi;

    int namelen = strlen(name);
    int valuelen = strlen(value);

    if(namelen >= PROP_NAME_MAX) return -1;
    if(valuelen >= PROP_VALUE_MAX) return -1;
    if(namelen < 1) return -1;

    pi = (prop_info*) __system_property_find(name);

    if(pi != 0) {
        /* ro.* properties may NEVER be modified once set */
        if(!strncmp(name, "ro.", 3) &&
          !(!strncmp(name+3, "hisense", 7) || !strncmp(name+3, "mbbms", 5) || !strncmp(name+3, "bootmode", 8))) return -1;

        pa = __system_property_area__;
        update_prop_info(pi, value, valuelen);
        pa->serial++;
        __futex_wake(&pa->serial, INT32_MAX);
    } else {
        pa = __system_property_area__;
        if(pa->count == PA_COUNT_MAX) return -1;

        pi = pa_info_array + pa->count;
        pi->serial = (valuelen << 24);
        memcpy(pi->name, name, namelen + 1);
        memcpy(pi->value, value, valuelen + 1);

        pa->toc[pa->count] =
            (namelen << 24) | (((unsigned) pi) - ((unsigned) pa));

        pa->count++;
        pa->serial++;
        __futex_wake(&pa->serial, INT32_MAX);
    }
    /* If name starts with "net." treat as a DNS property. */
    if (strncmp("net.", name, strlen("net.")) == 0)  {
        if (strcmp("net.change", name) == 0) {
            return 0;
        }
       /*
        * The 'net.change' property is a special property used track when any
        * 'net.*' property name is updated. It is _ONLY_ updated here. Its value
        * contains the last updated 'net.*' property.
        */
        property_set("net.change", name);
    } else if (persistent_properties_loaded &&
            strncmp("persist.", name, strlen("persist.")) == 0) {
        /*
         * Don't write properties to disk until after we have read all default properties
         * to prevent them from being overwritten by default values.
         */
        write_persistent_property(name, value);
    }
    property_changed(name, value);
    return 0;
}


对于是persist.的,则调write_persistent_property()写入文件中,所以问题就出在这里,文件被更改,如果zygote从镜像恢复,zygote内存中的属性没有体现实际文件中的内容。

但是这里的疑问是zygote进程是着怎么把__system_property_area__作了镜像的,因为目前看到的都是init进程做property的操作,和zygote进程是怎么联系上的呢?

这里想到一个做法:当有write_persistent_property的时候,把保存的zygote进程镜像删除,重新做镜像。
将其以独立文件的形式保存到data/property目录中,接着调用property_changed通知属性已经改变,是否有相应的action操作

查找以”property:“打头的action,如果相应action需要的条件成立,则调用action_add_queue_tail触发相应的action我们可以看一下init.rc中与property有关的action

static void write_persistent_property(const char *name, const char *value)
{
    const char *tempPath = PERSISTENT_PROPERTY_DIR "/.temp";
    char path[PATH_MAX];
    int fd, length;

    snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, name);

    fd = open(tempPath, O_WRONLY|O_CREAT|O_TRUNC, 0600);
    if (fd < 0) {
        ERROR("Unable to write persistent property to temp file %s errno: %d\n", tempPath, errno);
        return;
    }
    write(fd, value, strlen(value));
    close(fd);

    if (rename(tempPath, path)) {
        unlink(tempPath);
        ERROR("Unable to rename persistent property file %s to %s\n", tempPath, path);
    }
}

 

B.      set_init_properties_action

        设置一些属性

static int set_init_properties_action(int nargs, char **args)
{
    char tmp[PROP_VALUE_MAX];

    if (qemu[0])
        import_kernel_cmdline(1);

    if (calibration[0]) {
        PRINT("###: set ro.calibration 1.\n");
        property_set("ro.calibration", "1");
    }
    else {
        PRINT("###: set ro.calibration 0.\n");
        property_set("ro.calibration", "0");
    }

    /* In fastsleep mode. */
    if (!strcmp(bootmode,"fastsleep")) {
        PRINT("###: fastsleep mode.\n");
        PRINT("###: fastsleep mode.\n");
        PRINT("###: fastsleep mode.\n");
        property_set("ro.fastsleep", "1");
        fastsleep_enable = 1;
    }


    if (!strcmp(bootmode,"factory"))
        property_set("ro.factorytest", "1");
    else if (!strcmp(bootmode,"factory2"))
        property_set("ro.factorytest", "2");
    else
        property_set("ro.factorytest", "0");

    property_set("ro.serialno", serialno[0] ? serialno : "");
    property_set("ro.bootmode", bootmode[0] ? bootmode : "unknown");
    property_set("ro.baseband", baseband[0] ? baseband : "unknown");
    property_set("ro.carrier", carrier[0] ? carrier : "unknown");
    property_set("ro.bootloader", bootloader[0] ? bootloader : "unknown");

    property_set("ro.hardware", hardware);
    snprintf(tmp, PROP_VALUE_MAX, "%d", revision);
    property_set("ro.revision", tmp);
    return 0;
}


C.      property_service_init_action

static int property_service_init_action(int nargs, char **args)
{
    /* read any property files on system or data and
     * fire up the property service.  This must happen
     * after the ro.foo properties are set above so
     * that /data/local.prop cannot interfere with them.
     */
    start_property_service();
    return 0;
}


 

void start_property_service(void)
{
    int fd;

    load_properties_from_file(PROP_PATH_SYSTEM_BUILD);
    load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT);
    load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
    /* Read persistent properties after all default values have been loaded. */
    load_persistent_properties();

    fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM, 0666, 0, 0);
    if(fd < 0) return;
    fcntl(fd, F_SETFD, FD_CLOEXEC);
    fcntl(fd, F_SETFL, O_NONBLOCK);

    listen(fd, 8);
    property_set_fd = fd;
}

load_properties_from_file从几个文件装载系统和本地属性,load_persistent_properties装载永久属性,调用create_socket创建一个server端的socket用于和其它需要设置属性的进程通信,最后这个property_set_fd给init进程用,init进程充当property service功能

static void load_persistent_properties()
{
    DIR* dir = opendir(PERSISTENT_PROPERTY_DIR);
    struct dirent*  entry;
    char path[PATH_MAX];
    char value[PROP_VALUE_MAX];
    int fd, length;

    if (dir) {
        while ((entry = readdir(dir)) != NULL) {
            if (strncmp("persist.", entry->d_name, strlen("persist.")))
                continue;
#if HAVE_DIRENT_D_TYPE
            if (entry->d_type != DT_REG)
                continue;
#endif
            /* open the file and read the property value */
            snprintf(path, sizeof(path), "%s/%s", PERSISTENT_PROPERTY_DIR, entry->d_name);
            fd = open(path, O_RDONLY);
            if (fd >= 0) {
                length = read(fd, value, sizeof(value) - 1);
                if (length >= 0) {
                    value[length] = 0;
                    property_set(entry->d_name, value);
                } else {
                    ERROR("Unable to read persistent property file %s errno: %d\n", path, errno);
                }
                close(fd);
            } else {
                ERROR("Unable to open persistent property file %s errno: %d\n", path, errno);
            }
        }
        closedir(dir);
    } else {
        ERROR("Unable to open persistent property directory %s errno: %d\n", PERSISTENT_PROPERTY_DIR, errno);
    }

    persistent_properties_loaded = 1;
}


这里想到了是否zygote进程镜像恢复后,做load_persistent_properties里的动作。在init.c的for循环里有调restart_processes启动服务

restart_service_if_needed --> service_start

    pid = fork();

    if (pid == 0) {
        struct socketinfo *si;
        struct svcenvinfo *ei;
        char tmp[32];
        int fd, sz;

        if (properties_inited()) {
            get_property_workspace(&fd, &sz);
            sprintf(tmp, "%d,%d", dup(fd), sz);
            add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);
        }

可见,当属性初始化了(properties_inited), 然后add_environment("ANDROID_PROPERTY_WORKSPACE", tmp);添加到init进程的系统环境变量中

D.      queue_property_triggers_action

      把init.rc里perty:"等加到队列中

void queue_all_property_triggers()
{
    struct listnode *node;
    struct action *act;
    list_for_each(node, &action_list) {
        act = node_to_item(node, struct action, alist);
        if (!strncmp(act->name, "property:", strlen("property:"))) {
            /* parse property name and value
               syntax is property:<name>=<value> */
            const char* name = act->name + strlen("property:");
            const char* equals = strchr(name, '=');
            if (equals) {
                char prop_name[PROP_NAME_MAX + 1];
                const char* value;
                int length = equals - name;
                if (length > PROP_NAME_MAX) {
                    ERROR("property name too long in trigger %s", act->name);
                } else {
                    memcpy(prop_name, name, length);
                    prop_name[length] = 0;

                    /* does the property exist, and match the trigger value? */
                    value = property_get(prop_name);
                    if (value && !strcmp(equals + 1, value)) {
                        action_add_queue_tail(act);
                    }
                }
            }
        }
    }
}


E. handle_property_set_fd

void handle_property_set_fd()
{
    prop_msg msg;
    int s;
    int r;
    int res;
    struct ucred cr;
    struct sockaddr_un addr;
    socklen_t addr_size = sizeof(addr);
    socklen_t cr_size = sizeof(cr);

    if ((s = accept(property_set_fd, (struct sockaddr *) &addr, &addr_size)) < 0) {
        return;
    }

    /* Check socket options here */
    if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) {
        close(s);
        ERROR("Unable to recieve socket options\n");
        return;
    }

    r = recv(s, &msg, sizeof(msg), 0);
    close(s);
    if(r != sizeof(prop_msg)) {
        ERROR("sys_prop: mis-match msg size recieved: %d expected: %d\n",
              r, sizeof(prop_msg));
        return;
    }

    switch(msg.cmd) {
    case PROP_MSG_SETPROP:
        msg.name[PROP_NAME_MAX-1] = 0;
        msg.value[PROP_VALUE_MAX-1] = 0;

        if(memcmp(msg.name,"ctl.",4) == 0) {
            if (check_control_perms(msg.value, cr.uid, cr.gid)) {
                handle_control_message((char*) msg.name + 4, (char*) msg.value);
            } else {
                ERROR("sys_prop: Unable to %s service ctl [%s] uid: %d pid:%d\n",
                        msg.name + 4, msg.value, cr.uid, cr.pid);
            }
        } else {
            if (check_perms(msg.name, cr.uid, cr.gid)) {
                property_set((char*) msg.name, (char*) msg.value);
            } else {
                ERROR("sys_prop: permission denied uid:%d gid:%d name:%s\n",
                      cr.uid, cr.gid, msg.name);
            }
        }
        break;

    default:
        break;
    }
}


最后分析下zygote的内存镜像为何会保存property的内存区域

前面提到的__system_property_area__是在bionic里定义的,在libcutils.so里,所以在不同的进程中这个__system_property_area__是互相独立的。在加载libcutils.so的时候,会调用__libc_init_common,__libc_init_common会调用system_properties.c里的__system_properties_init

int __system_properties_init(void)
{
    prop_area *pa;
    int s, fd;
    unsigned sz;
    char *env;

    if(__system_property_area__ != ((void*) &dummy_props)) {
        return 0;
    }

    env = getenv("ANDROID_PROPERTY_WORKSPACE");
    if (!env) {
        return -1;
    }
    fd = atoi(env);
    env = strchr(env, ',');
    if (!env) {
        return -1;
    }
    sz = atoi(env + 1);
    
    pa = mmap(0, sz, PROT_READ, MAP_SHARED, fd, 0);
    
    if(pa == MAP_FAILED) {
        return -1;
    }

    if((pa->magic != PROP_AREA_MAGIC) || (pa->version != PROP_AREA_VERSION)) {
        munmap(pa, sz);
        return -1;
    }

    __system_property_area__ = pa;
    return 0;
}


这里获取环境变量,重新设置property区域,可以看到,当zygote进程镜像恢复后,里面的值仍然是以前的内存区域的值,

在java_lang_ProcessManager.cpp里ProcessManager_staticInitialize的native函数给JAVA调了,在java里调ProcessManager.staticInitialize可以重新初始化静态变量

static void ProcessManager_staticInitialize(JNIEnv* env,
        jclass clazz) {
#ifdef ANDROID
    char* fdString = getenv("ANDROID_PROPERTY_WORKSPACE");
    if (fdString) {
        androidSystemPropertiesFd = atoi(fdString);
    }
#endif

    onExitMethod = env->GetMethodID(clazz, "onExit", "(II)V");
    if (onExitMethod == NULL) {
        return;
    }
}


 

你可能感兴趣的:(android,android,property)