Wake-up lock: detects No-Sleep in the Android * Application (unable to Sleep)

Source: Internet
Author: User

Author: philippe-micel

Summary

If the Android * application uses an improper wake-up lock, the battery power consumption will be significantly increased. In this article, we will introduce some tips and tips to help you identify the No Sleep vulnerability related to misuse of wake-up locks.

1. Introduction
2. Wake up lock
2.1. Introduction to wakeup locks
2.2. Android user wake-up lock
2.3. Android kernel wake-up lock
2.4. No-Sleep Vulnerability
3. Identify the No Sleep Vulnerability
3.1. Use adb
3.2. Use BetterBatteryStats Application
4. Test Cases
5. Conclusion
6. References

1. Introduction

Limiting battery power consumption is essential for smartphones. For maximum autonomy, the Android operating system design can enable sleep mode when detecting no user activity on the system. Some applications require the device to be enabled, even if there is no user operation for a long time. For example, watching videos, listening to music, using GPS, and playing games. Android provides such a mechanism for the operating system or application to ensure that the device remains awake. This mechanism is called a wake-up lock. For more information, see Christopher Bird's article "Wake-Up locks for Android ".

The emergence of this mechanism puts the responsibility for managing component activities on the application developers. If an error occurs, the application may consume a lot of battery power-even if the application is not running on the frontend.

2. Wake-up lock 2. 1. Introduction to the wake-up lock

A wake-up lock is a software mechanism that controls the power status of a host device. The operating system can export clear Power Management handles and APIs to specify when a component needs to be enabled or awakened until it is explicitly released from the task.

The wake-up lock mechanism can be implemented at two levels: user and kernel. Demonstrate the internal design of the Android wake-up lock implementation. The user wake-up lock can be used by high-level operating system services or applications and provided through the power management service. It allows applications to control the power status of devices. The kernel wake-up lock is controlled by the operating system kernel or driver. The user wake-up lock is mapped to the kernel wake-up lock. Any active kernel-level wake-up lock can prevent the system from being suspended in the ACPI S3 State (in RAM suspended)-it is the most energy-saving status for mobile devices.

2.2. Android user wake-up lock

The Android architecture uses PowerManager to export the wake-up lock mechanism. The wake-up lock can be divided into four types:

Tag Value CPU Screen Keyboard

PARTIAL_WAKE_LOCK

Enable

Close

Close

SCREEN_DIM_WAKE_LOCK

Enable

Darken

Close

SCREEN_BRIGHT_WAKE_LOCK

Enable

Brightening

Close

FULL_WAKE_LOCK

Enable

Brightening

Brightening

Please note that FULL_WAKE_LOCK will be deprecated since API grade 17. The application should use FLAG_KEEP_SCREEN_ON.

You can use the wake-up lock to force some components (CPU, screen, and keyboard) to remain awake.

Please refer to the special reminder about PARTIAL_WAKE_LOCK: the CPU continues to run no matter whether the display times out or the screen is in any status-even if you press the power button. This may cause silent power consumption, that is, the phone looks in standby mode (the screen is off), but is actually completely awake.

In other wake-up locks, you can still use the power button to make the device sleep. After you press the power button, all the wake-up locks except the local wake-up locks will be completely released.

The above is the method by which the application controls the wake-up lock. Basically, it is a GET/release mechanism. When the application needs to enable some components, it will obtain the wake-up lock. When you no longer need these components to be enabled, you need to release the wake-up lock.

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wl.acquire();
..screen will stay on during this section..
wl.release();

2.3. Android kernel wake-up lock

The kernel wake-up lock is a low-level wake-up lock controlled by the kernel. They can be obtained/released from the kernel. In this regard, application developers have less direct control over them, but the running status of the application can indirectly trigger these wake-up locks and inadvertently increase the battery power consumption.

The following is an example of the kernel wake-up lock.

