通過Android源碼學習之淺析SystemServer脈絡知道了SystemServer是怎么通過利用JNI,但相繼的問題出現了:SystemServer是干嘛用的?本人從《深入理解Android 卷2》截取摘錄這一問題的回答:
SystemServer是什么?它是Android Java的兩大支柱之一。另外一個支柱是專門負責孵化Java進程的Zygote。這兩大支柱倒了一個,都會導致Android Java的崩潰(所有由Zygote孵化的Java進程都會被銷毀,而SystemServer就是由Zygote孵化而來)。若Android Java真的崩潰了,則Linux系統中的進程init會重新啟動“兩大支柱”以重建Android Java。
SystemServer和系統服務有着重要關系。Android系統中幾乎所有的核心服務都在這個進程中,如ActivityManagerService、PowerManagerService和WindowManagerService等。那么,作為這些服務的大本營,SystemServer會是什么樣的呢?
其中“SystemServer會是什么樣的呢?“知道了一些,但不知道SystemServer怎么就是服務的大本營了?在回去看看SystemServer.java。打開Source Insight項目,發現代碼如下:
public static final void init2() { Slog.i(TAG, "Entered the Android system server!"); Thread thr = new ServerThread(); thr.setName("android.server.ServerThread"); thr.start(); }
又看見ini2函數了,這個函數主要的功能是創建新的線程ServerThread,所以當它執行start時,我們應該找到這個類的override的run()函數,在同樣的SystemServer.java中找到了ServerThread類的run函數,這個函數長的有點令人發指,但再仔細看發現其中有很多”重復的相似的代碼“,各種***Service、null、ServiceManager.addService("***",new ***)和try{}catch(){}、以及Slog.i()等等,不愧是大本營,幾乎所有的服務都在這里匯集ServiceManager.addService("***",new ***),有人這些服務進行歸類,一共六大類。我自己從這長長的run函數中截取皮毛代碼,如下所示:
LightsService lights = null; PowerManagerService power = null; BatteryService battery = null; AlarmManagerService alarm = null; NetworkManagementService networkManagement = null; NetworkStatsService networkStats = null; NetworkPolicyManagerService networkPolicy = null; ConnectivityService connectivity = null; WifiP2pService wifiP2p = null; WifiService wifi = null; IPackageManager pm = null; Context context = null; WindowManagerService wm = null; BluetoothService bluetooth = null; BluetoothA2dpService bluetoothA2dp = null; DockObserver dock = null; UsbService usb = null; UiModeManagerService uiMode = null; RecognitionManagerService recognition = null; ThrottleService throttle = null; NetworkTimeUpdateService networkTimeUpdater = null; // Critical services... try { Slog.i(TAG, "Entropy Service"); ServiceManager.addService("entropy", new EntropyService()); Slog.i(TAG, "Power Manager"); power = new PowerManagerService(); ServiceManager.addService(Context.POWER_SERVICE, power); Slog.i(TAG, "Activity Manager"); context = ActivityManagerService.main(factoryTest); Slog.i(TAG, "Telephony Registry"); ServiceManager.addService("telephony.registry", new TelephonyRegistry(context)); AttributeCache.init(context); Slog.i(TAG, "Package Manager"); // Only run "core" apps if we're encrypting the device. String cryptState = SystemProperties.get("vold.decrypt"); boolean onlyCore = false; if (ENCRYPTING_STATE.equals(cryptState)) { Slog.w(TAG, "Detected encryption in progress - only parsing core apps"); onlyCore = true; } else if (ENCRYPTED_STATE.equals(cryptState)) { Slog.w(TAG, "Device encrypted - only parsing core apps");
所以這里的最重要的一行代碼就是ServiceManager.addService("***",new ***),但自己初次分析源代碼,還不知道這函數具體是怎么將各種服務添加到系統中的,所以這個ServiceManager類的分析,待到自己有能力了在做總結。高深的自己不懂,只能拿軟柿子來捏一捏了,這么多**service,我選擇了最簡單的一個EntropyService分析(要是你讀過了《深入理解Android》別拍磚啊,但求指導~~~)。
找到該文件的137(貌似)代碼---->ServiceManager.addService("entropy", new EntropyService());
所以接着找到這個類EntropyService,類代碼如下:
public EntropyService() { this(getSystemDir() + "/entropy.dat", "/dev/urandom"); } /** Test only interface, not for public use */ public EntropyService(String entropyFile, String randomDevice) { if (randomDevice == null) { throw new NullPointerException("randomDevice"); } if (entropyFile == null) { throw new NullPointerException("entropyFile"); } this.randomDevice = randomDevice; this.entropyFile = entropyFile; loadInitialEntropy(); addDeviceSpecificEntropy(); writeEntropy(); scheduleEntropyWriter(); }
首先是調用自己的函數getSystemDir(),創建文件夾,然后返回路徑名稱,接着就是想在創建entropy.dat文件保存信息,最后調用另一個帶兩個參數的構造函數(有點廢話),緊接着保存兩個string參數、調用四個函數。字面的意思是初始化、添加、寫入、按時間寫。看第一個函數:
private void loadInitialEntropy() { try { RandomBlock.fromFile(entropyFile).toFile(randomDevice, false); } catch (IOException e) { Slog.w(TAG, "unable to load initial entropy (first boot?)", e); } }
看似簡單,它是調用了RandomBlock類的靜態函數fromFile,然后再寫入,意思就是從"entropy.dat"寫入"/dev/urandom"中,具體是什么現在也不懂,看看RandomBlock類。
class RandomBlock { private static final String TAG = "RandomBlock"; private static final boolean DEBUG = false; private static final int BLOCK_SIZE = 4096; private byte[] block = new byte[BLOCK_SIZE]; private RandomBlock() { } static RandomBlock fromFile(String filename) throws IOException { if (DEBUG) Slog.v(TAG, "reading from file " + filename); InputStream stream = null; try { stream = new FileInputStream(filename); return fromStream(stream); } finally { close(stream); } } private static RandomBlock fromStream(InputStream in) throws IOException { RandomBlock retval = new RandomBlock(); int total = 0; while(total < BLOCK_SIZE) { int result = in.read(retval.block, total, BLOCK_SIZE - total); if (result == -1) { throw new EOFException(); } total += result; } return retval; } void toFile(String filename, boolean sync) throws IOException { if (DEBUG) Slog.v(TAG, "writing to file " + filename); RandomAccessFile out = null; try { out = new RandomAccessFile(filename, sync ? "rws" : "rw"); toDataOut(out); truncateIfPossible(out); } finally { close(out); } } private static void truncateIfPossible(RandomAccessFile f) { try { f.setLength(BLOCK_SIZE); } catch (IOException e) { // ignore this exception. Sometimes, the file we're trying to // write is a character device, such as /dev/urandom, and // these character devices do not support setting the length. } } private void toDataOut(DataOutput out) throws IOException { out.write(block); } private static void close(Closeable c) { try { if (c == null) { return; } c.close(); } catch (IOException e) { Slog.w(TAG, "IOException thrown while closing Closeable", e); } } }
這類夠絕的,不是static就是private,連構造函數都private了,明白了,先是從文件entropy.dat讀出數據流,保存到block字符數組中,然后寫入到urandom中,這里有兩個文件操作的類FileInputStream和RandomAccessFile,讓我想到了《Head First Design Pattern》中有個(裝飾模式?)介紹過怎么解讀Java的文件操作類之間的關系,回頭好好復習一下。
第一關鍵函數讀完了,接着第二個addDeviceSpecificEntropy函數,看代碼:
/** * Add additional information to the kernel entropy pool. The * information isn't necessarily "random", but that's ok. Even * sending non-random information to {@code /dev/urandom} is useful * because, while it doesn't increase the "quality" of the entropy pool, * it mixes more bits into the pool, which gives us a higher degree * of uncertainty in the generated randomness. Like nature, writes to * the random device can only cause the quality of the entropy in the * kernel to stay the same or increase. * * <p>For maximum effect, we try to target information which varies * on a per-device basis, and is not easily observable to an * attacker. */ private void addDeviceSpecificEntropy() { PrintWriter out = null; try { out = new PrintWriter(new FileOutputStream(randomDevice)); out.println("Copyright (C) 2009 The Android Open Source Project"); out.println("All Your Randomness Are Belong To Us"); out.println(START_TIME); out.println(START_NANOTIME); out.println(SystemProperties.get("ro.serialno")); out.println(SystemProperties.get("ro.bootmode")); out.println(SystemProperties.get("ro.baseband")); out.println(SystemProperties.get("ro.carrier")); out.println(SystemProperties.get("ro.bootloader")); out.println(SystemProperties.get("ro.hardware")); out.println(SystemProperties.get("ro.revision")); out.println(new Object().hashCode()); out.println(System.currentTimeMillis()); out.println(System.nanoTime()); } catch (IOException e) { Slog.w(TAG, "Unable to add device specific data to the entropy pool", e); } finally { if (out != null) { out.close(); } } }
看着字面的理解就是首先將一些文本信息,如”Copyright (C) 2009 The Android Open Source Project“寫入到這個urandom設備(姑且認為是urandom文件)中,接着將SystemProperties獲取的東東寫入,最后寫入系統時間等,現在看看SystemProperties到底是什么東西了。看代碼:

public class SystemProperties { public static final int PROP_NAME_MAX = 31; public static final int PROP_VALUE_MAX = 91; private 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); private 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); /** * Get the value for the given key. * @return an empty string if the key isn't found * @throws IllegalArgumentException if the key exceeds 32 characters */ public static String get(String key) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } return native_get(key); } /** * Get the value for the given key. * @return if the key isn't found, return def if it isn't null, or an empty string otherwise * @throws IllegalArgumentException if the key exceeds 32 characters */ public static String get(String key, String def) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } return native_get(key, def); } /** * Get the value for the given key, and return as an integer. * @param key the key to lookup * @param def a default value to return * @return the key parsed as an integer, or def if the key isn't found or * cannot be parsed * @throws IllegalArgumentException if the key exceeds 32 characters */ public static int getInt(String key, int def) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } return native_get_int(key, def); } /** * Get the value for the given key, and return as a long. * @param key the key to lookup * @param def a default value to return * @return the key parsed as a long, or def if the key isn't found or * cannot be parsed * @throws IllegalArgumentException if the key exceeds 32 characters */ public static long getLong(String key, long def) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } return native_get_long(key, def); } /** * Get the value for the given key, returned as a boolean. * Values 'n', 'no', '0', 'false' or 'off' are considered false. * Values 'y', 'yes', '1', 'true' or 'on' are considered true. * (case sensitive). * If the key does not exist, or has any other value, then the default * result is returned. * @param key the key to lookup * @param def a default value to return * @return the key parsed as a boolean, or def if the key isn't found or is * not able to be parsed as a boolean. * @throws IllegalArgumentException if the key exceeds 32 characters */ public static boolean getBoolean(String key, boolean def) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } return native_get_boolean(key, def); } /** * Set the value for the given key. * @throws IllegalArgumentException if the key exceeds 32 characters * @throws IllegalArgumentException if the value exceeds 92 characters */ public static void set(String key, String val) { if (key.length() > PROP_NAME_MAX) { throw new IllegalArgumentException("key.length > " + PROP_NAME_MAX); } if (val != null && val.length() > PROP_VALUE_MAX) { throw new IllegalArgumentException("val.length > " + PROP_VALUE_MAX); } native_set(key, val); } }
好嘛~~~這個又是和Native有關了,留給自己接着分析了(也給大家自己分析)~~~
第三個函數了,writeEntropy()看代碼:
private void writeEntropy() { try { RandomBlock.fromFile(randomDevice).toFile(entropyFile, true); } catch (IOException e) { Slog.w(TAG, "unable to write entropy", e); } }
這不就是和之前的相似嗎?直接將urando設備的內容讀出寫入到entropy.dat中。
第四個函數了,scheduleEntropyWriter,看代碼:
private void scheduleEntropyWriter() { mHandler.removeMessages(ENTROPY_WHAT); mHandler.sendEmptyMessageDelayed(ENTROPY_WHAT, ENTROPY_WRITE_PERIOD); }
接着看看mHandler它是如何定義操作的:
/** * Handler that periodically updates the entropy on disk. */ private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what != ENTROPY_WHAT) { Slog.e(TAG, "Will not process invalid message"); return; } writeEntropy(); scheduleEntropyWriter(); } };
具體意思就是向這個類每三個小時發送一個消息,當消息到達之后,該類會再次調用writeEntropy()。。。
現在知道這個服務是怎么進展的,但具體啟動這個服務干嘛用的,有知道的教教我~~~