方法:
修改./default.prop
把ro.secure設為0,persist.service.adb.enable設為1,adbd進程就會以root使用者的身份啟動。
原理:
可以看一下Android系統根目錄下的/init.rc的片段:
... ...
# adbd is controlled by the persist.service.adb.enable system property
service adbd /sbin/adbd
disabled
# adbd on at boot in emulator
on property:ro.kernel.qemu=1
start adbd
on property:persist.service.adb.enable=1
start adbd
on property:persist.service.adb.enable=0
stop adbd
... ...
這裡定義了一個觸發器,只要persist.service.adb.enable值被置為1,就會啟動/sbin/adbd。
在build目錄下搜尋一下,發現了main.mk中有這樣的程式碼片段
## user/userdebug ##
user_variant := $(filter userdebug user,$(TARGET_BUILD_VARIANT))
enable_target_debugging := true
ifneq (,$(user_variant))
# Target is secure in user builds.
ADDITIONAL_DEFAULT_PROPERTIES += ro.secure=1
tags_to_install := user
ifeq ($(user_variant),userdebug)
# Pick up some extra useful tools
tags_to_install += debug
else
# Disable debugging in plain user builds.
enable_target_debugging :=
endif
# TODO: Always set WITH_DEXPREOPT (for user builds) once it works on OSX.
# Also, remove the corresponding block in config/product_config.make.
ifeq ($(HOST_OS)-$(WITH_DEXPREOPT_buildbot),linux-true)
WITH_DEXPREOPT := true
endif
# Disallow mock locations by default for user builds
ADDITIONAL_DEFAULT_PROPERTIES += ro.allow.mock.location=0
else # !user_variant
# Turn on checkjni for non-user builds.
ADDITIONAL_BUILD_PROPERTIES += ro.kernel.android.checkjni=1
# Set device insecure for non-user builds.
ADDITIONAL_DEFAULT_PROPERTIES += ro.secure=0
# Allow mock locations by default for non user builds
ADDITIONAL_DEFAULT_PROPERTIES += ro.allow.mock.location=1
endif # !user_variant
ifeq (true,$(strip $(enable_target_debugging)))
# Target is more debuggable and adbd is on by default
ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=1 persist.service.adb.enable=1
# Include the debugging/testing OTA keys in this build.
INCLUDE_TEST_OTA_KEYS := true
else # !enable_target_debugging
# Target is less debuggable and adbd is off by default
ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=0 persist.service.adb.enable=0
endif # !enable_target_debugging
這段代碼我大致解釋一下:
主要通過判斷當前的編譯模式來給幾個屬性賦予不同的值,然後把屬性儲存區在ADDITIONAL_DEFAULT_PROPERTIES這個變數中,這個變數在後面是要寫到根目錄下的/default.prop中去,在系統啟動時被屬性服務載入的。也就是說我們在/default.prop中看到的幾個屬性的值是在這裡設定的。
只看兩個屬性ro.secure,persist.service.adb.enable。當前是user模式的話,編譯系統會把ro.secure置為1,把persist.service.adb.enable置為0.也就是說,用user模式編譯出來的系統運行在安全模式下,adbd預設關閉。即使通過設定屬性的方式開啟,adbd進程的使用者也是shell,不具有root許可權。這樣,普通使用者或者開發人員拿到一個機器後,通過PC運行adb shell時,是以shell使用者登入機器的。
好了,現在把ro.secure置為0,再重新編譯,只要設定屬性persist.service.adb.enable的值為1,adbd進程就會以root使用者的身份啟動。