Wlan_rx:It is controlled by the kernel when data is sent or received through Wi-Fi.

PowerManagerService:Is applicable to all containers with local wake-up locks.

Sync: Enabled when the synchronization process is running.

Alarm_rtc: Control alert (used when the application or process performs regular checks ).

Main: Keep the kernel in the wake-up state. When the system enters the pending mode, this is the last released wake-up lock.

2.4. No-Sleep Vulnerability

The application must release each wake-up lock required by the application at a certain time point to allow the system to return to the deep sleep mode. If the wake-up lock has not been released, the acquisition/release mechanism may cause a vulnerability. Even if the application that enables the wake-up lock stops running on the foreground, the wake-up lock is still in use. The wake-up lock can be released only when the call is used to explicitly release the wake-up lock or when the application is terminated (forced to close. Enabling some wake-up locks will prevent the system from entering deep sleep mode-even if no activity significantly increases power consumption and silent reduces battery autonomy. This is the No-Sleep vulnerability. Due to the event-driven feature of Android, developers may not be able to think of all the code paths of the wake-up lock that their applications obtain and need to disable. This vulnerability type is called the No-Sleep vulnerability code path.

Another scenario where this type of vulnerability occurs is that the wake-up lock is released because it is not effectively obtained. This may happen in the multi-threaded code that gets and releases the wake-up lock in different threads. This is the Race Condition for the No-Sleep vulnerability.

The last problem is the No-sleep expansion, in which the time needed to obtain the wake-up lock is longer than the actual time needed.

Why are these problems highlighted? According to P. Vekris, "328 of the 55% applications that use the wake-up lock do not follow our policy for no-sleep vulnerabilities" [2012]. Some major applications are released when the No-Sleep vulnerability occurs. Therefore, developers need to be aware of this to run their applications in the optimal way.

3. Identify the No-Sleep Vulnerability

You can solve the no sleep vulnerability in two ways: static code path scan analysis and dynamic runtime analysis. In this article, we mainly introduce runtime analysis.

In this way, you cannot find all the wake-up lock vulnerabilities in the application. However, it helps you find the wake-up lock problem that occurs during the running period. To locate the wake-up lock issue, you must follow the code path of the unlocked lock. Test whether an application has solved the no sleep vulnerability, including operating the application in different locations of the application, and try to exit the application in different ways to confirm whether the wake-up lock still exists.

In some cases, it is necessary to prevent the system from going to sleep even if the application stops running on the foreground. The application may need to execute a task in the background. This is the case. For example, if an application needs to download a video or game dataset for a long time. During the download process, the user may make the application run in the background, but the mobile phone should remain awake before the download is complete. In this case, the application should always enable the wake-up lock before the download is complete. Of course, you need to ensure that the wake-up lock is released at a certain point. For example, if the network is disconnected during the download process, you do not need to wake up the phone.

In short, it is found that the No Sleep vulnerability is closely related to the environment. There are no predefined standards to help you easily identify the problem. The above vulnerabilities can only be found by common sense.

3.1. Use adb

Shell Command is the easiest tool to view the wake-up lock.

To fully understand the kernel wake-up lock, enter:

Adb shell cat/proc/wakelocks

name count expire_count wake_count active_since total_time
"PowerManagerService" 1502 0 0 0 337817677431
"main" 15 0 0 0 984265842688
"alarm" 1512 0 792 0 217778251643
"radio-interface" 16 0 0 0 16676538930
"alarm_rtc" 804 4 0 0 1204136324759
"gps-lock" 1 0 0 0 10753659786
name sleep_time max_time last_change
"PowerManagerService" 95729409122 140921663667 9723417252748
"main" 0 212424732355 9498127170228
"alarm" 217617362047 357976941 9723371461242
"radio-interface" 0 1659328496 9486387144974
"alarm_rtc" 1200253446201 66082936501 9483176054624
"gps-lock" 0 10753659786 37632803440

For Images Using kernel 3.4 or later, use "adb shell cat/sys/kernel/debug/wakeup_sources ". Although this format provides all information, it is not suitable for users. The tools described below are more convenient.

You can use "adb shell dumpsys power" to easily view specific applications. The following is a typical output method of the command. As you can see, after the command is released, the user wake-up lock is displayed in red. This command can view the user wake-up lock displayed in the system.

Power Manager State:
mIsPowered=true mPowerState=3 mScreenOffTime=1618305 ms
mPartialCount=3
mWakeLockState=SCREEN_ON_BIT
mUserState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
mPowerState=SCREEN_BRIGHT_BIT SCREEN_ON_BIT
mLocks.gather=SCREEN_ON_BIT
mNextTimeout=2382037 now=2378097 3s from now
mDimScreen=true mStayOnConditions=3 mPreparingForScreenOn=false mSkippedScreenOn=false
mScreenOffReason=0 mUserState=3
mBroadcastQueue={-1,-1,-1}
mBroadcastWhy={0,0,0}
mPokey=0 mPokeAwakeonSet=false
mKeyboardVisible=false mUserActivityAllowed=true
mKeylightDelay=6000 mDimDelay=587000 mScreenOffDelay=7000
mPreventScreenOn=false mScreenBrightnessOverride=-1 mButtonBrightnessOverride=-1
mScreenOffTimeoutSetting=600000 mMaximumScreenOffTimeout=2147483647
mLastScreenOnTime=27380
mBroadcastWakeLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
mStayOnWhilePluggedInScreenDimLock=UnsynchronizedWakeLock(mFlags=0x6 mCount=0 mHeld=true)
mStayOnWhilePluggedInPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=true)
mPreventScreenOnPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
mProximityPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false)
mProximityWakeLockCount=0
mProximitySensorEnabled=false
mProximitySensorActive=false
mProximityPendingValue=-1
mLastProximityEventTime=0
mLightSensorEnabled=true mLightSensorAdjustSetting=0.0
mLightSensorValue=11.0 mLightSensorPendingValue=10.0
mHighestLightSensorValue=47 mWaitingForFirstLightSensor=false
mLightSensorPendingDecrease=false mLightSensorPendingIncrease=false
mLightSensorScreenBrightness=42 mLightSensorButtonBrightness=0 mLightSensorKeyboardBrightness=0
mUseSoftwareAutoBrightness=true
mAutoBrightessEnabled=true
creenBrightnessAnimator:
animating: start:42, end:42, duration:480, current:42
startSensorValue:47 endSensorValue:11
startTimeMillis:2361638 now:2378092
currentMask:SCREEN_BRIGHT_BIT
mLocks.size=4:
SCREEN_DIM_WAKE_LOCK          'StayOnWhilePluggedIn_Screen_Dim' activated (minState=1, uid=1000, pid=388)
PARTIAL_WAKE_LOCK             'StayOnWhilePluggedIn_Partial' activated (minState=0, uid=1000, pid=388)
PARTIAL_WAKE_LOCK             'HDA_PARTIAL_WAKE_LOCK' activated (minState=0, uid=10046, pid=4690)
PARTIAL_WAKE_LOCK             'AudioOut_2' activated (minState=0, uid=1013, pid=157)
mPokeLocks.size=0:

