blob: 136c84eaf5435156b670b37fe214e493f9db3710 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
Makoto Onukid67070e2018-03-30 12:39:14 -070019import android.annotation.IntDef;
Adam Lesinski4ece3d62016-06-16 18:05:41 -070020import android.annotation.NonNull;
21import android.annotation.Nullable;
Artur Satayevc895b1b2019-12-10 17:47:51 +000022import android.compat.annotation.UnsupportedAppUsage;
Felipe Lemea4f39cd2019-02-19 15:08:59 -080023import android.content.AutofillOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.BroadcastReceiver;
25import android.content.ComponentName;
Felipe Leme326f15a2019-02-19 09:42:24 -080026import android.content.ContentCaptureOptions;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010027import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.ContentResolver;
29import android.content.Context;
30import android.content.ContextWrapper;
31import android.content.IContentProvider;
Jeff Brown6e539312015-02-24 18:53:21 -080032import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.Intent;
34import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070035import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ReceiverCallNotAllowedException;
37import android.content.ServiceConnection;
38import android.content.SharedPreferences;
Adam Lesinski4e862812016-11-21 16:02:24 -080039import android.content.pm.ActivityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.IPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Jeff Sharkey6d515712012-09-20 16:06:08 -070043import android.content.pm.PackageManager.NameNotFoundException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.res.AssetManager;
Jason Monkbd983642017-02-24 16:57:40 -050045import android.content.res.CompatResources;
Dianne Hackborn5be8de32011-05-24 18:11:57 -070046import android.content.res.CompatibilityInfo;
Dianne Hackborn756220b2012-08-14 16:45:30 -070047import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.res.Resources;
Ryan Mitchell4579c0a2020-01-08 16:29:11 -080049import android.content.res.loader.ResourcesLoader;
Vasu Nori74f170f2010-06-01 18:06:18 -070050import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.database.sqlite.SQLiteDatabase;
52import android.database.sqlite.SQLiteDatabase.CursorFactory;
53import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Binder;
Jeff Brown6e539312015-02-24 18:53:21 -080057import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.Bundle;
Amith Yamasanicd757062012-10-19 18:23:52 -070059import android.os.Debug;
Oscar Montemayor539d3c42010-01-29 15:27:00 -080060import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.os.FileUtils;
62import android.os.Handler;
63import android.os.IBinder;
svetoslavganov75986cf2009-05-14 22:28:01 -070064import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070066import android.os.RemoteException;
Adam Lesinski4e862812016-11-21 16:02:24 -080067import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070068import android.os.UserHandle;
Jeff Sharkeya65e6492017-06-21 13:45:11 -060069import android.os.UserManager;
Jeff Sharkeyae266462017-11-27 13:32:24 -070070import android.os.storage.StorageManager;
Todd Kennedy8f135982019-07-02 07:35:15 -070071import android.permission.IPermissionManager;
Jeff Sharkeye84bdd32016-02-08 12:16:00 -070072import android.system.ErrnoException;
73import android.system.Os;
74import android.system.OsConstants;
Jeff Sharkey83aacde2017-03-22 23:13:39 -060075import android.system.StructStat;
Jordan Liu54735532019-10-29 10:33:55 -070076import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.util.AndroidRuntimeException;
Jeff Sharkey8e3ddab2013-06-17 18:26:37 -070078import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.util.Log;
Amith Yamasanicd757062012-10-19 18:23:52 -070080import android.util.Slog;
Jeff Brown98365d72012-08-19 20:30:52 -070081import android.view.Display;
Jeff Brown6e539312015-02-24 18:53:21 -080082import android.view.DisplayAdjustments;
Felipe Lemebb567ae2017-10-04 09:56:21 -070083import android.view.autofill.AutofillManager.AutofillClient;
Dan Egnor95240272009-10-27 18:23:39 -070084
Jeff Sharkey35871f22016-01-29 17:13:29 -070085import com.android.internal.annotations.GuardedBy;
86import com.android.internal.util.Preconditions;
87
Jeff Sharkeydd02e332018-06-27 14:41:57 -060088import dalvik.system.BlockGuard;
89
Jeff Sharkey83aacde2017-03-22 23:13:39 -060090import libcore.io.Memory;
Adam Lesinski4e862812016-11-21 16:02:24 -080091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.io.File;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
Jeff Sharkey35871f22016-01-29 17:13:29 -070096import java.io.FilenameFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.io.IOException;
98import java.io.InputStream;
Makoto Onukid67070e2018-03-30 12:39:14 -070099import java.lang.annotation.Retention;
100import java.lang.annotation.RetentionPolicy;
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600101import java.nio.ByteOrder;
Felka Chang0d824d42019-11-19 15:06:52 +0800102import java.nio.file.Path;
Christopher Tatefe2368c2017-05-17 15:42:35 -0700103import java.util.ArrayList;
Ryan Mitchell4579c0a2020-01-08 16:29:11 -0800104import java.util.List;
Jeff Sharkey7a30a302015-12-08 14:20:06 -0700105import java.util.Objects;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700106import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108class ReceiverRestrictedContext extends ContextWrapper {
Andrei Onea4b2116c2019-02-28 15:13:42 +0000109 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 ReceiverRestrictedContext(Context base) {
111 super(base);
112 }
113
114 @Override
115 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
116 return registerReceiver(receiver, filter, null, null);
117 }
118
119 @Override
120 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
121 String broadcastPermission, Handler scheduler) {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700122 if (receiver == null) {
123 // Allow retrieving current sticky broadcast; this is safe since we
124 // aren't actually registering a receiver.
125 return super.registerReceiver(null, filter, broadcastPermission, scheduler);
126 } else {
127 throw new ReceiverCallNotAllowedException(
128 "BroadcastReceiver components are not allowed to register to receive intents");
129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 }
131
132 @Override
Meng Wang3f9e0362019-11-05 10:43:45 -0800133 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter,
134 String broadcastPermission, Handler scheduler) {
135 return registerReceiverAsUser(
136 receiver, UserHandle.ALL, filter, broadcastPermission, scheduler);
137 }
138
139 @Override
Dianne Hackborn20e80982012-08-31 19:00:44 -0700140 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
141 IntentFilter filter, String broadcastPermission, Handler scheduler) {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700142 if (receiver == null) {
143 // Allow retrieving current sticky broadcast; this is safe since we
144 // aren't actually registering a receiver.
145 return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
146 } else {
147 throw new ReceiverCallNotAllowedException(
148 "BroadcastReceiver components are not allowed to register to receive intents");
149 }
Dianne Hackborn20e80982012-08-31 19:00:44 -0700150 }
151
152 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 public boolean bindService(Intent service, ServiceConnection conn, int flags) {
154 throw new ReceiverCallNotAllowedException(
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700155 "BroadcastReceiver components are not allowed to bind to services");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800157
158 @Override
Bo Liu58a57662019-03-06 20:21:45 +0000159 public boolean bindService(
160 Intent service, int flags, Executor executor, ServiceConnection conn) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800161 throw new ReceiverCallNotAllowedException(
Bo Liu58a57662019-03-06 20:21:45 +0000162 "BroadcastReceiver components are not allowed to bind to services");
163 }
164
165 @Override
166 public boolean bindIsolatedService(Intent service, int flags, String instanceName,
167 Executor executor, ServiceConnection conn) {
168 throw new ReceiverCallNotAllowedException(
169 "BroadcastReceiver components are not allowed to bind to services");
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171}
172
173/**
Dianne Hackborn21556372010-02-04 16:34:40 -0800174 * Common implementation of Context API, which provides the base
175 * context object for Activity and other application components.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 */
Dianne Hackborn21556372010-02-04 16:34:40 -0800177class ContextImpl extends Context {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800178 private final static String TAG = "ContextImpl";
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700179 private final static boolean DEBUG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600181 private static final String XATTR_INODE_CACHE = "user.inode_cache";
182 private static final String XATTR_INODE_CODE_CACHE = "user.inode_code_cache";
183
Jeff Sharkey8e3ddab2013-06-17 18:26:37 -0700184 /**
185 * Map from package name, to preference name, to cached preferences.
186 */
Jeff Sharkeybe782582016-02-15 18:35:57 -0700187 @GuardedBy("ContextImpl.class")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100188 @UnsupportedAppUsage
Jeff Sharkeybe782582016-02-15 18:35:57 -0700189 private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;
190
191 /**
192 * Map from preference name to generated path.
193 */
194 @GuardedBy("ContextImpl.class")
Mathew Inwood8c854f82018-09-14 12:35:36 +0100195 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeybe782582016-02-15 18:35:57 -0700196 private ArrayMap<String, File> mSharedPrefsPaths;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100198 @UnsupportedAppUsage
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800199 final @NonNull ActivityThread mMainThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100200 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000201 final @NonNull LoadedApk mPackageInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100202 @UnsupportedAppUsage
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800203 private @Nullable ClassLoader mClassLoader;
Jeff Browndefd4a62014-03-10 21:24:37 -0700204
Andrii Kulian4a316972020-01-21 21:41:38 -0800205 private final @Nullable IBinder mToken;
Jeff Browndefd4a62014-03-10 21:24:37 -0700206
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700207 private final @NonNull UserHandle mUser;
Jeff Browndefd4a62014-03-10 21:24:37 -0700208
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100209 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700210 private final ApplicationContentResolver mContentResolver;
211
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100212 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700213 private final String mBasePackageName;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100214 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Browndefd4a62014-03-10 21:24:37 -0700215 private final String mOpPackageName;
216
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700217 /** If of feature this context is for */
218 private final @Nullable String mFeatureId;
219
Adam Lesinski4ece3d62016-06-16 18:05:41 -0700220 private final @NonNull ResourcesManager mResourcesManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100221 @UnsupportedAppUsage
Adam Lesinski8fa71072016-11-18 18:13:55 -0800222 private @NonNull Resources mResources;
Andrii Kulian4a316972020-01-21 21:41:38 -0800223 private @Nullable Display mDisplay; // may be null if invalid display or not initialized yet.
Jeff Browndefd4a62014-03-10 21:24:37 -0700224
Mathew Inwood8c854f82018-09-14 12:35:36 +0100225 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkey7a30a302015-12-08 14:20:06 -0700226 private final int mFlags;
Jeff Browndefd4a62014-03-10 21:24:37 -0700227
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100228 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private Context mOuterContext;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100230 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private int mThemeResource = 0;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100232 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private Resources.Theme mTheme = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100234 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 private PackageManager mPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private Context mReceiverRestrictedContext = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800238 // The name of the split this Context is representing. May be null.
239 private @Nullable String mSplitName = null;
240
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800241 private @Nullable AutofillClient mAutofillClient = null;
242 private @Nullable AutofillOptions mAutofillOptions;
Felipe Lemebb567ae2017-10-04 09:56:21 -0700243
Felipe Leme326f15a2019-02-19 09:42:24 -0800244 private ContentCaptureOptions mContentCaptureOptions = null;
Felipe Lemeecb08be2018-11-27 15:48:47 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 private final Object mSync = new Object();
247
Andrii Kulian4a316972020-01-21 21:41:38 -0800248 private boolean mIsSystemOrSystemUiContext;
249 private boolean mIsUiContext;
250
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700251 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 private File mDatabasesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700253 @GuardedBy("mSync")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100254 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 private File mPreferencesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700256 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 private File mFilesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700258 @GuardedBy("mSync")
Felka Chang0d824d42019-11-19 15:06:52 +0800259 private File mCratesDir;
260 @GuardedBy("mSync")
Christopher Tatea7835b62014-07-11 17:25:57 -0700261 private File mNoBackupFilesDir;
262 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 private File mCacheDir;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700264 @GuardedBy("mSync")
265 private File mCodeCacheDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700266
Jeff Brown6e539312015-02-24 18:53:21 -0800267 // The system service cache for the system services that are cached per-ContextImpl.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100268 @UnsupportedAppUsage
Jeff Brown6e539312015-02-24 18:53:21 -0800269 final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
Brad Fitzpatrick224ba0c2010-11-12 12:22:15 -0800270
Makoto Onukif896f122018-01-25 09:50:24 -0800271 static final int STATE_UNINITIALIZED = 0;
272 static final int STATE_INITIALIZING = 1;
273 static final int STATE_READY = 2;
Makoto Onukid67070e2018-03-30 12:39:14 -0700274 static final int STATE_NOT_FOUND = 3;
275
276 /** @hide */
277 @IntDef(prefix = { "STATE_" }, value = {
278 STATE_UNINITIALIZED,
279 STATE_INITIALIZING,
280 STATE_READY,
281 STATE_NOT_FOUND,
282 })
283 @Retention(RetentionPolicy.SOURCE)
284 @interface ServiceInitializationState {}
Makoto Onukif896f122018-01-25 09:50:24 -0800285
286 /**
287 * Initialization state for each service. Any of {@link #STATE_UNINITIALIZED},
288 * {@link #STATE_INITIALIZING} or {@link #STATE_READY},
289 */
Makoto Onukid67070e2018-03-30 12:39:14 -0700290 @ServiceInitializationState
291 final int[] mServiceInitializationStateArray = new int[mServiceCache.length];
Makoto Onukif896f122018-01-25 09:50:24 -0800292
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100293 @UnsupportedAppUsage
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700294 static ContextImpl getImpl(Context context) {
295 Context nextContext;
296 while ((context instanceof ContextWrapper) &&
297 (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
298 context = nextContext;
299 }
300 return (ContextImpl)context;
301 }
302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 @Override
304 public AssetManager getAssets() {
Dianne Hackborn756220b2012-08-14 16:45:30 -0700305 return getResources().getAssets();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 }
307
308 @Override
309 public Resources getResources() {
310 return mResources;
311 }
312
313 @Override
314 public PackageManager getPackageManager() {
315 if (mPackageManager != null) {
316 return mPackageManager;
317 }
318
Todd Kennedy8f135982019-07-02 07:35:15 -0700319 final IPackageManager pm = ActivityThread.getPackageManager();
320 final IPermissionManager permissionManager = ActivityThread.getPermissionManager();
321 if (pm != null && permissionManager != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 // Doesn't matter if we make more than one instance.
Todd Kennedy8f135982019-07-02 07:35:15 -0700323 return (mPackageManager = new ApplicationPackageManager(this, pm, permissionManager));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
325
326 return null;
327 }
328
329 @Override
330 public ContentResolver getContentResolver() {
331 return mContentResolver;
332 }
333
334 @Override
335 public Looper getMainLooper() {
336 return mMainThread.getLooper();
337 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 @Override
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700340 public Executor getMainExecutor() {
341 return mMainThread.getExecutor();
342 }
343
344 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 public Context getApplicationContext() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000346 return (mPackageInfo != null) ?
347 mPackageInfo.getApplication() : mMainThread.getApplication();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 @Override
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700351 public void setTheme(int resId) {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700352 synchronized (mSync) {
353 if (mThemeResource != resId) {
354 mThemeResource = resId;
355 initializeTheme();
356 }
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 @Override
Dianne Hackborn247fe742011-01-08 17:25:57 -0800361 public int getThemeResId() {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700362 synchronized (mSync) {
363 return mThemeResource;
364 }
Dianne Hackborn247fe742011-01-08 17:25:57 -0800365 }
366
367 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368 public Resources.Theme getTheme() {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700369 synchronized (mSync) {
370 if (mTheme != null) {
371 return mTheme;
372 }
373
374 mThemeResource = Resources.selectDefaultTheme(mThemeResource,
375 getOuterContext().getApplicationInfo().targetSdkVersion);
376 initializeTheme();
377
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700378 return mTheme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 }
381
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700382 private void initializeTheme() {
383 if (mTheme == null) {
384 mTheme = mResources.newTheme();
385 }
386 mTheme.applyStyle(mThemeResource, true);
387 }
388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 @Override
390 public ClassLoader getClassLoader() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000391 return mClassLoader != null ? mClassLoader : (mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 }
393
394 @Override
395 public String getPackageName() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000396 if (mPackageInfo != null) {
397 return mPackageInfo.getPackageName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 }
Todd Kennedy233a0b12018-01-29 20:30:24 +0000399 // No mPackageInfo means this is a Context for the system itself,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800400 // and this here is its name.
401 return "android";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 }
403
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -0800404 /** @hide */
405 @Override
406 public String getBasePackageName() {
407 return mBasePackageName != null ? mBasePackageName : getPackageName();
408 }
409
Dianne Hackborn95d78532013-09-11 09:51:14 -0700410 /** @hide */
411 @Override
412 public String getOpPackageName() {
413 return mOpPackageName != null ? mOpPackageName : getBasePackageName();
414 }
415
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700416 /** @hide */
417 @Override
418 public @Nullable String getFeatureId() {
419 return mFeatureId;
420 }
421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 @Override
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700423 public ApplicationInfo getApplicationInfo() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000424 if (mPackageInfo != null) {
425 return mPackageInfo.getApplicationInfo();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700426 }
427 throw new RuntimeException("Not supported in system context");
428 }
429
430 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 public String getPackageResourcePath() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000432 if (mPackageInfo != null) {
433 return mPackageInfo.getResDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 }
435 throw new RuntimeException("Not supported in system context");
436 }
437
438 @Override
439 public String getPackageCodePath() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000440 if (mPackageInfo != null) {
441 return mPackageInfo.getAppDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 }
443 throw new RuntimeException("Not supported in system context");
444 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200445
Jeff Brown6e539312015-02-24 18:53:21 -0800446 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 public SharedPreferences getSharedPreferences(String name, int mode) {
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700448 // At least one application in the world actually passes in a null
449 // name. This happened to work because when we generated the file name
450 // we would stringify it to "null.xml". Nice.
Todd Kennedy233a0b12018-01-29 20:30:24 +0000451 if (mPackageInfo.getApplicationInfo().targetSdkVersion <
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700452 Build.VERSION_CODES.KITKAT) {
453 if (name == null) {
454 name = "null";
455 }
456 }
457
Jeff Sharkeybe782582016-02-15 18:35:57 -0700458 File file;
459 synchronized (ContextImpl.class) {
460 if (mSharedPrefsPaths == null) {
461 mSharedPrefsPaths = new ArrayMap<>();
462 }
463 file = mSharedPrefsPaths.get(name);
464 if (file == null) {
465 file = getSharedPreferencesPath(name);
466 mSharedPrefsPaths.put(name, file);
467 }
468 }
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700469 return getSharedPreferences(file, mode);
470 }
471
472 @Override
473 public SharedPreferences getSharedPreferences(File file, int mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800474 SharedPreferencesImpl sp;
Dianne Hackbornf6913592013-09-05 13:21:24 -0700475 synchronized (ContextImpl.class) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700476 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
477 sp = cache.get(file);
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700478 if (sp == null) {
John Reckf3903e92017-05-12 17:12:54 -0700479 checkMode(mode);
480 if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
481 if (isCredentialProtectedStorage()
Jeff Sharkeya65e6492017-06-21 13:45:11 -0600482 && !getSystemService(UserManager.class)
483 .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
John Reckf3903e92017-05-12 17:12:54 -0700484 throw new IllegalStateException("SharedPreferences in credential encrypted "
485 + "storage are not available until after user is unlocked");
486 }
487 }
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700488 sp = new SharedPreferencesImpl(file, mode);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700489 cache.put(file, sp);
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700490 return sp;
491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800493 if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
494 getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
495 // If somebody else (some other process) changed the prefs
496 // file behind our back, we reload it. This has been the
497 // historical (if undocumented) behavior.
498 sp.startReloadIfChangedUnexpectedly();
499 }
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700500 return sp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 }
502
Andreas Gampe3f24e692018-02-05 13:24:28 -0800503 @GuardedBy("ContextImpl.class")
Jeff Sharkey35871f22016-01-29 17:13:29 -0700504 private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
Jeff Sharkeybe782582016-02-15 18:35:57 -0700505 if (sSharedPrefsCache == null) {
506 sSharedPrefsCache = new ArrayMap<>();
Jeff Sharkey35871f22016-01-29 17:13:29 -0700507 }
508
509 final String packageName = getPackageName();
Jeff Sharkeybe782582016-02-15 18:35:57 -0700510 ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700511 if (packagePrefs == null) {
512 packagePrefs = new ArrayMap<>();
Jeff Sharkeybe782582016-02-15 18:35:57 -0700513 sSharedPrefsCache.put(packageName, packagePrefs);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700514 }
515
516 return packagePrefs;
517 }
518
Christopher Tatefe2368c2017-05-17 15:42:35 -0700519 @Override
520 public void reloadSharedPreferences() {
521 // Build the list of all per-context impls (i.e. caches) we know about
522 ArrayList<SharedPreferencesImpl> spImpls = new ArrayList<>();
523 synchronized (ContextImpl.class) {
524 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
525 for (int i = 0; i < cache.size(); i++) {
526 final SharedPreferencesImpl sp = cache.valueAt(i);
527 if (sp != null) {
528 spImpls.add(sp);
529 }
530 }
531 }
532
533 // Issue the reload outside the cache lock
534 for (int i = 0; i < spImpls.size(); i++) {
535 spImpls.get(i).startReloadIfChangedUnexpectedly();
536 }
537 }
538
Jeff Sharkey35871f22016-01-29 17:13:29 -0700539 /**
540 * Try our best to migrate all files from source to target that match
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700541 * requested prefix.
542 *
543 * @return the number of files moved, or -1 if there was trouble.
Jeff Sharkey35871f22016-01-29 17:13:29 -0700544 */
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600545 private static int moveFiles(File sourceDir, File targetDir, final String prefix) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700546 final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() {
547 @Override
548 public boolean accept(File dir, String name) {
549 return name.startsWith(prefix);
550 }
551 });
552
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700553 int res = 0;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700554 for (File sourceFile : sourceFiles) {
555 final File targetFile = new File(targetDir, sourceFile.getName());
556 Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile);
557 try {
558 FileUtils.copyFileOrThrow(sourceFile, targetFile);
559 FileUtils.copyPermissions(sourceFile, targetFile);
560 if (!sourceFile.delete()) {
561 throw new IOException("Failed to clean up " + sourceFile);
562 }
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700563 if (res != -1) {
564 res++;
565 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700566 } catch (IOException e) {
567 Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e);
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700568 res = -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700569 }
570 }
571 return res;
572 }
573
574 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600575 public boolean moveSharedPreferencesFrom(Context sourceContext, String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700576 synchronized (ContextImpl.class) {
577 final File source = sourceContext.getSharedPreferencesPath(name);
578 final File target = getSharedPreferencesPath(name);
579
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600580 final int res = moveFiles(source.getParentFile(), target.getParentFile(),
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700581 source.getName());
582 if (res > 0) {
583 // We moved at least one file, so evict any in-memory caches for
584 // either location
585 final ArrayMap<File, SharedPreferencesImpl> cache =
586 getSharedPreferencesCacheLocked();
587 cache.remove(source);
588 cache.remove(target);
589 }
590 return res != -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700591 }
592 }
593
594 @Override
595 public boolean deleteSharedPreferences(String name) {
596 synchronized (ContextImpl.class) {
597 final File prefs = getSharedPreferencesPath(name);
598 final File prefsBackup = SharedPreferencesImpl.makeBackupFile(prefs);
599
600 // Evict any in-memory caches
601 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
602 cache.remove(prefs);
603
604 prefs.delete();
605 prefsBackup.delete();
606
607 // We failed if files are still lingering
608 return !(prefs.exists() || prefsBackup.exists());
609 }
610 }
611
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100612 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 private File getPreferencesDir() {
614 synchronized (mSync) {
615 if (mPreferencesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700616 mPreferencesDir = new File(getDataDir(), "shared_prefs");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700618 return ensurePrivateDirExists(mPreferencesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620 }
621
622 @Override
623 public FileInputStream openFileInput(String name)
624 throws FileNotFoundException {
625 File f = makeFilename(getFilesDir(), name);
626 return new FileInputStream(f);
627 }
628
629 @Override
Jeff Sharkey634dc422016-01-30 17:44:15 -0700630 public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
631 checkMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 final boolean append = (mode&MODE_APPEND) != 0;
633 File f = makeFilename(getFilesDir(), name);
634 try {
635 FileOutputStream fos = new FileOutputStream(f, append);
636 setFilePermissionsFromMode(f.getPath(), mode, 0);
637 return fos;
638 } catch (FileNotFoundException e) {
639 }
640
641 File parent = f.getParentFile();
642 parent.mkdir();
643 FileUtils.setPermissions(
644 parent.getPath(),
645 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
646 -1, -1);
647 FileOutputStream fos = new FileOutputStream(f, append);
648 setFilePermissionsFromMode(f.getPath(), mode, 0);
649 return fos;
650 }
651
652 @Override
653 public boolean deleteFile(String name) {
654 File f = makeFilename(getFilesDir(), name);
655 return f.delete();
656 }
657
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700658 /**
659 * Common-path handling of app data dir creation
660 */
Jeff Sharkey35871f22016-01-29 17:13:29 -0700661 private static File ensurePrivateDirExists(File file) {
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600662 return ensurePrivateDirExists(file, 0771, -1, null);
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700663 }
664
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600665 private static File ensurePrivateCacheDirExists(File file, String xattr) {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700666 final int gid = UserHandle.getCacheAppGid(Process.myUid());
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600667 return ensurePrivateDirExists(file, 02771, gid, xattr);
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700668 }
669
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600670 private static File ensurePrivateDirExists(File file, int mode, int gid, String xattr) {
Christopher Tatea7835b62014-07-11 17:25:57 -0700671 if (!file.exists()) {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700672 final String path = file.getAbsolutePath();
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700673 try {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700674 Os.mkdir(path, mode);
675 Os.chmod(path, mode);
676 if (gid != -1) {
677 Os.chown(path, -1, gid);
678 }
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700679 } catch (ErrnoException e) {
680 if (e.errno == OsConstants.EEXIST) {
681 // We must have raced with someone; that's okay
682 } else {
683 Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
Christopher Tatea7835b62014-07-11 17:25:57 -0700684 }
Christopher Tatea7835b62014-07-11 17:25:57 -0700685 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600686
687 if (xattr != null) {
688 try {
689 final StructStat stat = Os.stat(file.getAbsolutePath());
690 final byte[] value = new byte[8];
691 Memory.pokeLong(value, 0, stat.st_ino, ByteOrder.nativeOrder());
692 Os.setxattr(file.getParentFile().getAbsolutePath(), xattr, value, 0);
693 } catch (ErrnoException e) {
694 Log.w(TAG, "Failed to update " + xattr + ": " + e.getMessage());
695 }
696 }
Christopher Tatea7835b62014-07-11 17:25:57 -0700697 }
698 return file;
699 }
700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 @Override
702 public File getFilesDir() {
703 synchronized (mSync) {
704 if (mFilesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700705 mFilesDir = new File(getDataDir(), "files");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700707 return ensurePrivateDirExists(mFilesDir);
Christopher Tatea7835b62014-07-11 17:25:57 -0700708 }
709 }
710
711 @Override
Felka Chang0d824d42019-11-19 15:06:52 +0800712 public File getCrateDir(@NonNull String crateId) {
713 Preconditions.checkArgument(FileUtils.isValidExtFilename(crateId), "invalidated crateId");
714 final Path cratesRootPath = getDataDir().toPath().resolve("crates");
715 final Path absoluteNormalizedCratePath = cratesRootPath.resolve(crateId)
716 .toAbsolutePath().normalize();
717
718 synchronized (mSync) {
719 if (mCratesDir == null) {
720 mCratesDir = cratesRootPath.toFile();
721 }
722 ensurePrivateDirExists(mCratesDir);
723 }
724
725 File cratedDir = absoluteNormalizedCratePath.toFile();
726 return ensurePrivateDirExists(cratedDir);
727 }
728
729 @Override
Christopher Tatea7835b62014-07-11 17:25:57 -0700730 public File getNoBackupFilesDir() {
731 synchronized (mSync) {
732 if (mNoBackupFilesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700733 mNoBackupFilesDir = new File(getDataDir(), "no_backup");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700735 return ensurePrivateDirExists(mNoBackupFilesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 }
737 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 @Override
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800740 public File getExternalFilesDir(String type) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700741 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700742 final File[] dirs = getExternalFilesDirs(type);
743 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700744 }
745
746 @Override
747 public File[] getExternalFilesDirs(String type) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800748 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600749 File[] dirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700750 if (type != null) {
751 dirs = Environment.buildPaths(dirs, type);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800752 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700753 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800754 }
755 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200756
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800757 @Override
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800758 public File getObbDir() {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700759 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700760 final File[] dirs = getObbDirs();
761 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700762 }
763
764 @Override
765 public File[] getObbDirs() {
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800766 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600767 File[] dirs = Environment.buildExternalStorageAppObbDirs(getPackageName());
768 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800769 }
770 }
771
772 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 public File getCacheDir() {
774 synchronized (mSync) {
775 if (mCacheDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700776 mCacheDir = new File(getDataDir(), "cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600778 return ensurePrivateCacheDirExists(mCacheDir, XATTR_INODE_CACHE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200781
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800782 @Override
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700783 public File getCodeCacheDir() {
784 synchronized (mSync) {
785 if (mCodeCacheDir == null) {
Alex Light2d0691c2019-10-03 14:36:57 -0700786 mCodeCacheDir = getCodeCacheDirBeforeBind(getDataDir());
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700787 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600788 return ensurePrivateCacheDirExists(mCodeCacheDir, XATTR_INODE_CODE_CACHE);
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700789 }
790 }
791
Alex Light2d0691c2019-10-03 14:36:57 -0700792 /**
793 * Helper for getting code-cache dir potentially before application bind.
794 *
795 * @hide
796 */
797 static File getCodeCacheDirBeforeBind(File dataDir) {
798 return new File(dataDir, "code_cache");
799 }
800
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700801 @Override
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800802 public File getExternalCacheDir() {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700803 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700804 final File[] dirs = getExternalCacheDirs();
805 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700806 }
807
808 @Override
809 public File[] getExternalCacheDirs() {
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800810 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600811 File[] dirs = Environment.buildExternalStorageAppCacheDirs(getPackageName());
812 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800813 }
814 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 @Override
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700817 public File[] getExternalMediaDirs() {
818 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600819 File[] dirs = Environment.buildExternalStorageAppMediaDirs(getPackageName());
820 return ensureExternalDirsExistOrFilter(dirs);
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700821 }
822 }
823
Fyodor Kupolov61221292016-09-02 15:21:03 -0700824 /**
825 * @hide
826 */
827 @Nullable
828 @Override
829 public File getPreloadsFileCache() {
830 return Environment.getDataPreloadsFileCacheDirectory(getPackageName());
831 }
832
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700833 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 public File getFileStreamPath(String name) {
835 return makeFilename(getFilesDir(), name);
836 }
837
838 @Override
Jeff Sharkey6a6cdaf2015-12-07 19:25:19 -0700839 public File getSharedPreferencesPath(String name) {
840 return makeFilename(getPreferencesDir(), name + ".xml");
841 }
842
843 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 public String[] fileList() {
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700845 return FileUtils.listOrEmpty(getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847
848 @Override
849 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
Jeff Brown47847f32012-03-22 19:13:11 -0700850 return openOrCreateDatabase(name, mode, factory, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852
853 @Override
Vasu Nori74f170f2010-06-01 18:06:18 -0700854 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
855 DatabaseErrorHandler errorHandler) {
Jeff Sharkey634dc422016-01-30 17:44:15 -0700856 checkMode(mode);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700857 File f = getDatabasePath(name);
Jeff Brown47847f32012-03-22 19:13:11 -0700858 int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
859 if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
860 flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
861 }
Sunny Goyala21e6b22015-12-02 09:51:02 -0800862 if ((mode & MODE_NO_LOCALIZED_COLLATORS) != 0) {
863 flags |= SQLiteDatabase.NO_LOCALIZED_COLLATORS;
864 }
Jeff Brown47847f32012-03-22 19:13:11 -0700865 SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
Vasu Nori74f170f2010-06-01 18:06:18 -0700866 setFilePermissionsFromMode(f.getPath(), mode, 0);
867 return db;
868 }
869
870 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600871 public boolean moveDatabaseFrom(Context sourceContext, String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700872 synchronized (ContextImpl.class) {
873 final File source = sourceContext.getDatabasePath(name);
874 final File target = getDatabasePath(name);
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600875 return moveFiles(source.getParentFile(), target.getParentFile(),
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700876 source.getName()) != -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700877 }
878 }
879
880 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 public boolean deleteDatabase(String name) {
882 try {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700883 File f = getDatabasePath(name);
Jeff Brown79087e42012-03-01 19:52:44 -0800884 return SQLiteDatabase.deleteDatabase(f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 } catch (Exception e) {
886 }
887 return false;
888 }
889
890 @Override
891 public File getDatabasePath(String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700892 File dir;
893 File f;
894
895 if (name.charAt(0) == File.separatorChar) {
896 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
897 dir = new File(dirPath);
898 name = name.substring(name.lastIndexOf(File.separatorChar));
899 f = new File(dir, name);
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700900
901 if (!dir.isDirectory() && dir.mkdir()) {
902 FileUtils.setPermissions(dir.getPath(),
903 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
904 -1, -1);
905 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700906 } else {
907 dir = getDatabasesDir();
908 f = makeFilename(dir, name);
909 }
910
Jeff Sharkey35871f22016-01-29 17:13:29 -0700911 return f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
913
914 @Override
915 public String[] databaseList() {
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700916 return FileUtils.listOrEmpty(getDatabasesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 private File getDatabasesDir() {
920 synchronized (mSync) {
921 if (mDatabasesDir == null) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700922 if ("android".equals(getPackageName())) {
923 mDatabasesDir = new File("/data/system");
924 } else {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700925 mDatabasesDir = new File(getDataDir(), "databases");
Jeff Sharkey35871f22016-01-29 17:13:29 -0700926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700928 return ensurePrivateDirExists(mDatabasesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800933 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 public Drawable getWallpaper() {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700935 return getWallpaperManager().getDrawable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937
938 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800939 @Deprecated
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700940 public Drawable peekWallpaper() {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700941 return getWallpaperManager().peekDrawable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 }
943
944 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800945 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 public int getWallpaperDesiredMinimumWidth() {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700947 return getWallpaperManager().getDesiredMinimumWidth();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
949
950 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800951 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 public int getWallpaperDesiredMinimumHeight() {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700953 return getWallpaperManager().getDesiredMinimumHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
956 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800957 @Deprecated
958 public void setWallpaper(Bitmap bitmap) throws IOException {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700959 getWallpaperManager().setBitmap(bitmap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 }
961
962 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800963 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 public void setWallpaper(InputStream data) throws IOException {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700965 getWallpaperManager().setStream(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 }
967
968 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800969 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 public void clearWallpaper() throws IOException {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700971 getWallpaperManager().clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973
Jeff Brown6e539312015-02-24 18:53:21 -0800974 private WallpaperManager getWallpaperManager() {
975 return getSystemService(WallpaperManager.class);
976 }
977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 @Override
979 public void startActivity(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -0700980 warnIfCallingFromSystemProcess();
Dianne Hackborna4972e92012-03-14 10:38:05 -0700981 startActivity(intent, null);
982 }
983
Amith Yamasani82644082012-08-03 13:09:11 -0700984 /** @hide */
985 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700986 public void startActivityAsUser(Intent intent, UserHandle user) {
Dianne Hackbornf1c26e22012-08-23 13:54:58 -0700987 startActivityAsUser(intent, null, user);
Amith Yamasani82644082012-08-03 13:09:11 -0700988 }
989
Dianne Hackborna4972e92012-03-14 10:38:05 -0700990 @Override
991 public void startActivity(Intent intent, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -0700992 warnIfCallingFromSystemProcess();
Jorim Jaggi2adba072016-03-03 13:43:39 +0100993
994 // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
995 // generally not allowed, except if the caller specifies the task id the activity should
Bryce Leef465ea02017-05-02 16:58:22 -0700996 // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
997 // maintain this for backwards compatibility.
998 final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
999
1000 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
1001 && (targetSdkVersion < Build.VERSION_CODES.N
1002 || targetSdkVersion >= Build.VERSION_CODES.P)
1003 && (options == null
1004 || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 throw new AndroidRuntimeException(
1006 "Calling startActivity() from outside of an Activity "
Bryce Leef465ea02017-05-02 16:58:22 -07001007 + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
1008 + " Is this really what you want?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
1010 mMainThread.getInstrumentation().execStartActivity(
Dianne Hackborna750a632015-06-16 17:18:23 -07001011 getOuterContext(), mMainThread.getApplicationThread(), null,
1012 (Activity) null, intent, -1, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
1014
Amith Yamasani258848d2012-08-10 17:06:33 -07001015 /** @hide */
1016 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001017 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001018 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001019 ActivityTaskManager.getService().startActivityAsUser(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001020 mMainThread.getApplicationThread(), getBasePackageName(), intent,
Amith Yamasani258848d2012-08-10 17:06:33 -07001021 intent.resolveTypeIfNeeded(getContentResolver()),
Jeff Hao1b012d32014-08-20 10:35:34 -07001022 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001023 user.getIdentifier());
Dianne Hackborne5c42622015-05-19 16:04:04 -07001024 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001025 throw e.rethrowFromSystemServer();
Amith Yamasani258848d2012-08-10 17:06:33 -07001026 }
1027 }
1028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 @Override
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001030 public void startActivities(Intent[] intents) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001031 warnIfCallingFromSystemProcess();
Dianne Hackborna4972e92012-03-14 10:38:05 -07001032 startActivities(intents, null);
1033 }
1034
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001035 /** @hide */
1036 @Override
Selim Cinek7fa385a2018-01-24 08:35:28 -08001037 public int startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001038 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1039 throw new AndroidRuntimeException(
1040 "Calling startActivities() from outside of an Activity "
1041 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1042 + " Is this really what you want?");
1043 }
Selim Cinek7fa385a2018-01-24 08:35:28 -08001044 return mMainThread.getInstrumentation().execStartActivitiesAsUser(
Dianne Hackborna750a632015-06-16 17:18:23 -07001045 getOuterContext(), mMainThread.getApplicationThread(), null,
1046 (Activity) null, intents, options, userHandle.getIdentifier());
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001047 }
1048
Dianne Hackborna4972e92012-03-14 10:38:05 -07001049 @Override
1050 public void startActivities(Intent[] intents, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001051 warnIfCallingFromSystemProcess();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001052 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1053 throw new AndroidRuntimeException(
1054 "Calling startActivities() from outside of an Activity "
1055 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1056 + " Is this really what you want?");
1057 }
1058 mMainThread.getInstrumentation().execStartActivities(
Dianne Hackborna750a632015-06-16 17:18:23 -07001059 getOuterContext(), mMainThread.getApplicationThread(), null,
1060 (Activity) null, intents, options);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001061 }
1062
1063 @Override
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001064 public void startIntentSender(IntentSender intent,
1065 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
1066 throws IntentSender.SendIntentException {
Dianne Hackborna4972e92012-03-14 10:38:05 -07001067 startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
1068 }
1069
1070 @Override
1071 public void startIntentSender(IntentSender intent, Intent fillInIntent,
1072 int flagsMask, int flagsValues, int extraFlags, Bundle options)
1073 throws IntentSender.SendIntentException {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001074 try {
1075 String resolvedType = null;
1076 if (fillInIntent != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07001077 fillInIntent.migrateExtraStreamToClipData();
Jeff Sharkey344744b2016-01-28 19:03:30 -07001078 fillInIntent.prepareToLeaveProcess(this);
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001079 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
1080 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001081 int result = ActivityTaskManager.getService()
Dianne Hackborn3e6e3852017-05-19 16:12:08 -07001082 .startActivityIntentSender(mMainThread.getApplicationThread(),
1083 intent != null ? intent.getTarget() : null,
1084 intent != null ? intent.getWhitelistToken() : null,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001085 fillInIntent, resolvedType, null, null,
Dianne Hackborna4972e92012-03-14 10:38:05 -07001086 0, flagsMask, flagsValues, options);
1087 if (result == ActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001088 throw new IntentSender.SendIntentException();
1089 }
1090 Instrumentation.checkStartActivityResult(result, null);
1091 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001092 throw e.rethrowFromSystemServer();
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001093 }
1094 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02001095
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001096 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 public void sendBroadcast(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001098 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1100 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001101 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001102 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001103 mMainThread.getApplicationThread(), intent, resolvedType, null,
1104 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
1105 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001107 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109 }
1110
Amith Yamasani67cf7d32012-02-16 14:31:23 -08001111 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 public void sendBroadcast(Intent intent, String receiverPermission) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001113 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001115 String[] receiverPermissions = receiverPermission == null ? null
1116 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001118 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001119 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001120 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001121 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1122 null, false, false, getUserId());
1123 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001124 throw e.rethrowFromSystemServer();
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001125 }
1126 }
1127
1128 @Override
1129 public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions) {
1130 warnIfCallingFromSystemProcess();
1131 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1132 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001133 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001134 ActivityManager.getService().broadcastIntent(
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001135 mMainThread.getApplicationThread(), intent, resolvedType, null,
1136 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001137 null, false, false, getUserId());
1138 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001139 throw e.rethrowFromSystemServer();
Dianne Hackborna750a632015-06-16 17:18:23 -07001140 }
1141 }
1142
1143 @Override
Tyler Gunnf955e562018-04-26 14:43:31 -07001144 public void sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user,
1145 String[] receiverPermissions) {
Tyler Gunnf955e562018-04-26 14:43:31 -07001146 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1147 try {
1148 intent.prepareToLeaveProcess(this);
1149 ActivityManager.getService().broadcastIntent(
1150 mMainThread.getApplicationThread(), intent, resolvedType, null,
1151 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1152 null, false, false, user.getIdentifier());
1153 } catch (RemoteException e) {
1154 throw e.rethrowFromSystemServer();
1155 }
1156 }
1157
1158 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001159 public void sendBroadcast(Intent intent, String receiverPermission, Bundle options) {
1160 warnIfCallingFromSystemProcess();
1161 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001162 String[] receiverPermissions = receiverPermission == null ? null
1163 : new String[] {receiverPermission};
Dianne Hackborna750a632015-06-16 17:18:23 -07001164 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001165 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001166 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001167 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001168 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001169 options, false, false, getUserId());
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001170 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001171 throw e.rethrowFromSystemServer();
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001172 }
1173 }
1174
1175 @Override
1176 public void sendBroadcast(Intent intent, String receiverPermission, int appOp) {
1177 warnIfCallingFromSystemProcess();
1178 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001179 String[] receiverPermissions = receiverPermission == null ? null
1180 : new String[] {receiverPermission};
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001181 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001182 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001183 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001184 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001185 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
Dianne Hackborna750a632015-06-16 17:18:23 -07001186 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001188 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 }
1191
1192 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001193 public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001194 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001196 String[] receiverPermissions = receiverPermission == null ? null
1197 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001199 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001200 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001201 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001202 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001203 null, true, false, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001205 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207 }
1208
1209 @Override
1210 public void sendOrderedBroadcast(Intent intent,
1211 String receiverPermission, BroadcastReceiver resultReceiver,
1212 Handler scheduler, int initialCode, String initialData,
1213 Bundle initialExtras) {
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001214 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001215 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1216 }
1217
1218 @Override
1219 public void sendOrderedBroadcast(Intent intent,
1220 String receiverPermission, Bundle options, BroadcastReceiver resultReceiver,
1221 Handler scheduler, int initialCode, String initialData,
1222 Bundle initialExtras) {
1223 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
1224 resultReceiver, scheduler, initialCode, initialData, initialExtras, options);
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001225 }
1226
1227 @Override
1228 public void sendOrderedBroadcast(Intent intent,
1229 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1230 Handler scheduler, int initialCode, String initialData,
1231 Bundle initialExtras) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001232 sendOrderedBroadcast(intent, receiverPermission, appOp,
1233 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1234 }
1235
1236 void sendOrderedBroadcast(Intent intent,
1237 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1238 Handler scheduler, int initialCode, String initialData,
1239 Bundle initialExtras, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001240 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 IIntentReceiver rd = null;
1242 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001243 if (mPackageInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 if (scheduler == null) {
1245 scheduler = mMainThread.getHandler();
1246 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001247 rd = mPackageInfo.getReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 resultReceiver, getOuterContext(), scheduler,
1249 mMainThread.getInstrumentation(), false);
1250 } else {
1251 if (scheduler == null) {
1252 scheduler = mMainThread.getHandler();
1253 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001254 rd = new LoadedApk.ReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1256 }
1257 }
1258 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001259 String[] receiverPermissions = receiverPermission == null ? null
1260 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001262 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001263 ActivityManager.getService().broadcastIntent(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 mMainThread.getApplicationThread(), intent, resolvedType, rd,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001265 initialCode, initialData, initialExtras, receiverPermissions, appOp,
Dianne Hackborna750a632015-06-16 17:18:23 -07001266 options, true, false, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001268 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
1270 }
1271
1272 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001273 public void sendBroadcastAsUser(Intent intent, UserHandle user) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001274 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1275 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001276 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001277 ActivityManager.getService().broadcastIntent(mMainThread.getApplicationThread(),
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001278 intent, resolvedType, null, Activity.RESULT_OK, null, null, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001279 AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001280 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001281 throw e.rethrowFromSystemServer();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001282 }
1283 }
1284
1285 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001286 public void sendBroadcastAsUser(Intent intent, UserHandle user,
1287 String receiverPermission) {
Svet Ganov16a16892015-04-16 10:32:04 -07001288 sendBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE);
1289 }
1290
1291 @Override
Chad Brubaker52c8edc2016-07-25 14:30:26 -07001292 public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission,
1293 Bundle options) {
1294 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1295 String[] receiverPermissions = receiverPermission == null ? null
1296 : new String[] {receiverPermission};
1297 try {
1298 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001299 ActivityManager.getService().broadcastIntent(
Chad Brubaker52c8edc2016-07-25 14:30:26 -07001300 mMainThread.getApplicationThread(), intent, resolvedType, null,
1301 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1302 options, false, false, user.getIdentifier());
1303 } catch (RemoteException e) {
1304 throw e.rethrowFromSystemServer();
1305 }
1306 }
1307
1308 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001309 public void sendBroadcastAsUser(Intent intent, UserHandle user,
1310 String receiverPermission, int appOp) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001311 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001312 String[] receiverPermissions = receiverPermission == null ? null
1313 : new String[] {receiverPermission};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001314 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001315 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001316 ActivityManager.getService().broadcastIntent(
Svet Ganov16a16892015-04-16 10:32:04 -07001317 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001318 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
Svet Ganov16a16892015-04-16 10:32:04 -07001319 user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001320 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001321 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001322 }
1323 }
1324
1325 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001326 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001327 String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001328 int initialCode, String initialData, Bundle initialExtras) {
Amith Yamasani3cf75722014-05-16 12:37:29 -07001329 sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001330 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
Amith Yamasani3cf75722014-05-16 12:37:29 -07001331 }
1332
1333 @Override
1334 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1335 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001336 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
1337 sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp,
1338 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
1339 }
1340
1341 @Override
1342 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1343 String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver,
1344 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001345 IIntentReceiver rd = null;
1346 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001347 if (mPackageInfo != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001348 if (scheduler == null) {
1349 scheduler = mMainThread.getHandler();
1350 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001351 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001352 resultReceiver, getOuterContext(), scheduler,
1353 mMainThread.getInstrumentation(), false);
1354 } else {
1355 if (scheduler == null) {
1356 scheduler = mMainThread.getHandler();
1357 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001358 rd = new LoadedApk.ReceiverDispatcher(resultReceiver, getOuterContext(),
1359 scheduler, null, false).getIIntentReceiver();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001360 }
1361 }
1362 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001363 String[] receiverPermissions = receiverPermission == null ? null
1364 : new String[] {receiverPermission};
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001365 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001366 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001367 ActivityManager.getService().broadcastIntent(
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001368 mMainThread.getApplicationThread(), intent, resolvedType, rd,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001369 initialCode, initialData, initialExtras, receiverPermissions,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001370 appOp, options, true, false, user.getIdentifier());
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001371 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001372 throw e.rethrowFromSystemServer();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001373 }
1374 }
1375
1376 @Override
Jordan Liu54735532019-10-29 10:33:55 -07001377 public void sendOrderedBroadcast(Intent intent, String receiverPermission,
1378 String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler,
1379 int initialCode, String initialData, @Nullable Bundle initialExtras) {
1380 int intAppOp = AppOpsManager.OP_NONE;
1381 if (!TextUtils.isEmpty(receiverAppOp)) {
1382 intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1383 }
1384 sendOrderedBroadcastAsUser(intent, getUser(),
1385 receiverPermission, intAppOp, resultReceiver, scheduler, initialCode, initialData,
1386 initialExtras);
1387 }
1388
1389 @Override
Peter Wang7701f572019-11-07 16:57:23 -08001390 public void sendOrderedBroadcast(Intent intent, String receiverPermission, String receiverAppOp,
1391 Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
1392 String initialData, @Nullable Bundle initialExtras) {
1393 int intAppOp = AppOpsManager.OP_NONE;
1394 if (!TextUtils.isEmpty(receiverAppOp)) {
1395 intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1396 }
1397 sendOrderedBroadcastAsUser(intent, getUser(), receiverPermission, intAppOp, options,
1398 resultReceiver, scheduler, initialCode, initialData, initialExtras);
1399 }
1400
1401 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001402 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 public void sendStickyBroadcast(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001404 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1406 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001407 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001408 ActivityManager.getService().broadcastIntent(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 mMainThread.getApplicationThread(), intent, resolvedType, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001410 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001411 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001413 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415 }
1416
1417 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001418 @Deprecated
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001419 public void sendStickyOrderedBroadcast(Intent intent,
1420 BroadcastReceiver resultReceiver,
1421 Handler scheduler, int initialCode, String initialData,
1422 Bundle initialExtras) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001423 warnIfCallingFromSystemProcess();
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001424 IIntentReceiver rd = null;
1425 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001426 if (mPackageInfo != null) {
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001427 if (scheduler == null) {
1428 scheduler = mMainThread.getHandler();
1429 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001430 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001431 resultReceiver, getOuterContext(), scheduler,
1432 mMainThread.getInstrumentation(), false);
1433 } else {
1434 if (scheduler == null) {
1435 scheduler = mMainThread.getHandler();
1436 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001437 rd = new LoadedApk.ReceiverDispatcher(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001438 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1439 }
1440 }
1441 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1442 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001443 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001444 ActivityManager.getService().broadcastIntent(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001445 mMainThread.getApplicationThread(), intent, resolvedType, rd,
1446 initialCode, initialData, initialExtras, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001447 AppOpsManager.OP_NONE, null, true, true, getUserId());
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001448 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001449 throw e.rethrowFromSystemServer();
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001450 }
1451 }
1452
1453 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001454 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public void removeStickyBroadcast(Intent intent) {
1456 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1457 if (resolvedType != null) {
1458 intent = new Intent(intent);
1459 intent.setDataAndType(intent.getData(), resolvedType);
1460 }
1461 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001462 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001463 ActivityManager.getService().unbroadcastIntent(
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001464 mMainThread.getApplicationThread(), intent, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001466 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 }
1469
1470 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001471 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001472 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
1473 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1474 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001475 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001476 ActivityManager.getService().broadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001477 mMainThread.getApplicationThread(), intent, resolvedType, null,
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001478 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
1479 user.getIdentifier());
1480 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001481 throw e.rethrowFromSystemServer();
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001482 }
1483 }
1484
1485 @Override
1486 @Deprecated
1487 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options) {
1488 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1489 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001490 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001491 ActivityManager.getService().broadcastIntent(
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001492 mMainThread.getApplicationThread(), intent, resolvedType, null,
1493 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, options, false, true,
1494 user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001495 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001496 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001497 }
1498 }
1499
1500 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001501 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001502 public void sendStickyOrderedBroadcastAsUser(Intent intent,
1503 UserHandle user, BroadcastReceiver resultReceiver,
1504 Handler scheduler, int initialCode, String initialData,
1505 Bundle initialExtras) {
1506 IIntentReceiver rd = null;
1507 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001508 if (mPackageInfo != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001509 if (scheduler == null) {
1510 scheduler = mMainThread.getHandler();
1511 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001512 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001513 resultReceiver, getOuterContext(), scheduler,
1514 mMainThread.getInstrumentation(), false);
1515 } else {
1516 if (scheduler == null) {
1517 scheduler = mMainThread.getHandler();
1518 }
1519 rd = new LoadedApk.ReceiverDispatcher(
1520 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1521 }
1522 }
1523 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1524 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001525 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001526 ActivityManager.getService().broadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001527 mMainThread.getApplicationThread(), intent, resolvedType, rd,
1528 initialCode, initialData, initialExtras, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001529 AppOpsManager.OP_NONE, null, true, true, user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001530 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001531 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001532 }
1533 }
1534
1535 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001536 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001537 public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
1538 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1539 if (resolvedType != null) {
1540 intent = new Intent(intent);
1541 intent.setDataAndType(intent.getData(), resolvedType);
1542 }
1543 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001544 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001545 ActivityManager.getService().unbroadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001546 mMainThread.getApplicationThread(), intent, user.getIdentifier());
1547 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001548 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001549 }
1550 }
1551
1552 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1554 return registerReceiver(receiver, filter, null, null);
1555 }
1556
1557 @Override
1558 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001559 int flags) {
1560 return registerReceiver(receiver, filter, null, null, flags);
Chad Brubaker816c83b2017-03-02 10:27:59 -08001561 }
1562
1563 @Override
1564 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 String broadcastPermission, Handler scheduler) {
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001566 return registerReceiverInternal(receiver, getUserId(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001567 filter, broadcastPermission, scheduler, getOuterContext(), 0);
Chad Brubaker816c83b2017-03-02 10:27:59 -08001568 }
1569
1570 @Override
1571 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001572 String broadcastPermission, Handler scheduler, int flags) {
Chad Brubaker816c83b2017-03-02 10:27:59 -08001573 return registerReceiverInternal(receiver, getUserId(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001574 filter, broadcastPermission, scheduler, getOuterContext(), flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576
Dianne Hackborn20e80982012-08-31 19:00:44 -07001577 @Override
Meng Wang3f9e0362019-11-05 10:43:45 -08001578 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
1579 IntentFilter filter, String broadcastPermission, Handler scheduler) {
1580 return registerReceiverAsUser(receiver, UserHandle.ALL,
1581 filter, broadcastPermission, scheduler);
1582 }
1583
1584 @Override
Dianne Hackborn20e80982012-08-31 19:00:44 -07001585 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
1586 IntentFilter filter, String broadcastPermission, Handler scheduler) {
1587 return registerReceiverInternal(receiver, user.getIdentifier(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001588 filter, broadcastPermission, scheduler, getOuterContext(), 0);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001589 }
1590
1591 private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 IntentFilter filter, String broadcastPermission,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001593 Handler scheduler, Context context, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 IIntentReceiver rd = null;
1595 if (receiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001596 if (mPackageInfo != null && context != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 if (scheduler == null) {
1598 scheduler = mMainThread.getHandler();
1599 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001600 rd = mPackageInfo.getReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 receiver, context, scheduler,
1602 mMainThread.getInstrumentation(), true);
1603 } else {
1604 if (scheduler == null) {
1605 scheduler = mMainThread.getHandler();
1606 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001607 rd = new LoadedApk.ReceiverDispatcher(
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001608 receiver, context, scheduler, null, true).getIIntentReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 }
1611 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001612 final Intent intent = ActivityManager.getService().registerReceiver(
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001613 mMainThread.getApplicationThread(), mBasePackageName, rd, filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001614 broadcastPermission, userId, flags);
Jeff Sharkeyd136e512016-03-09 22:30:56 -07001615 if (intent != null) {
1616 intent.setExtrasClassLoader(getClassLoader());
1617 intent.prepareToEnterProcess();
1618 }
1619 return intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001621 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
1624
1625 @Override
1626 public void unregisterReceiver(BroadcastReceiver receiver) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001627 if (mPackageInfo != null) {
1628 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 getOuterContext(), receiver);
1630 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001631 ActivityManager.getService().unregisterReceiver(rd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001633 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 } else {
1636 throw new RuntimeException("Not supported in system context");
1637 }
1638 }
1639
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001640 private void validateServiceIntent(Intent service) {
1641 if (service.getComponent() == null && service.getPackage() == null) {
Dianne Hackborn955d8d62014-10-07 20:17:19 -07001642 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001643 IllegalArgumentException ex = new IllegalArgumentException(
1644 "Service Intent must be explicit: " + service);
1645 throw ex;
1646 } else {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001647 Log.w(TAG, "Implicit intents with startService are not safe: " + service
1648 + " " + Debug.getCallers(2, 3));
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001649 }
1650 }
1651 }
1652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 @Override
1654 public ComponentName startService(Intent service) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001655 warnIfCallingFromSystemProcess();
Christopher Tate242ba3e92017-04-14 15:07:06 -07001656 return startServiceCommon(service, false, mUser);
Christopher Tate42a386b2016-11-07 12:21:21 -08001657 }
1658
1659 @Override
Christopher Tate79047c62017-03-21 11:37:06 -07001660 public ComponentName startForegroundService(Intent service) {
1661 warnIfCallingFromSystemProcess();
Christopher Tate242ba3e92017-04-14 15:07:06 -07001662 return startServiceCommon(service, true, mUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001663 }
1664
1665 @Override
1666 public boolean stopService(Intent service) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001667 warnIfCallingFromSystemProcess();
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001668 return stopServiceCommon(service, mUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001669 }
1670
1671 @Override
1672 public ComponentName startServiceAsUser(Intent service, UserHandle user) {
Christopher Tate242ba3e92017-04-14 15:07:06 -07001673 return startServiceCommon(service, false, user);
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001674 }
1675
Christopher Tate42a386b2016-11-07 12:21:21 -08001676 @Override
Christopher Tate79047c62017-03-21 11:37:06 -07001677 public ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
Christopher Tate242ba3e92017-04-14 15:07:06 -07001678 return startServiceCommon(service, true, user);
Christopher Tate79047c62017-03-21 11:37:06 -07001679 }
1680
Christopher Tate242ba3e92017-04-14 15:07:06 -07001681 private ComponentName startServiceCommon(Intent service, boolean requireForeground,
1682 UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 try {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001684 validateServiceIntent(service);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001685 service.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001686 ComponentName cn = ActivityManager.getService().startService(
Svet Ganov99b60432015-06-27 13:15:22 -07001687 mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
Christopher Tate242ba3e92017-04-14 15:07:06 -07001688 getContentResolver()), requireForeground,
Christopher Tate79047c62017-03-21 11:37:06 -07001689 getOpPackageName(), user.getIdentifier());
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001690 if (cn != null) {
1691 if (cn.getPackageName().equals("!")) {
1692 throw new SecurityException(
1693 "Not allowed to start service " + service
1694 + " without permission " + cn.getClassName());
1695 } else if (cn.getPackageName().equals("!!")) {
1696 throw new SecurityException(
1697 "Unable to start service " + service
1698 + ": " + cn.getClassName());
Dianne Hackborn85e35642017-01-12 15:10:57 -08001699 } else if (cn.getPackageName().equals("?")) {
1700 throw new IllegalStateException(
1701 "Not allowed to start service " + service + ": " + cn.getClassName());
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 }
1704 return cn;
1705 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001706 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709
1710 @Override
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001711 public boolean stopServiceAsUser(Intent service, UserHandle user) {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001712 return stopServiceCommon(service, user);
1713 }
1714
1715 private boolean stopServiceCommon(Intent service, UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 try {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001717 validateServiceIntent(service);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001718 service.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001719 int res = ActivityManager.getService().stopService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 mMainThread.getApplicationThread(), service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001721 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (res < 0) {
1723 throw new SecurityException(
1724 "Not allowed to stop service " + service);
1725 }
1726 return res != 0;
1727 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001728 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730 }
1731
1732 @Override
Bo Liu58a57662019-03-06 20:21:45 +00001733 public boolean bindService(Intent service, ServiceConnection conn, int flags) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001734 warnIfCallingFromSystemProcess();
Bo Liu58a57662019-03-06 20:21:45 +00001735 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
1736 getUser());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001737 }
1738
1739 @Override
Bo Liu58a57662019-03-06 20:21:45 +00001740 public boolean bindService(
1741 Intent service, int flags, Executor executor, ServiceConnection conn) {
1742 warnIfCallingFromSystemProcess();
1743 return bindServiceCommon(service, conn, flags, null, null, executor, getUser());
1744 }
1745
1746 @Override
1747 public boolean bindIsolatedService(Intent service, int flags, String instanceName,
1748 Executor executor, ServiceConnection conn) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001749 warnIfCallingFromSystemProcess();
1750 if (instanceName == null) {
1751 throw new NullPointerException("null instanceName");
1752 }
Bo Liu58a57662019-03-06 20:21:45 +00001753 return bindServiceCommon(service, conn, flags, instanceName, null, executor, getUser());
Amith Yamasani37ce3a82012-02-06 12:04:42 -08001754 }
1755
1756 /** @hide */
1757 @Override
Amith Yamasani27b89e62013-01-16 12:30:11 -08001758 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
1759 UserHandle user) {
Bo Liu58a57662019-03-06 20:21:45 +00001760 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null, user);
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001761 }
1762
Adrian Roos691546e2016-02-09 10:13:41 -08001763 /** @hide */
1764 @Override
1765 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
1766 Handler handler, UserHandle user) {
1767 if (handler == null) {
1768 throw new IllegalArgumentException("handler must not be null.");
1769 }
Bo Liu58a57662019-03-06 20:21:45 +00001770 return bindServiceCommon(service, conn, flags, null, handler, null, user);
Adrian Roos691546e2016-02-09 10:13:41 -08001771 }
1772
Tony Mak46aabe52016-11-14 12:53:06 +00001773 /** @hide */
1774 @Override
1775 public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler,
1776 int flags) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001777 return mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
Tony Mak46aabe52016-11-14 12:53:06 +00001778 }
1779
1780 /** @hide */
1781 @Override
1782 public IApplicationThread getIApplicationThread() {
1783 return mMainThread.getApplicationThread();
1784 }
1785
Tony Makbf9928d2016-12-22 11:02:45 +00001786 /** @hide */
1787 @Override
1788 public Handler getMainThreadHandler() {
1789 return mMainThread.getHandler();
1790 }
1791
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001792 private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
Bo Liu58a57662019-03-06 20:21:45 +00001793 String instanceName, Handler handler, Executor executor, UserHandle user) {
Tony Mak46aabe52016-11-14 12:53:06 +00001794 // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 IServiceConnection sd;
Christopher Tate79b33172012-06-18 14:54:21 -07001796 if (conn == null) {
1797 throw new IllegalArgumentException("connection is null");
1798 }
Bo Liu58a57662019-03-06 20:21:45 +00001799 if (handler != null && executor != null) {
1800 throw new IllegalArgumentException("Handler and Executor both supplied");
1801 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001802 if (mPackageInfo != null) {
Bo Liu58a57662019-03-06 20:21:45 +00001803 if (executor != null) {
1804 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
1805 } else {
1806 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
1807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 } else {
1809 throw new RuntimeException("Not supported in system context");
1810 }
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001811 validateServiceIntent(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001813 IBinder token = getActivityToken();
Todd Kennedy233a0b12018-01-29 20:30:24 +00001814 if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
1815 && mPackageInfo.getApplicationInfo().targetSdkVersion
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001816 < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1817 flags |= BIND_WAIVE_PRIORITY;
1818 }
Jeff Sharkey344744b2016-01-28 19:03:30 -07001819 service.prepareToLeaveProcess(this);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001820 int res = ActivityManager.getService().bindIsolatedService(
Svet Ganov99b60432015-06-27 13:15:22 -07001821 mMainThread.getApplicationThread(), getActivityToken(), service,
1822 service.resolveTypeIfNeeded(getContentResolver()),
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001823 sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 if (res < 0) {
1825 throw new SecurityException(
1826 "Not allowed to bind to service " + service);
1827 }
1828 return res != 0;
1829 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001830 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 }
1833
1834 @Override
Dianne Hackborna631d562018-11-20 15:58:15 -08001835 public void updateServiceGroup(@NonNull ServiceConnection conn, int group, int importance) {
1836 if (conn == null) {
1837 throw new IllegalArgumentException("connection is null");
1838 }
1839 if (mPackageInfo != null) {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001840 IServiceConnection sd = mPackageInfo.lookupServiceDispatcher(conn, getOuterContext());
1841 if (sd == null) {
1842 throw new IllegalArgumentException("ServiceConnection not currently bound: "
1843 + conn);
1844 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001845 try {
1846 ActivityManager.getService().updateServiceGroup(sd, group, importance);
1847 } catch (RemoteException e) {
1848 throw e.rethrowFromSystemServer();
1849 }
1850 } else {
1851 throw new RuntimeException("Not supported in system context");
1852 }
1853 }
1854
1855 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 public void unbindService(ServiceConnection conn) {
Christopher Tate79b33172012-06-18 14:54:21 -07001857 if (conn == null) {
1858 throw new IllegalArgumentException("connection is null");
1859 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001860 if (mPackageInfo != null) {
1861 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 getOuterContext(), conn);
1863 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001864 ActivityManager.getService().unbindService(sd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001866 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868 } else {
1869 throw new RuntimeException("Not supported in system context");
1870 }
1871 }
1872
1873 @Override
1874 public boolean startInstrumentation(ComponentName className,
1875 String profileFile, Bundle arguments) {
1876 try {
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04001877 if (arguments != null) {
1878 arguments.setAllowFds(false);
1879 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001880 return ActivityManager.getService().startInstrumentation(
Narayan Kamath8dcfefd2014-05-15 18:12:59 +01001881 className, profileFile, 0, arguments, null, null, getUserId(),
1882 null /* ABI override */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001884 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
1887
1888 @Override
1889 public Object getSystemService(String name) {
Andrii Kulian4a316972020-01-21 21:41:38 -08001890 if (isUiComponent(name) && !isUiContext()) {
1891 Log.w(TAG, name + " should be accessed from Activity or other visual Context");
1892 }
Jeff Brown6e539312015-02-24 18:53:21 -08001893 return SystemServiceRegistry.getSystemService(this, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
Jeff Brown6e539312015-02-24 18:53:21 -08001896 @Override
1897 public String getSystemServiceName(Class<?> serviceClass) {
1898 return SystemServiceRegistry.getSystemServiceName(serviceClass);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001899 }
1900
Andrii Kulian4a316972020-01-21 21:41:38 -08001901 boolean isUiContext() {
1902 return mIsSystemOrSystemUiContext || mIsUiContext;
1903 }
1904
1905 private static boolean isUiComponent(String name) {
1906 return WINDOW_SERVICE.equals(name) || LAYOUT_INFLATER_SERVICE.equals(name)
1907 || WALLPAPER_SERVICE.equals(name);
1908 }
1909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 @Override
1911 public int checkPermission(String permission, int pid, int uid) {
1912 if (permission == null) {
1913 throw new IllegalArgumentException("permission is null");
1914 }
1915
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001916 final IActivityManager am = ActivityManager.getService();
Jeff Sharkeyd69b0832017-01-23 11:37:24 -07001917 if (am == null) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001918 // Well this is super awkward; we somehow don't have an active
Jeff Sharkeyd69b0832017-01-23 11:37:24 -07001919 // ActivityManager instance. If we're testing a root or system
1920 // UID, then they totally have whatever permission this is.
1921 final int appId = UserHandle.getAppId(uid);
1922 if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
1923 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
1924 return PackageManager.PERMISSION_GRANTED;
1925 }
Erik Wolsheimere21576f2018-03-29 16:21:41 -07001926 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold "
1927 + permission);
1928 return PackageManager.PERMISSION_DENIED;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001929 }
1930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 try {
Tim Murrayd06c6d292019-05-07 06:53:55 +00001932 return am.checkPermission(permission, pid, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001934 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
1936 }
1937
Dianne Hackbornff170242014-11-19 10:59:01 -08001938 /** @hide */
1939 @Override
1940 public int checkPermission(String permission, int pid, int uid, IBinder callerToken) {
1941 if (permission == null) {
1942 throw new IllegalArgumentException("permission is null");
1943 }
1944
1945 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001946 return ActivityManager.getService().checkPermissionWithToken(
Dianne Hackbornff170242014-11-19 10:59:01 -08001947 permission, pid, uid, callerToken);
1948 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001949 throw e.rethrowFromSystemServer();
Dianne Hackbornff170242014-11-19 10:59:01 -08001950 }
1951 }
1952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 @Override
1954 public int checkCallingPermission(String permission) {
1955 if (permission == null) {
1956 throw new IllegalArgumentException("permission is null");
1957 }
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 int pid = Binder.getCallingPid();
1960 if (pid != Process.myPid()) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001961 return checkPermission(permission, pid, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963 return PackageManager.PERMISSION_DENIED;
1964 }
1965
1966 @Override
1967 public int checkCallingOrSelfPermission(String permission) {
1968 if (permission == null) {
1969 throw new IllegalArgumentException("permission is null");
1970 }
1971
1972 return checkPermission(permission, Binder.getCallingPid(),
1973 Binder.getCallingUid());
1974 }
1975
Svetoslavc6d1c342015-02-26 14:44:43 -08001976 @Override
1977 public int checkSelfPermission(String permission) {
1978 if (permission == null) {
1979 throw new IllegalArgumentException("permission is null");
1980 }
1981
1982 return checkPermission(permission, Process.myPid(), Process.myUid());
1983 }
1984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 private void enforce(
1986 String permission, int resultOfCheck,
1987 boolean selfToo, int uid, String message) {
1988 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1989 throw new SecurityException(
1990 (message != null ? (message + ": ") : "") +
1991 (selfToo
1992 ? "Neither user " + uid + " nor current process has "
Tim Murrayd06c6d292019-05-07 06:53:55 +00001993 : "uid " + uid + " does not have ") +
1994 permission +
1995 ".");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997 }
1998
Jeff Brown6e539312015-02-24 18:53:21 -08001999 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 public void enforcePermission(
2001 String permission, int pid, int uid, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002002 enforce(permission,
2003 checkPermission(permission, pid, uid),
2004 false,
2005 uid,
2006 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008
Jeff Brown6e539312015-02-24 18:53:21 -08002009 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 public void enforceCallingPermission(String permission, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002011 enforce(permission,
2012 checkCallingPermission(permission),
2013 false,
2014 Binder.getCallingUid(),
2015 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 }
2017
Jeff Brown6e539312015-02-24 18:53:21 -08002018 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 public void enforceCallingOrSelfPermission(
2020 String permission, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002021 enforce(permission,
2022 checkCallingOrSelfPermission(permission),
2023 true,
2024 Binder.getCallingUid(),
2025 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027
2028 @Override
2029 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
2030 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002031 ActivityManager.getService().grantUriPermission(
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002032 mMainThread.getApplicationThread(), toPackage,
2033 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002035 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
2037 }
2038
2039 @Override
2040 public void revokeUriPermission(Uri uri, int modeFlags) {
2041 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002042 ActivityManager.getService().revokeUriPermission(
Dianne Hackborna47223f2017-03-30 13:49:13 -07002043 mMainThread.getApplicationThread(), null,
2044 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
2045 } catch (RemoteException e) {
2046 throw e.rethrowFromSystemServer();
2047 }
2048 }
2049
2050 @Override
2051 public void revokeUriPermission(String targetPackage, Uri uri, int modeFlags) {
2052 try {
2053 ActivityManager.getService().revokeUriPermission(
2054 mMainThread.getApplicationThread(), targetPackage,
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002055 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002057 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
2059 }
2060
2061 @Override
2062 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002064 return ActivityManager.getService().checkUriPermission(
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002065 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
Dianne Hackbornff170242014-11-19 10:59:01 -08002066 resolveUserId(uri), null);
2067 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002068 throw e.rethrowFromSystemServer();
Dianne Hackbornff170242014-11-19 10:59:01 -08002069 }
2070 }
2071
2072 /** @hide */
2073 @Override
2074 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) {
2075 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002076 return ActivityManager.getService().checkUriPermission(
Dianne Hackbornff170242014-11-19 10:59:01 -08002077 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
2078 resolveUserId(uri), callerToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002080 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
2083
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002084 private int resolveUserId(Uri uri) {
2085 return ContentProvider.getUserIdFromUri(uri, getUserId());
2086 }
2087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 @Override
2089 public int checkCallingUriPermission(Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 int pid = Binder.getCallingPid();
2091 if (pid != Process.myPid()) {
2092 return checkUriPermission(uri, pid,
2093 Binder.getCallingUid(), modeFlags);
2094 }
2095 return PackageManager.PERMISSION_DENIED;
2096 }
2097
2098 @Override
2099 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
2100 return checkUriPermission(uri, Binder.getCallingPid(),
2101 Binder.getCallingUid(), modeFlags);
2102 }
2103
2104 @Override
2105 public int checkUriPermission(Uri uri, String readPermission,
2106 String writePermission, int pid, int uid, int modeFlags) {
Mitsuru Oshima569076c2009-07-02 20:06:08 -07002107 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
2109 + readPermission + " writePermission=" + writePermission
2110 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
2111 }
2112 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2113 if (readPermission == null
2114 || checkPermission(readPermission, pid, uid)
2115 == PackageManager.PERMISSION_GRANTED) {
2116 return PackageManager.PERMISSION_GRANTED;
2117 }
2118 }
2119 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2120 if (writePermission == null
2121 || checkPermission(writePermission, pid, uid)
2122 == PackageManager.PERMISSION_GRANTED) {
2123 return PackageManager.PERMISSION_GRANTED;
2124 }
2125 }
2126 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
2127 : PackageManager.PERMISSION_DENIED;
2128 }
2129
2130 private String uriModeFlagToString(int uriModeFlags) {
Jeff Sharkey846318a2014-04-04 12:12:41 -07002131 StringBuilder builder = new StringBuilder();
2132 if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2133 builder.append("read and ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
Jeff Sharkey846318a2014-04-04 12:12:41 -07002135 if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2136 builder.append("write and ");
2137 }
2138 if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
2139 builder.append("persistable and ");
2140 }
2141 if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
2142 builder.append("prefix and ");
2143 }
2144
2145 if (builder.length() > 5) {
2146 builder.setLength(builder.length() - 5);
2147 return builder.toString();
2148 } else {
2149 throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags);
2150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
2152
2153 private void enforceForUri(
2154 int modeFlags, int resultOfCheck, boolean selfToo,
2155 int uid, Uri uri, String message) {
2156 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
2157 throw new SecurityException(
2158 (message != null ? (message + ": ") : "") +
2159 (selfToo
2160 ? "Neither user " + uid + " nor current process has "
2161 : "User " + uid + " does not have ") +
2162 uriModeFlagToString(modeFlags) +
2163 " permission on " +
2164 uri +
2165 ".");
2166 }
2167 }
2168
Jeff Brown6e539312015-02-24 18:53:21 -08002169 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 public void enforceUriPermission(
2171 Uri uri, int pid, int uid, int modeFlags, String message) {
2172 enforceForUri(
2173 modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
2174 false, uid, uri, message);
2175 }
2176
Jeff Brown6e539312015-02-24 18:53:21 -08002177 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 public void enforceCallingUriPermission(
2179 Uri uri, int modeFlags, String message) {
2180 enforceForUri(
2181 modeFlags, checkCallingUriPermission(uri, modeFlags),
Amith Yamasani742a6712011-05-04 14:49:28 -07002182 false,
2183 Binder.getCallingUid(), uri, message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185
Jeff Brown6e539312015-02-24 18:53:21 -08002186 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 public void enforceCallingOrSelfUriPermission(
2188 Uri uri, int modeFlags, String message) {
2189 enforceForUri(
2190 modeFlags,
2191 checkCallingOrSelfUriPermission(uri, modeFlags), true,
2192 Binder.getCallingUid(), uri, message);
2193 }
2194
Jeff Brown6e539312015-02-24 18:53:21 -08002195 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 public void enforceUriPermission(
2197 Uri uri, String readPermission, String writePermission,
2198 int pid, int uid, int modeFlags, String message) {
2199 enforceForUri(modeFlags,
2200 checkUriPermission(
2201 uri, readPermission, writePermission, pid, uid,
2202 modeFlags),
2203 false,
2204 uid,
2205 uri,
2206 message);
2207 }
2208
Tom O'Neill365632e2013-09-09 09:34:58 -07002209 /**
2210 * Logs a warning if the system process directly called a method such as
2211 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
2212 * The "AsUser" variants allow us to properly enforce the user's restrictions.
2213 */
Amith Yamasanicd757062012-10-19 18:23:52 -07002214 private void warnIfCallingFromSystemProcess() {
2215 if (Process.myUid() == Process.SYSTEM_UID) {
2216 Slog.w(TAG, "Calling a method in the system process without a qualified user: "
Dianne Hackborn40e9f292012-11-27 19:12:23 -08002217 + Debug.getCallers(5));
Amith Yamasanicd757062012-10-19 18:23:52 -07002218 }
2219 }
2220
Todd Kennedy233a0b12018-01-29 20:30:24 +00002221 private static Resources createResources(IBinder activityToken, LoadedApk pi, String splitName,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002222 int displayId, Configuration overrideConfig, CompatibilityInfo compatInfo,
2223 List<ResourcesLoader> resourcesLoader) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002224 final String[] splitResDirs;
2225 final ClassLoader classLoader;
2226 try {
2227 splitResDirs = pi.getSplitPaths(splitName);
2228 classLoader = pi.getSplitClassLoader(splitName);
2229 } catch (NameNotFoundException e) {
2230 throw new RuntimeException(e);
2231 }
2232 return ResourcesManager.getInstance().getResources(activityToken,
2233 pi.getResDir(),
2234 splitResDirs,
Winson710e3ec2019-02-25 13:38:20 -08002235 pi.getOverlayDirs(),
Todd Kennedy233a0b12018-01-29 20:30:24 +00002236 pi.getApplicationInfo().sharedLibraryFiles,
2237 displayId,
2238 overrideConfig,
2239 compatInfo,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002240 classLoader,
2241 resourcesLoader);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002242 }
2243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 @Override
Svetoslav976e8bd2014-07-16 15:12:03 -07002245 public Context createApplicationContext(ApplicationInfo application, int flags)
2246 throws NameNotFoundException {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002247 LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(),
Svetoslav976e8bd2014-07-16 15:12:03 -07002248 flags | CONTEXT_REGISTER_PACKAGE);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002249 if (pi != null) {
Andrii Kulian4a316972020-01-21 21:41:38 -08002250 ContextImpl c = new ContextImpl(this, mMainThread, pi, null, null, mToken,
Makoto Onuki4becc352019-01-30 13:30:41 -08002251 new UserHandle(UserHandle.getUserId(application.uid)), flags, null, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002252
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002253 final int displayId = getDisplayId();
Winson710e3ec2019-02-25 13:38:20 -08002254
Andrii Kulian4a316972020-01-21 21:41:38 -08002255 c.setResources(createResources(mToken, pi, null, displayId, null,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002256 getDisplayAdjustments(displayId).getCompatibilityInfo(), null));
Svetoslav976e8bd2014-07-16 15:12:03 -07002257 if (c.mResources != null) {
2258 return c;
2259 }
2260 }
2261
2262 throw new PackageManager.NameNotFoundException(
2263 "Application package " + application.packageName + " not found");
2264 }
2265
2266 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 public Context createPackageContext(String packageName, int flags)
Jeff Sharkey6d515712012-09-20 16:06:08 -07002268 throws NameNotFoundException {
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002269 return createPackageContextAsUser(packageName, flags, mUser);
Jeff Sharkey6d515712012-09-20 16:06:08 -07002270 }
2271
2272 @Override
2273 public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
2274 throws NameNotFoundException {
Kenny Guyc2a40602014-09-08 18:51:15 +00002275 if (packageName.equals("system") || packageName.equals("android")) {
Adam Lesinski8fa71072016-11-18 18:13:55 -08002276 // The system resources are loaded in every application, so we can safely copy
2277 // the context without reloading Resources.
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002278 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, null,
Andrii Kulian4a316972020-01-21 21:41:38 -08002279 mToken, user, flags, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281
Todd Kennedy233a0b12018-01-29 20:30:24 +00002282 LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002283 flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
Todd Kennedy233a0b12018-01-29 20:30:24 +00002284 if (pi != null) {
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002285 ContextImpl c = new ContextImpl(this, mMainThread, pi, mFeatureId, null,
Andrii Kulian4a316972020-01-21 21:41:38 -08002286 mToken, user, flags, null, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002287
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002288 final int displayId = getDisplayId();
Adam Lesinski8fa71072016-11-18 18:13:55 -08002289
Andrii Kulian4a316972020-01-21 21:41:38 -08002290 c.setResources(createResources(mToken, pi, null, displayId, null,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002291 getDisplayAdjustments(displayId).getCompatibilityInfo(), null));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 if (c.mResources != null) {
2293 return c;
2294 }
2295 }
2296
2297 // Should be a better exception.
2298 throw new PackageManager.NameNotFoundException(
Jeff Browndefd4a62014-03-10 21:24:37 -07002299 "Application package " + packageName + " not found");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002300 }
2301
Romain Guy870e09f2009-07-06 16:35:25 -07002302 @Override
Makoto Onukie5449f02019-10-11 20:19:58 -07002303 public Context createContextAsUser(UserHandle user, @CreatePackageOptions int flags) {
Makoto Onukib8440012019-10-09 15:33:11 -07002304 try {
Makoto Onukie5449f02019-10-11 20:19:58 -07002305 return createPackageContextAsUser(getPackageName(), flags, user);
Makoto Onukib8440012019-10-09 15:33:11 -07002306 } catch (NameNotFoundException e) {
2307 throw new IllegalStateException("Own package not found: package=" + getPackageName());
2308 }
2309 }
2310
2311 @Override
Adam Lesinski4e862812016-11-21 16:02:24 -08002312 public Context createContextForSplit(String splitName) throws NameNotFoundException {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002313 if (!mPackageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
Adam Lesinski4e862812016-11-21 16:02:24 -08002314 // All Splits are always loaded.
2315 return this;
2316 }
2317
Todd Kennedy233a0b12018-01-29 20:30:24 +00002318 final ClassLoader classLoader = mPackageInfo.getSplitClassLoader(splitName);
2319 final String[] paths = mPackageInfo.getSplitPaths(splitName);
Adam Lesinski4e862812016-11-21 16:02:24 -08002320
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002321 final ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo,
Andrii Kulian4a316972020-01-21 21:41:38 -08002322 mFeatureId, splitName, mToken, mUser, mFlags, classLoader, null);
Adam Lesinski4e862812016-11-21 16:02:24 -08002323
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002324 final int displayId = getDisplayId();
Adam Lesinski4e862812016-11-21 16:02:24 -08002325
Todd Kennedy233a0b12018-01-29 20:30:24 +00002326 context.setResources(ResourcesManager.getInstance().getResources(
Andrii Kulian4a316972020-01-21 21:41:38 -08002327 mToken,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002328 mPackageInfo.getResDir(),
2329 paths,
2330 mPackageInfo.getOverlayDirs(),
2331 mPackageInfo.getApplicationInfo().sharedLibraryFiles,
2332 displayId,
2333 null,
2334 mPackageInfo.getCompatibilityInfo(),
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002335 classLoader,
2336 mResources.getLoaders()));
Adam Lesinski4e862812016-11-21 16:02:24 -08002337 return context;
2338 }
2339
2340 @Override
Dianne Hackborn756220b2012-08-14 16:45:30 -07002341 public Context createConfigurationContext(Configuration overrideConfiguration) {
Jeff Browna492c3a2012-08-23 19:48:44 -07002342 if (overrideConfiguration == null) {
2343 throw new IllegalArgumentException("overrideConfiguration must not be null");
2344 }
2345
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002346 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
Andrii Kulian4a316972020-01-21 21:41:38 -08002347 mSplitName, mToken, mUser, mFlags, mClassLoader, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002348
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002349 final int displayId = getDisplayId();
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002350
Andrii Kulian4a316972020-01-21 21:41:38 -08002351 context.setResources(createResources(mToken, mPackageInfo, mSplitName, displayId,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002352 overrideConfiguration, getDisplayAdjustments(displayId).getCompatibilityInfo(),
2353 mResources.getLoaders()));
Adam Lesinski8fa71072016-11-18 18:13:55 -08002354 return context;
Dianne Hackborn756220b2012-08-14 16:45:30 -07002355 }
2356
2357 @Override
Jeff Browna492c3a2012-08-23 19:48:44 -07002358 public Context createDisplayContext(Display display) {
2359 if (display == null) {
2360 throw new IllegalArgumentException("display must not be null");
2361 }
2362
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002363 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
Andrii Kulian4a316972020-01-21 21:41:38 -08002364 mSplitName, mToken, mUser, mFlags, mClassLoader, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002365
2366 final int displayId = display.getDisplayId();
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002367
Andrii Kulian4a316972020-01-21 21:41:38 -08002368 context.setResources(createResources(mToken, mPackageInfo, mSplitName, displayId,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002369 null, getDisplayAdjustments(displayId).getCompatibilityInfo(),
2370 mResources.getLoaders()));
Adam Lesinski8fa71072016-11-18 18:13:55 -08002371 context.mDisplay = display;
2372 return context;
Jeff Browna492c3a2012-08-23 19:48:44 -07002373 }
2374
Jeff Browna492c3a2012-08-23 19:48:44 -07002375 @Override
Andrii Kulian4a316972020-01-21 21:41:38 -08002376 public @NonNull WindowContext createWindowContext(int type) {
2377 if (getDisplay() == null) {
2378 throw new UnsupportedOperationException("WindowContext can only be created from "
2379 + "other visual contexts, such as Activity or one created with "
2380 + "Context#createDisplayContext(Display)");
2381 }
2382 return new WindowContext(this, null /* token */, type);
2383 }
2384
2385 ContextImpl createBaseWindowContext(IBinder token) {
2386 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
2387 mSplitName, token, mUser, mFlags, mClassLoader, null);
2388 context.mIsUiContext = true;
2389 return context;
2390 }
2391
2392 @Override
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002393 public @NonNull Context createFeatureContext(@Nullable String featureId) {
2394 return new ContextImpl(this, mMainThread, mPackageInfo, featureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002395 mToken, mUser, mFlags, mClassLoader, null);
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002396 }
2397
2398 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002399 public Context createDeviceProtectedStorageContext() {
2400 final int flags = (mFlags & ~Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE)
2401 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002402 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002403 mToken, mUser, flags, mClassLoader, null);
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002404 }
2405
2406 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002407 public Context createCredentialProtectedStorageContext() {
2408 final int flags = (mFlags & ~Context.CONTEXT_DEVICE_PROTECTED_STORAGE)
2409 | Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002410 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002411 mToken, mUser, flags, mClassLoader, null);
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002412 }
2413
2414 @Override
Romain Guy870e09f2009-07-06 16:35:25 -07002415 public boolean isRestricted() {
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002416 return (mFlags & Context.CONTEXT_RESTRICTED) != 0;
2417 }
2418
2419 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002420 public boolean isDeviceProtectedStorage() {
2421 return (mFlags & Context.CONTEXT_DEVICE_PROTECTED_STORAGE) != 0;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002422 }
2423
2424 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002425 public boolean isCredentialProtectedStorage() {
2426 return (mFlags & Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE) != 0;
Romain Guy870e09f2009-07-06 16:35:25 -07002427 }
2428
Jeff Brown98365d72012-08-19 20:30:52 -07002429 @Override
Seigo Nonaka6d6cd682017-06-22 08:22:18 -07002430 public boolean canLoadUnsafeResources() {
2431 if (getPackageName().equals(getOpPackageName())) {
2432 return true;
2433 }
2434 return (mFlags & Context.CONTEXT_IGNORE_SECURITY) != 0;
2435 }
2436
2437 @Override
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002438 public Display getDisplay() {
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002439 if (mDisplay == null) {
2440 return mResourcesManager.getAdjustedDisplay(Display.DEFAULT_DISPLAY,
Bryce Lee609bf652017-02-09 16:50:13 -08002441 mResources);
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002442 }
2443
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002444 return mDisplay;
2445 }
2446
2447 @Override
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002448 public int getDisplayId() {
Andrii Kulian4a316972020-01-21 21:41:38 -08002449 final Display display = getDisplay();
2450 return display != null ? display.getDisplayId() : Display.DEFAULT_DISPLAY;
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002451 }
2452
2453 @Override
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002454 public void updateDisplay(int displayId) {
Bryce Lee609bf652017-02-09 16:50:13 -08002455 mDisplay = mResourcesManager.getAdjustedDisplay(displayId, mResources);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002456 }
2457
2458 @Override
Craig Mautner48d0d182013-06-11 07:53:06 -07002459 public DisplayAdjustments getDisplayAdjustments(int displayId) {
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002460 return mResources.getDisplayAdjustments();
Jeff Brown98365d72012-08-19 20:30:52 -07002461 }
2462
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -07002463 @Override
2464 public File getDataDir() {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002465 if (mPackageInfo != null) {
Jeff Sharkey35871f22016-01-29 17:13:29 -07002466 File res = null;
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002467 if (isCredentialProtectedStorage()) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002468 res = mPackageInfo.getCredentialProtectedDataDirFile();
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002469 } else if (isDeviceProtectedStorage()) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002470 res = mPackageInfo.getDeviceProtectedDataDirFile();
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002471 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002472 res = mPackageInfo.getDataDirFile();
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002473 }
Jeff Sharkey35871f22016-01-29 17:13:29 -07002474
2475 if (res != null) {
Jeff Sharkey21f50722016-04-27 12:38:02 -06002476 if (!res.exists() && android.os.Process.myUid() == android.os.Process.SYSTEM_UID) {
Jeff Sharkey24492ae2016-04-25 13:20:25 -06002477 Log.wtf(TAG, "Data directory doesn't exist for package " + getPackageName(),
2478 new Throwable());
2479 }
Jeff Sharkey35871f22016-01-29 17:13:29 -07002480 return res;
2481 } else {
2482 throw new RuntimeException(
2483 "No data directory found for package " + getPackageName());
2484 }
2485 } else {
2486 throw new RuntimeException(
2487 "No package details found for package " + getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 }
2490
2491 @Override
2492 public File getDir(String name, int mode) {
Jeff Sharkey634dc422016-01-30 17:44:15 -07002493 checkMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 name = "app_" + name;
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -07002495 File file = makeFilename(getDataDir(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 if (!file.exists()) {
2497 file.mkdir();
2498 setFilePermissionsFromMode(file.getPath(), mode,
2499 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
2500 }
2501 return file;
2502 }
2503
Jeff Sharkeyded653b2012-09-27 19:09:24 -07002504 /** {@hide} */
Jeff Brown6e539312015-02-24 18:53:21 -08002505 @Override
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002506 public UserHandle getUser() {
2507 return mUser;
2508 }
2509
2510 /** {@hide} */
2511 @Override
Jeff Sharkeyded653b2012-09-27 19:09:24 -07002512 public int getUserId() {
2513 return mUser.getIdentifier();
2514 }
2515
Felipe Lemebb567ae2017-10-04 09:56:21 -07002516 /** @hide */
2517 @Override
2518 public AutofillClient getAutofillClient() {
2519 return mAutofillClient;
2520 }
2521
2522 /** @hide */
2523 @Override
2524 public void setAutofillClient(AutofillClient client) {
2525 mAutofillClient = client;
2526 }
2527
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002528 /** @hide */
2529 @Override
Felipe Lemea4f39cd2019-02-19 15:08:59 -08002530 public AutofillOptions getAutofillOptions() {
2531 return mAutofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002532 }
2533
2534 /** @hide */
2535 @Override
Felipe Lemea4f39cd2019-02-19 15:08:59 -08002536 public void setAutofillOptions(AutofillOptions options) {
2537 mAutofillOptions = options;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002538 }
2539
Felipe Lemeecb08be2018-11-27 15:48:47 -08002540 /** @hide */
2541 @Override
Felipe Leme326f15a2019-02-19 09:42:24 -08002542 public ContentCaptureOptions getContentCaptureOptions() {
2543 return mContentCaptureOptions;
Felipe Lemeecb08be2018-11-27 15:48:47 -08002544 }
2545
2546 /** @hide */
2547 @Override
Felipe Leme326f15a2019-02-19 09:42:24 -08002548 public void setContentCaptureOptions(ContentCaptureOptions options) {
2549 mContentCaptureOptions = options;
Felipe Lemeecb08be2018-11-27 15:48:47 -08002550 }
2551
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002552 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002553 static ContextImpl createSystemContext(ActivityThread mainThread) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002554 LoadedApk packageInfo = new LoadedApk(mainThread);
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002555 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
2556 0, null, null);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002557 context.setResources(packageInfo.getResources());
Jeff Browndefd4a62014-03-10 21:24:37 -07002558 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
Adam Lesinski7f3f4992016-03-30 10:32:15 -07002559 context.mResourcesManager.getDisplayMetrics());
Andrii Kulian4a316972020-01-21 21:41:38 -08002560 context.mIsSystemOrSystemUiContext = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 return context;
2562 }
2563
Adam Lesinskia82b6262017-03-21 16:56:17 -07002564 /**
2565 * System Context to be used for UI. This Context has resources that can be themed.
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002566 * Make sure that the created system UI context shares the same LoadedApk as the system context.
lumark0b05f9e2018-11-26 15:09:06 +08002567 * @param systemContext The system context which created by
2568 * {@link #createSystemContext(ActivityThread)}.
2569 * @param displayId The ID of the display where the UI is shown.
Adam Lesinskia82b6262017-03-21 16:56:17 -07002570 */
lumark0b05f9e2018-11-26 15:09:06 +08002571 static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002572 final LoadedApk packageInfo = systemContext.mPackageInfo;
2573 ContextImpl context = new ContextImpl(null, systemContext.mMainThread, packageInfo, null,
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002574 null, null, null, 0, null, null);
lumark0b05f9e2018-11-26 15:09:06 +08002575 context.setResources(createResources(null, packageInfo, null, displayId, null,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002576 packageInfo.getCompatibilityInfo(), null));
lumark0b05f9e2018-11-26 15:09:06 +08002577 context.updateDisplay(displayId);
Andrii Kulian4a316972020-01-21 21:41:38 -08002578 context.mIsSystemOrSystemUiContext = true;
Adam Lesinskia82b6262017-03-21 16:56:17 -07002579 return context;
2580 }
2581
lumark0b05f9e2018-11-26 15:09:06 +08002582 /**
2583 * The overloaded method of {@link #createSystemUiContext(ContextImpl, int)}.
2584 * Uses {@Code Display.DEFAULT_DISPLAY} as the target display.
2585 */
2586 static ContextImpl createSystemUiContext(ContextImpl systemContext) {
2587 return createSystemUiContext(systemContext, Display.DEFAULT_DISPLAY);
2588 }
2589
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002590 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002591 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
Makoto Onuki4becc352019-01-30 13:30:41 -08002592 return createAppContext(mainThread, packageInfo, null);
2593 }
2594
2595 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
2596 String opPackageName) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002597 if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002598 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
2599 0, null, opPackageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002600 context.setResources(packageInfo.getResources());
Adam Lesinski8fa71072016-11-18 18:13:55 -08002601 return context;
Jeff Browndefd4a62014-03-10 21:24:37 -07002602 }
2603
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002604 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -07002605 static ContextImpl createActivityContext(ActivityThread mainThread,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002606 LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
Adam Lesinski082614c2016-03-04 14:33:47 -08002607 Configuration overrideConfiguration) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002608 if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
Adam Lesinski8fa71072016-11-18 18:13:55 -08002609
Todd Kennedy233a0b12018-01-29 20:30:24 +00002610 String[] splitDirs = packageInfo.getSplitResDirs();
2611 ClassLoader classLoader = packageInfo.getClassLoader();
Adam Lesinski4e862812016-11-21 16:02:24 -08002612
Todd Kennedy233a0b12018-01-29 20:30:24 +00002613 if (packageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
Adam Lesinski4e862812016-11-21 16:02:24 -08002614 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "SplitDependencies");
2615 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002616 classLoader = packageInfo.getSplitClassLoader(activityInfo.splitName);
2617 splitDirs = packageInfo.getSplitPaths(activityInfo.splitName);
Adam Lesinski4e862812016-11-21 16:02:24 -08002618 } catch (NameNotFoundException e) {
2619 // Nothing above us can handle a NameNotFoundException, better crash.
2620 throw new RuntimeException(e);
2621 } finally {
2622 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2623 }
2624 }
2625
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002626 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null,
2627 activityInfo.splitName, activityToken, null, 0, classLoader, null);
Andrii Kulian4a316972020-01-21 21:41:38 -08002628 context.mIsUiContext = true;
Adam Lesinski8fa71072016-11-18 18:13:55 -08002629
2630 // Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY.
2631 displayId = (displayId != Display.INVALID_DISPLAY) ? displayId : Display.DEFAULT_DISPLAY;
2632
2633 final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002634 ? packageInfo.getCompatibilityInfo()
Adam Lesinski8fa71072016-11-18 18:13:55 -08002635 : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
2636
Adam Lesinskic9701942016-11-28 19:44:19 -08002637 final ResourcesManager resourcesManager = ResourcesManager.getInstance();
2638
2639 // Create the base resources for which all configuration contexts for this Activity
2640 // will be rebased upon.
Jason Monkbd983642017-02-24 16:57:40 -05002641 context.setResources(resourcesManager.createBaseActivityResources(activityToken,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002642 packageInfo.getResDir(),
Adam Lesinski4e862812016-11-21 16:02:24 -08002643 splitDirs,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002644 packageInfo.getOverlayDirs(),
2645 packageInfo.getApplicationInfo().sharedLibraryFiles,
Adam Lesinskic9701942016-11-28 19:44:19 -08002646 displayId,
2647 overrideConfiguration,
2648 compatInfo,
Ryan Mitchell4579c0a2020-01-08 16:29:11 -08002649 classLoader,
2650 packageInfo.getApplication().getResources().getLoaders()));
Adam Lesinskic9701942016-11-28 19:44:19 -08002651 context.mDisplay = resourcesManager.getAdjustedDisplay(displayId,
Bryce Lee609bf652017-02-09 16:50:13 -08002652 context.getResources());
Adam Lesinski8fa71072016-11-18 18:13:55 -08002653 return context;
Jeff Browndefd4a62014-03-10 21:24:37 -07002654 }
2655
Adam Lesinski1665d0f2017-03-10 14:46:57 -08002656 private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002657 @NonNull LoadedApk packageInfo, @Nullable String featureId,
2658 @Nullable String splitName, @Nullable IBinder activityToken, @Nullable UserHandle user,
2659 int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 mOuterContext = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002662 // If creator didn't specify which storage to use, use the default
2663 // location for application.
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002664 if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
2665 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002666 final File dataDir = packageInfo.getDataDirFile();
2667 if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) {
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002668 flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002669 } else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) {
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002670 flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002671 }
2672 }
2673
Jeff Browndefd4a62014-03-10 21:24:37 -07002674 mMainThread = mainThread;
Andrii Kulian4a316972020-01-21 21:41:38 -08002675 mToken = activityToken;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002676 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677
Jeff Browndefd4a62014-03-10 21:24:37 -07002678 if (user == null) {
2679 user = Process.myUserHandle();
2680 }
2681 mUser = user;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002682
Todd Kennedy233a0b12018-01-29 20:30:24 +00002683 mPackageInfo = packageInfo;
Adam Lesinski1665d0f2017-03-10 14:46:57 -08002684 mSplitName = splitName;
Adam Lesinski4e862812016-11-21 16:02:24 -08002685 mClassLoader = classLoader;
Jeff Browndefd4a62014-03-10 21:24:37 -07002686 mResourcesManager = ResourcesManager.getInstance();
Jeff Browndefd4a62014-03-10 21:24:37 -07002687
Makoto Onuki4becc352019-01-30 13:30:41 -08002688 String opPackageName;
2689
Jeff Browndefd4a62014-03-10 21:24:37 -07002690 if (container != null) {
2691 mBasePackageName = container.mBasePackageName;
Makoto Onuki4becc352019-01-30 13:30:41 -08002692 opPackageName = container.mOpPackageName;
Jason Monkbd983642017-02-24 16:57:40 -05002693 setResources(container.mResources);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002694 mDisplay = container.mDisplay;
Andrii Kulian4a316972020-01-21 21:41:38 -08002695 mIsSystemOrSystemUiContext = container.mIsSystemOrSystemUiContext;
Dianne Hackborn95d78532013-09-11 09:51:14 -07002696 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002697 mBasePackageName = packageInfo.mPackageName;
2698 ApplicationInfo ainfo = packageInfo.getApplicationInfo();
Dianne Hackborn95d78532013-09-11 09:51:14 -07002699 if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
2700 // Special case: system components allow themselves to be loaded in to other
2701 // processes. For purposes of app ops, we must then consider the context as
2702 // belonging to the package of this process, not the system itself, otherwise
2703 // the package+uid verifications in app ops will fail.
Makoto Onuki4becc352019-01-30 13:30:41 -08002704 opPackageName = ActivityThread.currentPackageName();
Dianne Hackborn95d78532013-09-11 09:51:14 -07002705 } else {
Makoto Onuki4becc352019-01-30 13:30:41 -08002706 opPackageName = mBasePackageName;
Dianne Hackborn95d78532013-09-11 09:51:14 -07002707 }
2708 }
Xin Guan2bcb97b2014-09-10 15:24:30 -05002709
Makoto Onuki4becc352019-01-30 13:30:41 -08002710 mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002711 mFeatureId = featureId;
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002712 mContentResolver = new ApplicationContentResolver(this, mainThread);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
2714
Jason Monkbd983642017-02-24 16:57:40 -05002715 void setResources(Resources r) {
Jason Monkbd60e5b2017-03-02 12:55:00 -05002716 if (r instanceof CompatResources) {
2717 ((CompatResources) r).setContext(this);
Jason Monkbd983642017-02-24 16:57:40 -05002718 }
Jason Monkbd60e5b2017-03-02 12:55:00 -05002719 mResources = r;
Jason Monkbd983642017-02-24 16:57:40 -05002720 }
2721
Narayan Kamath29564cd2014-08-07 10:57:40 +01002722 void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002723 mPackageInfo.installSystemApplicationInfo(info, classLoader);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002726 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 final void scheduleFinalCleanup(String who, String what) {
2728 mMainThread.scheduleContextCleanup(this, who, what);
2729 }
2730
2731 final void performFinalCleanup(String who, String what) {
2732 //Log.i(TAG, "Cleanup up context: " + this);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002733 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 }
2735
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002736 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 final Context getReceiverRestrictedContext() {
2738 if (mReceiverRestrictedContext != null) {
2739 return mReceiverRestrictedContext;
2740 }
2741 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
2742 }
2743
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002744 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002745 final void setOuterContext(Context context) {
2746 mOuterContext = context;
2747 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002748
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002749 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 final Context getOuterContext() {
2751 return mOuterContext;
2752 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002753
Tony Mak46aabe52016-11-14 12:53:06 +00002754 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002755 @UnsupportedAppUsage
Tony Mak46aabe52016-11-14 12:53:06 +00002756 public IBinder getActivityToken() {
Andrii Kulian4a316972020-01-21 21:41:38 -08002757 return mToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 }
2759
Jeff Sharkey634dc422016-01-30 17:44:15 -07002760 private void checkMode(int mode) {
2761 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
2762 if ((mode & MODE_WORLD_READABLE) != 0) {
2763 throw new SecurityException("MODE_WORLD_READABLE no longer supported");
2764 }
2765 if ((mode & MODE_WORLD_WRITEABLE) != 0) {
2766 throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported");
2767 }
2768 }
2769 }
2770
Jeff Brown6e539312015-02-24 18:53:21 -08002771 @SuppressWarnings("deprecation")
Brad Fitzpatrickd3da4402010-11-10 08:27:11 -08002772 static void setFilePermissionsFromMode(String name, int mode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 int extraPermissions) {
2774 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
2775 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
2776 |extraPermissions;
2777 if ((mode&MODE_WORLD_READABLE) != 0) {
2778 perms |= FileUtils.S_IROTH;
2779 }
2780 if ((mode&MODE_WORLD_WRITEABLE) != 0) {
2781 perms |= FileUtils.S_IWOTH;
2782 }
Mitsuru Oshima569076c2009-07-02 20:06:08 -07002783 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
2785 + ", perms=0x" + Integer.toHexString(perms));
2786 }
2787 FileUtils.setPermissions(name, perms, -1, -1);
2788 }
2789
2790 private File makeFilename(File base, String name) {
2791 if (name.indexOf(File.separatorChar) < 0) {
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002792 final File res = new File(base, name);
2793 // We report as filesystem access here to give us the best shot at
2794 // detecting apps that will pass the path down to native code.
2795 BlockGuard.getVmPolicy().onPathAccess(res.getPath());
2796 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 }
2798 throw new IllegalArgumentException(
Oscar Montemayora8529f62009-11-18 10:14:20 -08002799 "File " + name + " contains a path separator");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 }
2801
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002802 /**
2803 * Ensure that given directories exist, trying to create them if missing. If
2804 * unable to create, they are filtered by replacing with {@code null}.
2805 */
Jeff Sharkey35871f22016-01-29 17:13:29 -07002806 private File[] ensureExternalDirsExistOrFilter(File[] dirs) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002807 final StorageManager sm = getSystemService(StorageManager.class);
2808 final File[] result = new File[dirs.length];
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002809 for (int i = 0; i < dirs.length; i++) {
2810 File dir = dirs[i];
2811 if (!dir.exists()) {
2812 if (!dir.mkdirs()) {
Christopher Tatecc866da2013-10-02 18:11:01 -07002813 // recheck existence in case of cross-process race
2814 if (!dir.exists()) {
2815 // Failing to mkdir() may be okay, since we might not have
2816 // enough permissions; ask vold to create on our behalf.
Christopher Tatecc866da2013-10-02 18:11:01 -07002817 try {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002818 sm.mkdirs(dir);
Jeff Sharkey983294592015-07-13 10:25:31 -07002819 } catch (Exception e) {
2820 Log.w(TAG, "Failed to ensure " + dir + ": " + e);
Christopher Tatecc866da2013-10-02 18:11:01 -07002821 dir = null;
2822 }
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002823 }
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002824 }
2825 }
2826 result[i] = dir;
2827 }
2828 return result;
2829 }
2830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // ----------------------------------------------------------------------
2832 // ----------------------------------------------------------------------
2833 // ----------------------------------------------------------------------
2834
2835 private static final class ApplicationContentResolver extends ContentResolver {
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002836 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07002837 private final ActivityThread mMainThread;
Jeff Sharkey6d515712012-09-20 16:06:08 -07002838
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002839 public ApplicationContentResolver(Context context, ActivityThread mainThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 super(context);
Daulet Zhanguzin0af97d62019-12-30 15:41:28 +00002841 mMainThread = Objects.requireNonNull(mainThread);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 }
2843
2844 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002845 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07002846 protected IContentProvider acquireProvider(Context context, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002847 return mMainThread.acquireProvider(context,
2848 ContentProvider.getAuthorityWithoutUserId(auth),
2849 resolveUserIdFromAuthority(auth), true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 }
2851
2852 @Override
Jeff Sharkey6d515712012-09-20 16:06:08 -07002853 protected IContentProvider acquireExistingProvider(Context context, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002854 return mMainThread.acquireExistingProvider(context,
2855 ContentProvider.getAuthorityWithoutUserId(auth),
2856 resolveUserIdFromAuthority(auth), true);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07002857 }
2858
2859 @Override
2860 public boolean releaseProvider(IContentProvider provider) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07002861 return mMainThread.releaseProvider(provider, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002863
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002864 @Override
Jeff Sharkey6d515712012-09-20 16:06:08 -07002865 protected IContentProvider acquireUnstableProvider(Context c, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002866 return mMainThread.acquireProvider(c,
2867 ContentProvider.getAuthorityWithoutUserId(auth),
2868 resolveUserIdFromAuthority(auth), false);
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002869 }
2870
2871 @Override
2872 public boolean releaseUnstableProvider(IContentProvider icp) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07002873 return mMainThread.releaseProvider(icp, false);
2874 }
2875
2876 @Override
2877 public void unstableProviderDied(IContentProvider icp) {
2878 mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002879 }
Jeff Sharkey7aa76012013-09-30 14:26:27 -07002880
2881 @Override
2882 public void appNotRespondingViaProvider(IContentProvider icp) {
2883 mMainThread.appNotRespondingViaProvider(icp.asBinder());
2884 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002885
2886 /** @hide */
2887 protected int resolveUserIdFromAuthority(String auth) {
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002888 return ContentProvider.getUserIdFromAuthority(auth, getUserId());
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002891}