Android 系统属性(SystemProperties)介绍
我們在開發過程中有時需要使用系統屬性,例如獲取系統軟件版本,獲取設備名名稱等;有時也需要設置自己的屬性,為了全面的介紹系統屬性,本文將基于Android 10(Q)來介紹Android的屬性使用,圍繞以下幾點問題展開介紹:
- prop的作用,如何調試和使用?
- prop實現原理,代碼流程,prop存儲在哪里,何時init?
- 如何添加自定義prop?
系統屬性簡單來說是用來存儲系統中某些鍵值對數據,具有全局性、存取靈活方便的特點。
一、終端prop命令
在終端設備中,可以通過以下命令進行prop調試。
1.1、查看prop
#查看系統所有props $getprop ... [persist.sys.timezone]: [Asia/Shanghai] //時區 [ro.system.build.type]: [userdebug] //系統編譯類型 [vendor.display.lcd_density]: [320] //屏幕密度 ...#獲取時區屬性persist.sys.timezone的值 $getprop persist.sys.timezone Asia/Shanghai#過濾屬性名或屬性值含有關鍵字"timezone"的屬性 $getprop | grep timezone [persist.sys.timezone]: [Asia/Shanghai]#獲取不存在的屬性時結果為空 $getprop hello1.2、設置prop
$getprop my.prop.test //屬性my.prop.test為空 $setprop my.prop.test 123 //設置屬性my.prop.test為123 $getprop my.prop.test //獲取屬性my.prop.test為123 123setprop 可以給屬性設置int、bool、string等基本類型
1.3、監聽prop
顯示屬性值發生變化的值
$watchprops [my.prop.test]: [123456]二、get和set prop代碼流程
2.1、get和set prop代碼流程圖
涉及的代碼路徑匯總如下:
frameworks\base\core\java\android\os\SystemProperties.java frameworks\base\core\jni\android_os_SystemProperties.cpp system\core\base\properties.cpp system\core\init\main.cpp system\core\init\init.cpp system\core\init\property_service.cpp system\core\property_service\libpropertyinfoparser\property_info_parser.cpp bionic\libc\include\sys\_system_properties.h bionic\libc\include\sys\system_properties.h bionic\libc\bionic\system_property_set.cpp bionic\libc\bionic\system_property_api.cpp bionic\libc\system_properties\contexts_serialized.cpp bionic\libc\system_properties\system_properties.cpp bionic\libc\system_properties\prop_area.cpp代碼流程整體時序圖如下:
系統屬性架構設計如下:
2.2、代碼流程介紹
frameworks\base\core\java\android\os\SystemProperties.java
Systemproperties類在android.os包下,因此使用時需要
SystemProperties提供了setprop和多種返回數據類型的getprop,采用鍵值對(key-value)的數據格式進行操作,具體如下:
public class SystemProperties { ... public static final int PROP_VALUE_MAX = 91; @UnsupportedAppUsageprivate static native String native_get(String key);private static native String native_get(String key, String def);private static native int native_get_int(String key, int def);@UnsupportedAppUsageprivate static native long native_get_long(String key, long def);private static native boolean native_get_boolean(String key, boolean def);private static native void native_set(String key, String def);private static native void native_add_change_callback();private static native void native_report_sysprop_change(); ...//獲取屬性key的值,如果沒有該屬性則返回默認值defpublic static String get(@NonNull String key, @Nullable String def) {if (TRACK_KEY_ACCESS) onKeyAccess(key);return native_get(key, def);} ...//設置屬性key的值為val,其不可為空、不能是"ro."開頭的只讀屬性//長度不能超過PROP_VALUE_MAX(91)public static void set(@NonNull String key, @Nullable String val) {if (val != null && !val.startsWith("ro.") && val.length() > PROP_VALUE_MAX) {throw new IllegalArgumentException("value of system property '" + key+ "' is longer than " + PROP_VALUE_MAX + " characters: " + val);}if (TRACK_KEY_ACCESS) onKeyAccess(key);native_set(key, val);} }通過JNI上述 native_set()和native_get()走到
frameworks\base\core\jni\android_os_SystemProperties.cpp
跟著調用關系,接著進入:
system\core\base\properties.cpp
觀察流程圖會發現這里會出現“岔路”,查詢和設置屬性的接口暫時走向不同文件接口
2.2.1、set prop流程
_system_properties.h頭文件定義PROP_SERVICE_NAME
bionic\libc\include\sys\_system_properties.h
bionic\libc\bionic\system_property_set.cpp
static const char property_service_socket[] = "/dev/socket/" PROP_SERVICE_NAME; static const char* kServiceVersionPropertyName = "ro.property_service.version"; ... int __system_property_set(const char* key, const char* value) {if (g_propservice_protocol_version == 0) {detect_protocol_version();//獲取屬性服務協議版本}//舊協議版本限定prop name最大長度為PROP_NAME_MAX,prop val最大長度為PROP_VALUE_MAXif (g_propservice_protocol_version == kProtocolVersion1) {//在bionic\libc\include\sys\system_properties.h中定義//#define PROP_NAME_MAX 32//#define PROP_VALUE_MAX 92if (strlen(key) >= PROP_NAME_MAX) return -1;if (strlen(value) >= PROP_VALUE_MAX) return -1;...return send_prop_msg(&msg);//send_prop_msg()也通過Socket與property_service進行通信} else {//進入新版本協議,僅對prop val長度有要求,不超過92,且屬性不為只讀屬性// New protocol only allows long values for ro. properties only.if (strlen(value) >= PROP_VALUE_MAX && strncmp(key, "ro.", 3) != 0) return -1;...SocketWriter writer(&connection);//通過Socket與property_service進行通信...} ... static const char* kServiceVersionPropertyName = "ro.property_service.version"; static constexpr uint32_t kProtocolVersion1 = 1; static constexpr uint32_t kProtocolVersion2 = 2; // current static atomic_uint_least32_t g_propservice_protocol_version = 0; static void detect_protocol_version() {//從ro.property_service.version中獲取協議版本,可在平臺終端getprop ro.property_service.version//在后續2.2.5小節中可找到設置該屬性的位置if (__system_property_get(kServiceVersionPropertyName, value) == 0) {g_propservice_protocol_version = kProtocolVersion1;} else {uint32_t version = static_cast<uint32_t>(atoll(value));if (version >= kProtocolVersion2) {g_propservice_protocol_version = kProtocolVersion2;} else {g_propservice_protocol_version = kProtocolVersion1;}... }2.2.2、屬性服務(property_service)
流程到了這里會發現,最終需要通過Socket與property_service來通信進行設置屬性值,那么問題來了:
- property_service是誰創建的?
- property_service是怎么啟動的?
- property_service是如何setprop的?
熟悉Android開機流程的同學會馬上聯想到init進程,property_service正是init進程來初始化和啟動的。
system\core\init\init.cpp
int SecondStageMain(int argc, char** argv) {...property_init();//屬性初始化...property_load_boot_defaults(load_debug_prop);//加載開機默認屬性配置StartPropertyService(&epoll);//啟動屬性服務... }2.2.3、屬性初始化
system\core\init\property_service.cpp
void property_init() {mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH);CreateSerializedPropertyInfo();//創建屬性信息property_infoif (__system_property_area_init()) {//創建共享內存LOG(FATAL) << "Failed to initialize property area";}if (!property_info_area.LoadDefaultPath()) {LOG(FATAL) << "Failed to load serialized property info file";} } ... ... //讀取selinux模塊中的property相關文件,解析并加載到property_info中 void CreateSerializedPropertyInfo() {auto property_infos = std::vector<PropertyInfoEntry>();if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts",&property_infos)) {return;}// Don't check for failure here, so we always have a sane list of properties.// E.g. In case of recovery, the vendor partition will not have mounted and we// still need the system / platform properties to function.if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts",&property_infos)) {// Fallback to nonplat_* if vendor_* doesn't exist.LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts",&property_infos);}if (access("/product/etc/selinux/product_property_contexts", R_OK) != -1) {LoadPropertyInfoFromFile("/product/etc/selinux/product_property_contexts",&property_infos);}if (access("/odm/etc/selinux/odm_property_contexts", R_OK) != -1) {LoadPropertyInfoFromFile("/odm/etc/selinux/odm_property_contexts", &property_infos);}} else {if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) {return;}if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) {// Fallback to nonplat_* if vendor_* doesn't exist.LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);}LoadPropertyInfoFromFile("/product_property_contexts", &property_infos);LoadPropertyInfoFromFile("/odm_property_contexts", &property_infos);}auto serialized_contexts = std::string();auto error = std::string();if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,&error)) {LOG(ERROR) << "Unable to serialize property contexts: " << error;return;}//將序列化屬性寫入/dev/__properties__/property_infoconstexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info";if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) {PLOG(ERROR) << "Unable to write serialized property infos to file";}selinux_android_restorecon(kPropertyInfosPath, 0); }bionic\libc\bionic\system_property_api.cpp
int __system_property_area_init() {bool fsetxattr_failed = false;return system_properties.AreaInit(PROP_FILENAME, &fsetxattr_failed) && !fsetxattr_failed ? 0 : -1; }初始化屬性內存共享區域
bionic\libc\system_properties\system_properties.cpp
bionic\libc\system_properties\contexts_serialized.cpp
bool ContextsSerialized::Initialize(bool writable, const char* filename, bool* fsetxattr_failed) {filename_ = filename;if (!InitializeProperties()) {return false;}... } bool ContextsSerialized::InitializeProperties() {if (!property_info_area_file_.LoadDefaultPath()) {return false;}... }system\core\property_service\libpropertyinfoparser\property_info_parser.cpp
bool PropertyInfoAreaFile::LoadDefaultPath() {return LoadPath("/dev/__properties__/property_info"); } bool PropertyInfoAreaFile::LoadPath(const char* filename) {int fd = open(filename, O_CLOEXEC | O_NOFOLLOW | O_RDONLY);...void* map_result = mmap(nullptr, mmap_size, PROT_READ, MAP_SHARED, fd, 0);... }__system_property_area_init()經過一系列的方法調用,最終通過mmap()將/dev/__property __/property_info加載到共享內存。
2.2.4、加載開機默認屬性配置
接著init進程中property_load_boot_defaults(load_debug_prop)函數分析
system\core\init\property_service.cpp
從上面代碼可以看出從多個屬性文件.prop中系統屬性加載至properties變量,再通過PropertySet()將properties添加到系統中,并初始化只讀、編譯、usb相關屬性值。
PropertySet()流程在2.2.1小節中有介紹,通過Socket與屬性服務進行通信,具體過程即將揭曉。
2.2.5、啟動屬性服務
2.2.2小節中提到init進程StartPropertyService(&epoll)啟動了屬性服務。
system\core\init\property_service.cpp
2.2.6、更新或添加屬性
bionic\libc\bionic\system_property_api.cpp
int __system_property_update(prop_info* pi, const char* value, unsigned int len) {return system_properties.Update(pi, value, len);//更新屬性值 } int __system_property_add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {return system_properties.Add(name, namelen, value, valuelen);//添加屬性值 }bionic\libc\system_properties\system_properties.cpp
int SystemProperties::Update(prop_info* pi, const char* value, unsigned int len) {...prop_area* pa = contexts_->GetSerialPropArea();uint32_t serial = atomic_load_explicit(&pi->serial, memory_order_relaxed);serial |= 1;atomic_store_explicit(&pi->serial, serial, memory_order_relaxed);atomic_thread_fence(memory_order_release);strlcpy(pi->value, value, len + 1);//屬性值更新...return 0; } int SystemProperties::Add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {...prop_area* serial_pa = contexts_->GetSerialPropArea();prop_area* pa = contexts_->GetPropAreaForName(name);bool ret = pa->add(name, namelen, value, valuelen);//向共享內存添加新屬性...return 0; }bionic\libc\system_properties\prop_area.cpp
bool prop_area::add(const char* name, unsigned int namelen, const char* value,unsigned int valuelen) {return find_property(root_node(), name, namelen, value, valuelen, true); } ... const prop_info* prop_area::find_property(prop_bt* const trie, const char* name, uint32_t namelen,const char* value, uint32_t valuelen,bool alloc_if_needed) {...prop_bt* root = nullptr;uint_least32_t children_offset = atomic_load_explicit(¤t->children, memory_order_relaxed);if (children_offset != 0) {//找到屬性節點root = to_prop_bt(¤t->children);} else if (alloc_if_needed) {//未找到時新建節點uint_least32_t new_offset;root = new_prop_bt(remaining_name, substr_size, &new_offset);if (root) {atomic_store_explicit(¤t->children, new_offset, memory_order_release);}}...current = find_prop_bt(root, remaining_name, substr_size, alloc_if_needed);remaining_name = sep + 1;}uint_least32_t prop_offset = atomic_load_explicit(¤t->prop, memory_order_relaxed);if (prop_offset != 0) {return to_prop_info(¤t->prop);//返回已存在的prop_info} else if (alloc_if_needed) {uint_least32_t new_offset;//添加新屬性prop_info* new_info = new_prop_info(name, namelen, value, valuelen, &new_offset);...} } prop_info* prop_area::new_prop_info(const char* name, uint32_t namelen, const char* value,uint32_t valuelen, uint_least32_t* const off) {...prop_info* info;if (valuelen >= PROP_VALUE_MAX) {uint32_t long_value_offset = 0;char* long_location = reinterpret_cast<char*>(allocate_obj(valuelen + 1, &long_value_offset));if (!long_location) return nullptr;memcpy(long_location, value, valuelen);long_location[valuelen] = '\0';long_value_offset -= new_offset;info = new (p) prop_info(name, namelen, long_value_offset);} else {info = new (p) prop_info(name, namelen, value, valuelen);}*off = new_offset;return info; }從上述code可分析出設置屬性流程中根據所設置的屬性值是否存在分別走update()和add()流程,而add 最后調用查找屬性方法,如果不存在則新建共享內存節點,將prop_info存入。自此,set prop流程結束。
2.2.7、get prop流程
承接2.2節system\core\base\properties.cpp中__system_property_find(key.c_str())
bionic\libc\bionic\system_property_api.cpp
bionic\libc\system_properties\system_properties.cpp
const prop_info* SystemProperties::Find(const char* name) {...prop_area* pa = contexts_->GetPropAreaForName(name);...return pa->find(name); }bionic\libc\system_properties\prop_area.cpp
const prop_info* prop_area::find(const char* name) {return find_property(root_node(), name, strlen(name), nullptr, 0, false); }find_property后續流程同2.2.6小節。
三、代碼中使用屬性
在上一章節中詳細介紹了獲取和設置屬性的代碼流程,但仍有部分問題仍待解決:
- 2.2.4小節中build.prop、default.prop在哪里生成的,如何打包進系統
- 如何添加自定義hello.prop
- 如何添加系統級默認屬性
- prop有哪些類型,不同前綴有什么區別
上述疑問暫時先擱置一下,先來介紹在java、C++代碼中如何使用屬性
3.1、java代碼中使用prop
在java代碼中使用prop需滿足以下兩點:
- import android.os.Systemproperties;
- 具有system權限:
- 在AndroidManifest.xml中,配置android:sharedUserId=“android.uid.system”
- 在Android.mk中,配置LOCAL_CERTIFICATE :=platform
Systemproperties部分源碼如下:
frameworks\base\core\java\android\os\SystemProperties.java
get和set pro以ActivityManagerService.java代碼為例:
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java
獲取屬性值可以根據值的類型使用合適返回值類型的方法如getInt()、getBoolean()、getLong(),SystemProperties.get()獲取的值為String。
3.2、C++代碼中使用prop
這里以MPEG4Writer.cpp為例
frameworks\av\media\libstagefright\MPEG4Writer.cpp
在C++代碼中使用prop需要:
- include <cutils/properties.h>
- Android.mk或Android.bp或Makefile中需要鏈接libcutils庫
properties.h源碼在:
system/core/libcutils/include/cutils/properties.h
3.3、特殊屬性
從2.2.5小節中可以看到有些屬性比較特殊,特總結如下:
3.3.1、 ro只讀屬性
ro即read only這類屬性通常是系統默認屬性,在系統編譯或初始化時設置的。
$ getprop ro.vendor.build.version.release 10 $ setprop ro.vendor.build.version.release 9 setprop: failed to set property 'ro.vendor.build.version.release' to '9'3.3.2、persist持久屬性
設置persist開頭的屬性,斷電后仍能保存,值寫入data/property/persistent_properties。
$ getprop persist.hello.test //屬性為空 $ setprop persist.hello.test abc //設置屬性persist.hello.test值為abc $ getprop persist.hello.test abc //屬性get正常 abc $reboot //重啟設備 $ getprop persist.hello.test //屬性為abc abc3.3.3、ctl 控制屬性
setprop ctl.start xxx //啟動某服務 setprop ctl.stop xxx //關閉某服務 setprop ctl.restart xxx //重啟某服務3.3.4、sys.powerctl屬性
sys.powerctl屬性可控制設備重啟關機
setprop sys.powerctl shutdown //設備關機 setprop sys.powerctl reboot //設備重啟3.3.5、普通屬性
設置其他格式開頭的屬性,斷電后不能保存
$ getprop hello.test //屬性為空 $ setprop hello.test 123//設置屬性persist.hello.test值為abc $ getprop hello.test 123//屬性get正常 123 $reboot //重啟設備 $ getprop hello.test //屬性為空3.4、添加系統默認屬性
從前面的介紹中我們知道系統開機時會load *.prop屬性配置文件中的屬性,因此開機后就有了默認屬性。這里我們可以在device/xxx/xxx/system.prop 中添加
device/google/marlin/system.prop
注意:這里添加的屬性前綴必須是在system/sepolicy/private/property_contexts中被定義過的,否則無效;定制化前綴屬性在后面定制prop屬性配置中會介紹。
make android后在out/target/product/xxx/system/build.prop 或out/target/product/xxx/vendor/build.prop可找到添加的屬性persist.hello.world,則說明基本添加成功,燒錄img驗證即可。
四、prop打包
我們已經知道如何添加系統默認屬性,但項目中有許多*.prop配置文件,
- 這些文件是如何最終打包至out/tartget/product/…/build.prop的呢?
- 為了便于客制化屬性管控,如何添加自己的prop配置文件呢?
本章將圍繞上面兩個問題進行介紹
4.1、prop打包流程
build.prop是由代碼編譯時,build/core/Makefile完成的
//指定編譯信息及設備基本信息腳本 BUILDINFO_SH := build/make/tools/buildinfo.sh BUILDINFO_COMMON_SH := build/make/tools/buildinfo_common.sh//指定build.prop生成路徑 INSTALLED_BUILD_PROP_TARGET := $(TARGET_OUT)/build.prop INSTALLED_PRODUCT_BUILD_PROP_TARGET := $(TARGET_OUT_PRODUCT)/build.prop INSTALLED_VENDOR_BUILD_PROP_TARGET := $(TARGET_OUT_VENDOR)/build.prop ... //生成build.prop $(intermediate_system_build_prop): $(BUILDINFO_SH) $(BUILDINFO_COMMON_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(API_FINGERPRINT)@echo Target buildinfo: $@@mkdir -p $(dir $@)$(hide) echo > $@ ifneq ($(PRODUCT_OEM_PROPERTIES),)$(hide) echo "#" >> $@; \echo "# PRODUCT_OEM_PROPERTIES" >> $@; \echo "#" >> $@;$(hide) $(foreach prop,$(PRODUCT_OEM_PROPERTIES), \echo "import /oem/oem.prop $(prop)" >> $@;) endif$(hide) PRODUCT_BRAND="$(PRODUCT_SYSTEM_BRAND)" \...TARGET_CPU_ABI2="$(TARGET_CPU_ABI2)" \bash $(BUILDINFO_SH) >> $@//將許多屬性追加至out/.../build.propbuild/make/tools/buildinfo.sh中配置了系統編譯常見信息,具體如下
... echo "ro.build.version.incremental=$BUILD_NUMBER"//軟件增量版本 echo "ro.build.version.sdk=$PLATFORM_SDK_VERSION"//軟件使用的sdk版本 echo "ro.build.version.release=$PLATFORM_VERSION"//系統版本號 echo "ro.build.date=`$DATE`"//軟件編譯日期 ...經過Makefile,將系統中各種prop配置文件合并生成在out指定路徑下。
也是在Makefile中將各路徑下build.prop隨系統分區一同打包進img,out\target\product\xxx\system\build.prop打包進system.img
out\target\product\xxx\vendor\build.prop打包進vendor.img
五、添加定制hello.prop
涉及的代碼路徑匯總如下:
device/qcom/qssi/hello.prop device/qcom/qssi/qssi.mk device/qcom/sepolicy/generic/private/property_contexts system/core/rootdir/init.rc system/core/init/property_service.cpp為了方便統一管理定制化屬性,有時會將定制化屬性都寫在定制的.prop文件中,下面以添加hello.prop為例說明添加過程。
5.1、device下添加hello.prop
device/qcom/qssi/hello.prop
# # system.prop for qssi # ro.hello.year=2022 //添加ro屬性 persist.hello.month=07 //添加persist屬性 hello.day=25 //添加hello屬性ro.product.model=HelloWorld //定制系統已有ro.product.model屬性5.2 配置預置路徑
修改device下的device.mk來指定hello.prop的預置路徑
device/qcom/qssi/qssi.mk
5.3、SELinux權限配置
hello.開頭的屬性是新添加的配置,需要在配置對應的SELinux規則,否則無效,配置方法如下:
device/qcom/sepolicy/generic/private/property_contexts
5.4、配置hello.prop權限
此步驟可省略,若未配置讀寫權限,默認system/prop為644
這里配置與system/build.prop相同的600權限
system/core/rootdir/init.rc
5.5、load hello.prop
5.2、小節中僅僅將hello.prop預置到system/hello.prop還不夠,系統啟動時需要load hello.prop才能使其生效
system/core/init/property_service.cpp
5.6、驗證hello.prop
Android全編譯后正常情況可找到生成的
out/target/product/qssi/system/hello.prop
檢查其內容應與device/qcom/qssi/hello.prop內容保持一致。
將打包好的img燒錄到設備中進行確認
總結
以上是生活随笔為你收集整理的Android 系统属性(SystemProperties)介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据丢失不用怕,迅捷转换器来帮您
- 下一篇: 开启沉浸式体验 艺画开天《灵笼》积极探索