To check whether the WAF lock is enabled after the application enters the background, follow these steps:

1. Connect the device to USB.
2. Enable and operate on the application.
3. Press the power button to enter sleep mode or exit the application in some way.
4. Wait 20 seconds.
5. Enter the following commands in command line mode:
> adb shell dumpsys power
6. Check whether PARTIAL_WAKE_LOCKs are the same. For example:
PARTIAL_WAKE_LOCK       ‘AudioOut_2’ activated(minState=0, uid=1013, pid=157)
7. Repeat Step 1 every 15 seconds for 3 to 5 times. If the results are the same, problems may occur.
3.2. Use BetterBatteryStats Application

BetterBatteryStats * (https://play.google.com/store/apps/details? Id = com. asksven. betterbatterystats & hl = en) is an Android app developed by Sven Knispel and can be purchased on Google Play. It can collect information to help you discover power consumption problems, especially lock wake-up problems.

First, you can view the deep sleep and wake-up modes and total time by selecting the "Other" entry. Ideally, in most cases, the phone should be in sleep state if it is not used.

In addition, you can compare the wake-up time with the screen start time to know when the event is actually active. Under normal circumstances, the screen start time and wake-up time should be off.

You can view the battery charging evaluation and wake-up, screen enabling, and Wi-Fi * status at various times.

Then, you can view the kernel wake-up lock. You can view the time and quantity of each kernel wake-up lock. A long time or a large number may indicate a problem. In this report, you cannot find out which application or process causes the hotspot to appear, but you can find the running status triggered by a specific application.

In the kernel wake-up lock report, "PowerManagerService" summarizes the time spent in the user wake-up lock. If the command line shows a hotspot, you can find it by viewing the local wake-up lock report.

In most cases, a local wake-up lock can indicate the application that controls it. It is helpful to find the culprit that causes the problem. However, sometimes some activities may be started through other applications. For example, a game may play a sound through the AudioOut audio channel allocated to the Android media library. If the encoding is not correct, you may think that the audio channel is not disabled because of a game error, rather than Android Gallery.

AlarmManager may prompt an alert to cause a wake-up event or make a large number of alarm changes to an application. You may want to view the "alarm" section, but you can view it only on an image with root permissions.

In addition, network access only supports images with root permissions. It may be helpful if you notice high traffic on the network. The multipdp/svnet-dormancy kernel wake-up lock may indicate that you still have high network usage.

4. Test Cases

Let's look at a real case of using the game. Start the game, play for about five minutes, and then exit the game in unconventional ways. In our case, we force exit by pressing the homepage key. The music is stopped and the home page appears. In the user's opinion, everything is normal. After the activity is stopped for a few minutes, the screen turns black. Keep your phone in this status for about half an hour, and then use BestBatteryStats to check it. On the "Other" page, you can see that although the screen is not turned on, the phone is still in the wake-up status. In addition, you can see that the battery power consumption rate is 8.5%/hour. Therefore, in this situation, the duration of using a fully-powered mobile phone is no more than 12 hours.

Now let's take a look at the kernel wake-up lock. We can see that although there is no activity, the two kernel wake-up locks remain in the wake-up status. One is PowerManagerService, which means that some users enable the local wake-up lock and the other is AudioOutLock. Let's take a look at the local wake-up lock interface.

On the local wake-up lock page, we can see that the audio channel in the media repository application is still open. This is strange because the user does not explicitly use the media repository application. In fact, the game starts the media library to play the game's music. The developer forgets to disable the audio channel when the home button breaks the application. Developers should take this situation into consideration and modify the application accordingly.

5. Conclusion

The wake-up lock is a very useful and powerful tool. However, improper use may affect the battery life of the device, greatly affecting the user experience. For developers, ensure that the code in the QA process does not result in any No Sleep vulnerability. They should consider using available tools to analyze the impact of their applications on battery and minimize the impact on user devices.

6. References
  • A. Pathak, et al., "What makes my mobile phone always awake? : Describe and detect no-sleep power vulnerabilities in the smartphone app, "MobiSys, November 1, 2012.
  • P. Vekris, et al., "No-Sleep power vulnerability found in Android apps", HotPower, November 2012.
  • Android wake-up lock http://developer.android.com/reference/android/ OS /PowerManager.WakeLock.html
  • Christopher Bird, "wake-up lock for android" http://software.intel.com/en-us/articles/wakelocks-for-android,Intel Corporation, 2012.
  • BetterBatteryStats site: http://better.asksven.org/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.