From 0ad9ab07fa0a106e55a423c837d306327045befe Mon Sep 17 00:00:00 2001 From: Lorenzo Colitti Date: Fri, 25 Mar 2016 17:40:11 +0900 Subject: [PATCH] Avoid null app context in StaticApplicationContextServiceFetcher. StaticApplicationContextServiceFetcher passes the application context to the services it creates, but sometimes the application context can be null. Cases we've seen so far are: - Apps that (incorrectly) call getSystemService in attachBaseContext. In this case the passed-in context is what will become the application context soon afterwards. - ActivityThread$ApplicationThread.setHttpProxy. In this case the passed-in context is the system context. In both of these cases the passed-in context is never freed, so passing it in to the service will not result in a leak. Bug: 27532714 Bug: 27502146 Bug: 27337770 Change-Id: I5971c67b0e699d1a77850be8a338a448a96ec7d7 --- core/java/android/app/SystemServiceRegistry.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/java/android/app/SystemServiceRegistry.java b/core/java/android/app/SystemServiceRegistry.java index 2987fbc4f33de..bdc4404057e5d 100644 --- a/core/java/android/app/SystemServiceRegistry.java +++ b/core/java/android/app/SystemServiceRegistry.java @@ -882,7 +882,12 @@ final class SystemServiceRegistry { public final T getService(ContextImpl ctx) { synchronized (StaticApplicationContextServiceFetcher.this) { if (mCachedInstance == null) { - mCachedInstance = createService(ctx.getApplicationContext()); + Context appContext = ctx.getApplicationContext(); + // If the application context is null, we're either in the system process or + // it's the application context very early in app initialization. In both these + // cases, the passed-in ContextImpl will not be freed, so it's safe to pass it + // to the service. http://b/27532714 . + mCachedInstance = createService(appContext != null ? appContext : ctx); } return mCachedInstance; }