blob: b7555ee1c04e0a0c82a600052fc8b005eb3dcd5f [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;
Vasu Nori74f170f2010-06-01 18:06:18 -070049import android.database.DatabaseErrorHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.database.sqlite.SQLiteDatabase;
51import android.database.sqlite.SQLiteDatabase.CursorFactory;
52import android.graphics.Bitmap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.graphics.drawable.Drawable;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Binder;
Jeff Brown6e539312015-02-24 18:53:21 -080056import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Bundle;
Amith Yamasanicd757062012-10-19 18:23:52 -070058import android.os.Debug;
Oscar Montemayor539d3c42010-01-29 15:27:00 -080059import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.FileUtils;
61import android.os.Handler;
62import android.os.IBinder;
svetoslavganov75986cf2009-05-14 22:28:01 -070063import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070065import android.os.RemoteException;
Adam Lesinski4e862812016-11-21 16:02:24 -080066import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Jeff Sharkeya65e6492017-06-21 13:45:11 -060068import android.os.UserManager;
Jeff Sharkeyae266462017-11-27 13:32:24 -070069import android.os.storage.StorageManager;
Todd Kennedy8f135982019-07-02 07:35:15 -070070import android.permission.IPermissionManager;
Jeff Sharkeye84bdd32016-02-08 12:16:00 -070071import android.system.ErrnoException;
72import android.system.Os;
73import android.system.OsConstants;
Jeff Sharkey83aacde2017-03-22 23:13:39 -060074import android.system.StructStat;
Jordan Liu54735532019-10-29 10:33:55 -070075import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.util.AndroidRuntimeException;
Jeff Sharkey8e3ddab2013-06-17 18:26:37 -070077import android.util.ArrayMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.util.Log;
Amith Yamasanicd757062012-10-19 18:23:52 -070079import android.util.Slog;
Jeff Brown98365d72012-08-19 20:30:52 -070080import android.view.Display;
Jeff Brown6e539312015-02-24 18:53:21 -080081import android.view.DisplayAdjustments;
Felipe Lemebb567ae2017-10-04 09:56:21 -070082import android.view.autofill.AutofillManager.AutofillClient;
Dan Egnor95240272009-10-27 18:23:39 -070083
Jeff Sharkey35871f22016-01-29 17:13:29 -070084import com.android.internal.annotations.GuardedBy;
85import com.android.internal.util.Preconditions;
86
Jeff Sharkeydd02e332018-06-27 14:41:57 -060087import dalvik.system.BlockGuard;
88
Jeff Sharkey83aacde2017-03-22 23:13:39 -060089import libcore.io.Memory;
Adam Lesinski4e862812016-11-21 16:02:24 -080090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.io.File;
92import java.io.FileInputStream;
93import java.io.FileNotFoundException;
94import java.io.FileOutputStream;
Jeff Sharkey35871f22016-01-29 17:13:29 -070095import java.io.FilenameFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.io.IOException;
97import java.io.InputStream;
Makoto Onukid67070e2018-03-30 12:39:14 -070098import java.lang.annotation.Retention;
99import java.lang.annotation.RetentionPolicy;
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600100import java.nio.ByteOrder;
Felka Chang0d824d42019-11-19 15:06:52 +0800101import java.nio.file.Path;
Christopher Tatefe2368c2017-05-17 15:42:35 -0700102import java.util.ArrayList;
Jeff Sharkey7a30a302015-12-08 14:20:06 -0700103import java.util.Objects;
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700104import java.util.concurrent.Executor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106class ReceiverRestrictedContext extends ContextWrapper {
Andrei Onea4b2116c2019-02-28 15:13:42 +0000107 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 ReceiverRestrictedContext(Context base) {
109 super(base);
110 }
111
112 @Override
113 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
114 return registerReceiver(receiver, filter, null, null);
115 }
116
117 @Override
118 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
119 String broadcastPermission, Handler scheduler) {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700120 if (receiver == null) {
121 // Allow retrieving current sticky broadcast; this is safe since we
122 // aren't actually registering a receiver.
123 return super.registerReceiver(null, filter, broadcastPermission, scheduler);
124 } else {
125 throw new ReceiverCallNotAllowedException(
126 "BroadcastReceiver components are not allowed to register to receive intents");
127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 }
129
130 @Override
Meng Wang3f9e0362019-11-05 10:43:45 -0800131 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter,
132 String broadcastPermission, Handler scheduler) {
133 return registerReceiverAsUser(
134 receiver, UserHandle.ALL, filter, broadcastPermission, scheduler);
135 }
136
137 @Override
Dianne Hackborn20e80982012-08-31 19:00:44 -0700138 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
139 IntentFilter filter, String broadcastPermission, Handler scheduler) {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700140 if (receiver == null) {
141 // Allow retrieving current sticky broadcast; this is safe since we
142 // aren't actually registering a receiver.
143 return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
144 } else {
145 throw new ReceiverCallNotAllowedException(
146 "BroadcastReceiver components are not allowed to register to receive intents");
147 }
Dianne Hackborn20e80982012-08-31 19:00:44 -0700148 }
149
150 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 public boolean bindService(Intent service, ServiceConnection conn, int flags) {
152 throw new ReceiverCallNotAllowedException(
Jeff Sharkey27bd34d2012-09-16 12:49:00 -0700153 "BroadcastReceiver components are not allowed to bind to services");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 }
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800155
156 @Override
Bo Liu58a57662019-03-06 20:21:45 +0000157 public boolean bindService(
158 Intent service, int flags, Executor executor, ServiceConnection conn) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800159 throw new ReceiverCallNotAllowedException(
Bo Liu58a57662019-03-06 20:21:45 +0000160 "BroadcastReceiver components are not allowed to bind to services");
161 }
162
163 @Override
164 public boolean bindIsolatedService(Intent service, int flags, String instanceName,
165 Executor executor, ServiceConnection conn) {
166 throw new ReceiverCallNotAllowedException(
167 "BroadcastReceiver components are not allowed to bind to services");
Dianne Hackborn27b4d942018-11-12 15:01:40 -0800168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169}
170
171/**
Dianne Hackborn21556372010-02-04 16:34:40 -0800172 * Common implementation of Context API, which provides the base
173 * context object for Activity and other application components.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 */
Dianne Hackborn21556372010-02-04 16:34:40 -0800175class ContextImpl extends Context {
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800176 private final static String TAG = "ContextImpl";
Mitsuru Oshima569076c2009-07-02 20:06:08 -0700177 private final static boolean DEBUG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600179 private static final String XATTR_INODE_CACHE = "user.inode_cache";
180 private static final String XATTR_INODE_CODE_CACHE = "user.inode_code_cache";
181
Jeff Sharkey8e3ddab2013-06-17 18:26:37 -0700182 /**
183 * Map from package name, to preference name, to cached preferences.
184 */
Jeff Sharkeybe782582016-02-15 18:35:57 -0700185 @GuardedBy("ContextImpl.class")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100186 @UnsupportedAppUsage
Jeff Sharkeybe782582016-02-15 18:35:57 -0700187 private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;
188
189 /**
190 * Map from preference name to generated path.
191 */
192 @GuardedBy("ContextImpl.class")
Mathew Inwood8c854f82018-09-14 12:35:36 +0100193 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkeybe782582016-02-15 18:35:57 -0700194 private ArrayMap<String, File> mSharedPrefsPaths;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100196 @UnsupportedAppUsage
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800197 final @NonNull ActivityThread mMainThread;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100198 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +0000199 final @NonNull LoadedApk mPackageInfo;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100200 @UnsupportedAppUsage
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800201 private @Nullable ClassLoader mClassLoader;
Jeff Browndefd4a62014-03-10 21:24:37 -0700202
Andrii Kulian4a316972020-01-21 21:41:38 -0800203 private final @Nullable IBinder mToken;
Jeff Browndefd4a62014-03-10 21:24:37 -0700204
Jeff Sharkeyad357d12018-02-02 13:25:31 -0700205 private final @NonNull UserHandle mUser;
Jeff Browndefd4a62014-03-10 21:24:37 -0700206
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100207 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700208 private final ApplicationContentResolver mContentResolver;
209
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100210 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -0700211 private final String mBasePackageName;
Mathew Inwood8c854f82018-09-14 12:35:36 +0100212 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Browndefd4a62014-03-10 21:24:37 -0700213 private final String mOpPackageName;
214
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700215 /** If of feature this context is for */
216 private final @Nullable String mFeatureId;
217
Adam Lesinski4ece3d62016-06-16 18:05:41 -0700218 private final @NonNull ResourcesManager mResourcesManager;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100219 @UnsupportedAppUsage
Adam Lesinski8fa71072016-11-18 18:13:55 -0800220 private @NonNull Resources mResources;
Andrii Kulian4a316972020-01-21 21:41:38 -0800221 private @Nullable Display mDisplay; // may be null if invalid display or not initialized yet.
Jeff Browndefd4a62014-03-10 21:24:37 -0700222
Mathew Inwood8c854f82018-09-14 12:35:36 +0100223 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Jeff Sharkey7a30a302015-12-08 14:20:06 -0700224 private final int mFlags;
Jeff Browndefd4a62014-03-10 21:24:37 -0700225
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100226 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private Context mOuterContext;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100228 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private int mThemeResource = 0;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100230 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 private Resources.Theme mTheme = null;
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100232 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private PackageManager mPackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private Context mReceiverRestrictedContext = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
Adam Lesinski1665d0f2017-03-10 14:46:57 -0800236 // The name of the split this Context is representing. May be null.
237 private @Nullable String mSplitName = null;
238
Felipe Lemea4f39cd2019-02-19 15:08:59 -0800239 private @Nullable AutofillClient mAutofillClient = null;
240 private @Nullable AutofillOptions mAutofillOptions;
Felipe Lemebb567ae2017-10-04 09:56:21 -0700241
Felipe Leme326f15a2019-02-19 09:42:24 -0800242 private ContentCaptureOptions mContentCaptureOptions = null;
Felipe Lemeecb08be2018-11-27 15:48:47 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 private final Object mSync = new Object();
245
Andrii Kulian4a316972020-01-21 21:41:38 -0800246 private boolean mIsSystemOrSystemUiContext;
247 private boolean mIsUiContext;
248
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700249 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 private File mDatabasesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700251 @GuardedBy("mSync")
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100252 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 private File mPreferencesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700254 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 private File mFilesDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700256 @GuardedBy("mSync")
Felka Chang0d824d42019-11-19 15:06:52 +0800257 private File mCratesDir;
258 @GuardedBy("mSync")
Christopher Tatea7835b62014-07-11 17:25:57 -0700259 private File mNoBackupFilesDir;
260 @GuardedBy("mSync")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 private File mCacheDir;
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700262 @GuardedBy("mSync")
263 private File mCodeCacheDir;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700264
Jeff Brown6e539312015-02-24 18:53:21 -0800265 // The system service cache for the system services that are cached per-ContextImpl.
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100266 @UnsupportedAppUsage
Jeff Brown6e539312015-02-24 18:53:21 -0800267 final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
Brad Fitzpatrick224ba0c2010-11-12 12:22:15 -0800268
Makoto Onukif896f122018-01-25 09:50:24 -0800269 static final int STATE_UNINITIALIZED = 0;
270 static final int STATE_INITIALIZING = 1;
271 static final int STATE_READY = 2;
Makoto Onukid67070e2018-03-30 12:39:14 -0700272 static final int STATE_NOT_FOUND = 3;
273
274 /** @hide */
275 @IntDef(prefix = { "STATE_" }, value = {
276 STATE_UNINITIALIZED,
277 STATE_INITIALIZING,
278 STATE_READY,
279 STATE_NOT_FOUND,
280 })
281 @Retention(RetentionPolicy.SOURCE)
282 @interface ServiceInitializationState {}
Makoto Onukif896f122018-01-25 09:50:24 -0800283
284 /**
285 * Initialization state for each service. Any of {@link #STATE_UNINITIALIZED},
286 * {@link #STATE_INITIALIZING} or {@link #STATE_READY},
287 */
Makoto Onukid67070e2018-03-30 12:39:14 -0700288 @ServiceInitializationState
289 final int[] mServiceInitializationStateArray = new int[mServiceCache.length];
Makoto Onukif896f122018-01-25 09:50:24 -0800290
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100291 @UnsupportedAppUsage
Dianne Hackborn5fd21692011-06-07 14:09:47 -0700292 static ContextImpl getImpl(Context context) {
293 Context nextContext;
294 while ((context instanceof ContextWrapper) &&
295 (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
296 context = nextContext;
297 }
298 return (ContextImpl)context;
299 }
300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 @Override
302 public AssetManager getAssets() {
Dianne Hackborn756220b2012-08-14 16:45:30 -0700303 return getResources().getAssets();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 }
305
306 @Override
307 public Resources getResources() {
308 return mResources;
309 }
310
311 @Override
312 public PackageManager getPackageManager() {
313 if (mPackageManager != null) {
314 return mPackageManager;
315 }
316
Todd Kennedy8f135982019-07-02 07:35:15 -0700317 final IPackageManager pm = ActivityThread.getPackageManager();
318 final IPermissionManager permissionManager = ActivityThread.getPermissionManager();
319 if (pm != null && permissionManager != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 // Doesn't matter if we make more than one instance.
Todd Kennedy8f135982019-07-02 07:35:15 -0700321 return (mPackageManager = new ApplicationPackageManager(this, pm, permissionManager));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322 }
323
324 return null;
325 }
326
327 @Override
328 public ContentResolver getContentResolver() {
329 return mContentResolver;
330 }
331
332 @Override
333 public Looper getMainLooper() {
334 return mMainThread.getLooper();
335 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 @Override
Jeff Sharkey8439ac02017-12-12 17:26:23 -0700338 public Executor getMainExecutor() {
339 return mMainThread.getExecutor();
340 }
341
342 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 public Context getApplicationContext() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000344 return (mPackageInfo != null) ?
345 mPackageInfo.getApplication() : mMainThread.getApplication();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 @Override
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700349 public void setTheme(int resId) {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700350 synchronized (mSync) {
351 if (mThemeResource != resId) {
352 mThemeResource = resId;
353 initializeTheme();
354 }
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 @Override
Dianne Hackborn247fe742011-01-08 17:25:57 -0800359 public int getThemeResId() {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700360 synchronized (mSync) {
361 return mThemeResource;
362 }
Dianne Hackborn247fe742011-01-08 17:25:57 -0800363 }
364
365 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 public Resources.Theme getTheme() {
Adam Lesinski1e87a362017-06-12 12:22:10 -0700367 synchronized (mSync) {
368 if (mTheme != null) {
369 return mTheme;
370 }
371
372 mThemeResource = Resources.selectDefaultTheme(mThemeResource,
373 getOuterContext().getApplicationInfo().targetSdkVersion);
374 initializeTheme();
375
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700376 return mTheme;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379
Alan Viverettecc2a1d42015-05-01 11:28:37 -0700380 private void initializeTheme() {
381 if (mTheme == null) {
382 mTheme = mResources.newTheme();
383 }
384 mTheme.applyStyle(mThemeResource, true);
385 }
386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 @Override
388 public ClassLoader getClassLoader() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000389 return mClassLoader != null ? mClassLoader : (mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
391
392 @Override
393 public String getPackageName() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000394 if (mPackageInfo != null) {
395 return mPackageInfo.getPackageName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
Todd Kennedy233a0b12018-01-29 20:30:24 +0000397 // No mPackageInfo means this is a Context for the system itself,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800398 // and this here is its name.
399 return "android";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800400 }
401
Dianne Hackbornd8e1dbb2013-01-17 17:47:37 -0800402 /** @hide */
403 @Override
404 public String getBasePackageName() {
405 return mBasePackageName != null ? mBasePackageName : getPackageName();
406 }
407
Dianne Hackborn95d78532013-09-11 09:51:14 -0700408 /** @hide */
409 @Override
410 public String getOpPackageName() {
411 return mOpPackageName != null ? mOpPackageName : getBasePackageName();
412 }
413
Philip P. Moltmann59076d82019-08-19 15:00:40 -0700414 /** @hide */
415 @Override
416 public @Nullable String getFeatureId() {
417 return mFeatureId;
418 }
419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 @Override
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700421 public ApplicationInfo getApplicationInfo() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000422 if (mPackageInfo != null) {
423 return mPackageInfo.getApplicationInfo();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700424 }
425 throw new RuntimeException("Not supported in system context");
426 }
427
428 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 public String getPackageResourcePath() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000430 if (mPackageInfo != null) {
431 return mPackageInfo.getResDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 }
433 throw new RuntimeException("Not supported in system context");
434 }
435
436 @Override
437 public String getPackageCodePath() {
Todd Kennedy233a0b12018-01-29 20:30:24 +0000438 if (mPackageInfo != null) {
439 return mPackageInfo.getAppDir();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
441 throw new RuntimeException("Not supported in system context");
442 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200443
Jeff Brown6e539312015-02-24 18:53:21 -0800444 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 public SharedPreferences getSharedPreferences(String name, int mode) {
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700446 // At least one application in the world actually passes in a null
447 // name. This happened to work because when we generated the file name
448 // we would stringify it to "null.xml". Nice.
Todd Kennedy233a0b12018-01-29 20:30:24 +0000449 if (mPackageInfo.getApplicationInfo().targetSdkVersion <
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700450 Build.VERSION_CODES.KITKAT) {
451 if (name == null) {
452 name = "null";
453 }
454 }
455
Jeff Sharkeybe782582016-02-15 18:35:57 -0700456 File file;
457 synchronized (ContextImpl.class) {
458 if (mSharedPrefsPaths == null) {
459 mSharedPrefsPaths = new ArrayMap<>();
460 }
461 file = mSharedPrefsPaths.get(name);
462 if (file == null) {
463 file = getSharedPreferencesPath(name);
464 mSharedPrefsPaths.put(name, file);
465 }
466 }
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700467 return getSharedPreferences(file, mode);
468 }
469
470 @Override
471 public SharedPreferences getSharedPreferences(File file, int mode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 SharedPreferencesImpl sp;
Dianne Hackbornf6913592013-09-05 13:21:24 -0700473 synchronized (ContextImpl.class) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700474 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
475 sp = cache.get(file);
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700476 if (sp == null) {
John Reckf3903e92017-05-12 17:12:54 -0700477 checkMode(mode);
478 if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
479 if (isCredentialProtectedStorage()
Jeff Sharkeya65e6492017-06-21 13:45:11 -0600480 && !getSystemService(UserManager.class)
481 .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
John Reckf3903e92017-05-12 17:12:54 -0700482 throw new IllegalStateException("SharedPreferences in credential encrypted "
483 + "storage are not available until after user is unlocked");
484 }
485 }
Jeff Sharkey8fc29cf2015-11-30 17:51:00 -0700486 sp = new SharedPreferencesImpl(file, mode);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700487 cache.put(file, sp);
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700488 return sp;
489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 }
Brad Fitzpatrick4e920f72010-12-14 11:52:13 -0800491 if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
492 getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
493 // If somebody else (some other process) changed the prefs
494 // file behind our back, we reload it. This has been the
495 // historical (if undocumented) behavior.
496 sp.startReloadIfChangedUnexpectedly();
497 }
Brad Fitzpatrick6194c532010-09-07 18:00:33 -0700498 return sp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
Andreas Gampe3f24e692018-02-05 13:24:28 -0800501 @GuardedBy("ContextImpl.class")
Jeff Sharkey35871f22016-01-29 17:13:29 -0700502 private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
Jeff Sharkeybe782582016-02-15 18:35:57 -0700503 if (sSharedPrefsCache == null) {
504 sSharedPrefsCache = new ArrayMap<>();
Jeff Sharkey35871f22016-01-29 17:13:29 -0700505 }
506
507 final String packageName = getPackageName();
Jeff Sharkeybe782582016-02-15 18:35:57 -0700508 ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700509 if (packagePrefs == null) {
510 packagePrefs = new ArrayMap<>();
Jeff Sharkeybe782582016-02-15 18:35:57 -0700511 sSharedPrefsCache.put(packageName, packagePrefs);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700512 }
513
514 return packagePrefs;
515 }
516
Christopher Tatefe2368c2017-05-17 15:42:35 -0700517 @Override
518 public void reloadSharedPreferences() {
519 // Build the list of all per-context impls (i.e. caches) we know about
520 ArrayList<SharedPreferencesImpl> spImpls = new ArrayList<>();
521 synchronized (ContextImpl.class) {
522 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
523 for (int i = 0; i < cache.size(); i++) {
524 final SharedPreferencesImpl sp = cache.valueAt(i);
525 if (sp != null) {
526 spImpls.add(sp);
527 }
528 }
529 }
530
531 // Issue the reload outside the cache lock
532 for (int i = 0; i < spImpls.size(); i++) {
533 spImpls.get(i).startReloadIfChangedUnexpectedly();
534 }
535 }
536
Jeff Sharkey35871f22016-01-29 17:13:29 -0700537 /**
538 * Try our best to migrate all files from source to target that match
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700539 * requested prefix.
540 *
541 * @return the number of files moved, or -1 if there was trouble.
Jeff Sharkey35871f22016-01-29 17:13:29 -0700542 */
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600543 private static int moveFiles(File sourceDir, File targetDir, final String prefix) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700544 final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() {
545 @Override
546 public boolean accept(File dir, String name) {
547 return name.startsWith(prefix);
548 }
549 });
550
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700551 int res = 0;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700552 for (File sourceFile : sourceFiles) {
553 final File targetFile = new File(targetDir, sourceFile.getName());
554 Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile);
555 try {
556 FileUtils.copyFileOrThrow(sourceFile, targetFile);
557 FileUtils.copyPermissions(sourceFile, targetFile);
558 if (!sourceFile.delete()) {
559 throw new IOException("Failed to clean up " + sourceFile);
560 }
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700561 if (res != -1) {
562 res++;
563 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700564 } catch (IOException e) {
565 Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e);
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700566 res = -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700567 }
568 }
569 return res;
570 }
571
572 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600573 public boolean moveSharedPreferencesFrom(Context sourceContext, String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700574 synchronized (ContextImpl.class) {
575 final File source = sourceContext.getSharedPreferencesPath(name);
576 final File target = getSharedPreferencesPath(name);
577
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600578 final int res = moveFiles(source.getParentFile(), target.getParentFile(),
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700579 source.getName());
580 if (res > 0) {
581 // We moved at least one file, so evict any in-memory caches for
582 // either location
583 final ArrayMap<File, SharedPreferencesImpl> cache =
584 getSharedPreferencesCacheLocked();
585 cache.remove(source);
586 cache.remove(target);
587 }
588 return res != -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700589 }
590 }
591
592 @Override
593 public boolean deleteSharedPreferences(String name) {
594 synchronized (ContextImpl.class) {
595 final File prefs = getSharedPreferencesPath(name);
596 final File prefsBackup = SharedPreferencesImpl.makeBackupFile(prefs);
597
598 // Evict any in-memory caches
599 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
600 cache.remove(prefs);
601
602 prefs.delete();
603 prefsBackup.delete();
604
605 // We failed if files are still lingering
606 return !(prefs.exists() || prefsBackup.exists());
607 }
608 }
609
Mathew Inwood61e8ae62018-08-14 14:17:44 +0100610 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 private File getPreferencesDir() {
612 synchronized (mSync) {
613 if (mPreferencesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700614 mPreferencesDir = new File(getDataDir(), "shared_prefs");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700616 return ensurePrivateDirExists(mPreferencesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
618 }
619
620 @Override
621 public FileInputStream openFileInput(String name)
622 throws FileNotFoundException {
623 File f = makeFilename(getFilesDir(), name);
624 return new FileInputStream(f);
625 }
626
627 @Override
Jeff Sharkey634dc422016-01-30 17:44:15 -0700628 public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
629 checkMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 final boolean append = (mode&MODE_APPEND) != 0;
631 File f = makeFilename(getFilesDir(), name);
632 try {
633 FileOutputStream fos = new FileOutputStream(f, append);
634 setFilePermissionsFromMode(f.getPath(), mode, 0);
635 return fos;
636 } catch (FileNotFoundException e) {
637 }
638
639 File parent = f.getParentFile();
640 parent.mkdir();
641 FileUtils.setPermissions(
642 parent.getPath(),
643 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
644 -1, -1);
645 FileOutputStream fos = new FileOutputStream(f, append);
646 setFilePermissionsFromMode(f.getPath(), mode, 0);
647 return fos;
648 }
649
650 @Override
651 public boolean deleteFile(String name) {
652 File f = makeFilename(getFilesDir(), name);
653 return f.delete();
654 }
655
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700656 /**
657 * Common-path handling of app data dir creation
658 */
Jeff Sharkey35871f22016-01-29 17:13:29 -0700659 private static File ensurePrivateDirExists(File file) {
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600660 return ensurePrivateDirExists(file, 0771, -1, null);
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700661 }
662
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600663 private static File ensurePrivateCacheDirExists(File file, String xattr) {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700664 final int gid = UserHandle.getCacheAppGid(Process.myUid());
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600665 return ensurePrivateDirExists(file, 02771, gid, xattr);
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700666 }
667
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600668 private static File ensurePrivateDirExists(File file, int mode, int gid, String xattr) {
Christopher Tatea7835b62014-07-11 17:25:57 -0700669 if (!file.exists()) {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700670 final String path = file.getAbsolutePath();
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700671 try {
Jeff Sharkey5eb3eb52016-12-13 08:44:51 -0700672 Os.mkdir(path, mode);
673 Os.chmod(path, mode);
674 if (gid != -1) {
675 Os.chown(path, -1, gid);
676 }
Jeff Sharkeye84bdd32016-02-08 12:16:00 -0700677 } catch (ErrnoException e) {
678 if (e.errno == OsConstants.EEXIST) {
679 // We must have raced with someone; that's okay
680 } else {
681 Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
Christopher Tatea7835b62014-07-11 17:25:57 -0700682 }
Christopher Tatea7835b62014-07-11 17:25:57 -0700683 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600684
685 if (xattr != null) {
686 try {
687 final StructStat stat = Os.stat(file.getAbsolutePath());
688 final byte[] value = new byte[8];
689 Memory.pokeLong(value, 0, stat.st_ino, ByteOrder.nativeOrder());
690 Os.setxattr(file.getParentFile().getAbsolutePath(), xattr, value, 0);
691 } catch (ErrnoException e) {
692 Log.w(TAG, "Failed to update " + xattr + ": " + e.getMessage());
693 }
694 }
Christopher Tatea7835b62014-07-11 17:25:57 -0700695 }
696 return file;
697 }
698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 @Override
700 public File getFilesDir() {
701 synchronized (mSync) {
702 if (mFilesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700703 mFilesDir = new File(getDataDir(), "files");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700705 return ensurePrivateDirExists(mFilesDir);
Christopher Tatea7835b62014-07-11 17:25:57 -0700706 }
707 }
708
709 @Override
Felka Chang0d824d42019-11-19 15:06:52 +0800710 public File getCrateDir(@NonNull String crateId) {
711 Preconditions.checkArgument(FileUtils.isValidExtFilename(crateId), "invalidated crateId");
712 final Path cratesRootPath = getDataDir().toPath().resolve("crates");
713 final Path absoluteNormalizedCratePath = cratesRootPath.resolve(crateId)
714 .toAbsolutePath().normalize();
715
716 synchronized (mSync) {
717 if (mCratesDir == null) {
718 mCratesDir = cratesRootPath.toFile();
719 }
720 ensurePrivateDirExists(mCratesDir);
721 }
722
723 File cratedDir = absoluteNormalizedCratePath.toFile();
724 return ensurePrivateDirExists(cratedDir);
725 }
726
727 @Override
Christopher Tatea7835b62014-07-11 17:25:57 -0700728 public File getNoBackupFilesDir() {
729 synchronized (mSync) {
730 if (mNoBackupFilesDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700731 mNoBackupFilesDir = new File(getDataDir(), "no_backup");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700733 return ensurePrivateDirExists(mNoBackupFilesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 @Override
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800738 public File getExternalFilesDir(String type) {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700739 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700740 final File[] dirs = getExternalFilesDirs(type);
741 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700742 }
743
744 @Override
745 public File[] getExternalFilesDirs(String type) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800746 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600747 File[] dirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700748 if (type != null) {
749 dirs = Environment.buildPaths(dirs, type);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800750 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700751 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800752 }
753 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200754
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800755 @Override
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800756 public File getObbDir() {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700757 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700758 final File[] dirs = getObbDirs();
759 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700760 }
761
762 @Override
763 public File[] getObbDirs() {
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800764 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600765 File[] dirs = Environment.buildExternalStorageAppObbDirs(getPackageName());
766 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborn805fd7e2011-01-16 18:30:29 -0800767 }
768 }
769
770 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 public File getCacheDir() {
772 synchronized (mSync) {
773 if (mCacheDir == null) {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700774 mCacheDir = new File(getDataDir(), "cache");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600776 return ensurePrivateCacheDirExists(mCacheDir, XATTR_INODE_CACHE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200779
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800780 @Override
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700781 public File getCodeCacheDir() {
782 synchronized (mSync) {
783 if (mCodeCacheDir == null) {
Alex Light2d0691c2019-10-03 14:36:57 -0700784 mCodeCacheDir = getCodeCacheDirBeforeBind(getDataDir());
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700785 }
Jeff Sharkey83aacde2017-03-22 23:13:39 -0600786 return ensurePrivateCacheDirExists(mCodeCacheDir, XATTR_INODE_CODE_CACHE);
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700787 }
788 }
789
Alex Light2d0691c2019-10-03 14:36:57 -0700790 /**
791 * Helper for getting code-cache dir potentially before application bind.
792 *
793 * @hide
794 */
795 static File getCodeCacheDirBeforeBind(File dataDir) {
796 return new File(dataDir, "code_cache");
797 }
798
Jeff Sharkey4ed745d2014-07-15 20:39:15 -0700799 @Override
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800800 public File getExternalCacheDir() {
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700801 // Operates on primary external storage
Christopher Tate11179b42017-07-13 15:18:38 -0700802 final File[] dirs = getExternalCacheDirs();
803 return (dirs != null && dirs.length > 0) ? dirs[0] : null;
Jeff Sharkey1abdb712013-08-11 16:28:14 -0700804 }
805
806 @Override
807 public File[] getExternalCacheDirs() {
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800808 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600809 File[] dirs = Environment.buildExternalStorageAppCacheDirs(getPackageName());
810 return ensureExternalDirsExistOrFilter(dirs);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800811 }
812 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 @Override
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700815 public File[] getExternalMediaDirs() {
816 synchronized (mSync) {
Jeff Sharkey4a2b1192016-06-27 17:43:15 -0600817 File[] dirs = Environment.buildExternalStorageAppMediaDirs(getPackageName());
818 return ensureExternalDirsExistOrFilter(dirs);
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700819 }
820 }
821
Fyodor Kupolov61221292016-09-02 15:21:03 -0700822 /**
823 * @hide
824 */
825 @Nullable
826 @Override
827 public File getPreloadsFileCache() {
828 return Environment.getDataPreloadsFileCacheDirectory(getPackageName());
829 }
830
Jeff Sharkey2ee3c1e2014-05-30 15:38:35 -0700831 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 public File getFileStreamPath(String name) {
833 return makeFilename(getFilesDir(), name);
834 }
835
836 @Override
Jeff Sharkey6a6cdaf2015-12-07 19:25:19 -0700837 public File getSharedPreferencesPath(String name) {
838 return makeFilename(getPreferencesDir(), name + ".xml");
839 }
840
841 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 public String[] fileList() {
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700843 return FileUtils.listOrEmpty(getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845
846 @Override
847 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
Jeff Brown47847f32012-03-22 19:13:11 -0700848 return openOrCreateDatabase(name, mode, factory, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
850
851 @Override
Vasu Nori74f170f2010-06-01 18:06:18 -0700852 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
853 DatabaseErrorHandler errorHandler) {
Jeff Sharkey634dc422016-01-30 17:44:15 -0700854 checkMode(mode);
Jeff Sharkey35871f22016-01-29 17:13:29 -0700855 File f = getDatabasePath(name);
Jeff Brown47847f32012-03-22 19:13:11 -0700856 int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
857 if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
858 flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
859 }
Sunny Goyala21e6b22015-12-02 09:51:02 -0800860 if ((mode & MODE_NO_LOCALIZED_COLLATORS) != 0) {
861 flags |= SQLiteDatabase.NO_LOCALIZED_COLLATORS;
862 }
Jeff Brown47847f32012-03-22 19:13:11 -0700863 SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
Vasu Nori74f170f2010-06-01 18:06:18 -0700864 setFilePermissionsFromMode(f.getPath(), mode, 0);
865 return db;
866 }
867
868 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600869 public boolean moveDatabaseFrom(Context sourceContext, String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700870 synchronized (ContextImpl.class) {
871 final File source = sourceContext.getDatabasePath(name);
872 final File target = getDatabasePath(name);
Jeff Sharkey8a372a02016-03-16 16:25:45 -0600873 return moveFiles(source.getParentFile(), target.getParentFile(),
Jeff Sharkey390f2ed2016-03-01 15:25:03 -0700874 source.getName()) != -1;
Jeff Sharkey35871f22016-01-29 17:13:29 -0700875 }
876 }
877
878 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 public boolean deleteDatabase(String name) {
880 try {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700881 File f = getDatabasePath(name);
Jeff Brown79087e42012-03-01 19:52:44 -0800882 return SQLiteDatabase.deleteDatabase(f);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 } catch (Exception e) {
884 }
885 return false;
886 }
887
888 @Override
889 public File getDatabasePath(String name) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700890 File dir;
891 File f;
892
893 if (name.charAt(0) == File.separatorChar) {
894 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
895 dir = new File(dirPath);
896 name = name.substring(name.lastIndexOf(File.separatorChar));
897 f = new File(dir, name);
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700898
899 if (!dir.isDirectory() && dir.mkdir()) {
900 FileUtils.setPermissions(dir.getPath(),
901 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
902 -1, -1);
903 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700904 } else {
905 dir = getDatabasesDir();
906 f = makeFilename(dir, name);
907 }
908
Jeff Sharkey35871f22016-01-29 17:13:29 -0700909 return f;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 }
911
912 @Override
913 public String[] databaseList() {
Jeff Sharkeyc4bab982016-02-01 10:16:01 -0700914 return FileUtils.listOrEmpty(getDatabasesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 private File getDatabasesDir() {
918 synchronized (mSync) {
919 if (mDatabasesDir == null) {
Jeff Sharkey35871f22016-01-29 17:13:29 -0700920 if ("android".equals(getPackageName())) {
921 mDatabasesDir = new File("/data/system");
922 } else {
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -0700923 mDatabasesDir = new File(getDataDir(), "databases");
Jeff Sharkey35871f22016-01-29 17:13:29 -0700924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
Jeff Sharkey35871f22016-01-29 17:13:29 -0700926 return ensurePrivateDirExists(mDatabasesDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 }
928 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +0200929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800931 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 public Drawable getWallpaper() {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700933 return getWallpaperManager().getDrawable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 }
935
936 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800937 @Deprecated
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700938 public Drawable peekWallpaper() {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700939 return getWallpaperManager().peekDrawable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941
942 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800943 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 public int getWallpaperDesiredMinimumWidth() {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700945 return getWallpaperManager().getDesiredMinimumWidth();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 }
947
948 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800949 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 public int getWallpaperDesiredMinimumHeight() {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700951 return getWallpaperManager().getDesiredMinimumHeight();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
953
954 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800955 @Deprecated
956 public void setWallpaper(Bitmap bitmap) throws IOException {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700957 getWallpaperManager().setBitmap(bitmap);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959
960 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800961 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 public void setWallpaper(InputStream data) throws IOException {
Dianne Hackborn4c62fc02009-08-08 20:40:27 -0700963 getWallpaperManager().setStream(data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
965
966 @Override
Jeff Brown6e539312015-02-24 18:53:21 -0800967 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 public void clearWallpaper() throws IOException {
Dianne Hackborn8cc6a502009-08-05 21:29:42 -0700969 getWallpaperManager().clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971
Jeff Brown6e539312015-02-24 18:53:21 -0800972 private WallpaperManager getWallpaperManager() {
973 return getSystemService(WallpaperManager.class);
974 }
975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 @Override
977 public void startActivity(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -0700978 warnIfCallingFromSystemProcess();
Dianne Hackborna4972e92012-03-14 10:38:05 -0700979 startActivity(intent, null);
980 }
981
Amith Yamasani82644082012-08-03 13:09:11 -0700982 /** @hide */
983 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700984 public void startActivityAsUser(Intent intent, UserHandle user) {
Dianne Hackbornf1c26e22012-08-23 13:54:58 -0700985 startActivityAsUser(intent, null, user);
Amith Yamasani82644082012-08-03 13:09:11 -0700986 }
987
Dianne Hackborna4972e92012-03-14 10:38:05 -0700988 @Override
989 public void startActivity(Intent intent, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -0700990 warnIfCallingFromSystemProcess();
Jorim Jaggi2adba072016-03-03 13:43:39 +0100991
992 // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
993 // generally not allowed, except if the caller specifies the task id the activity should
Bryce Leef465ea02017-05-02 16:58:22 -0700994 // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
995 // maintain this for backwards compatibility.
996 final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
997
998 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
999 && (targetSdkVersion < Build.VERSION_CODES.N
1000 || targetSdkVersion >= Build.VERSION_CODES.P)
1001 && (options == null
1002 || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 throw new AndroidRuntimeException(
1004 "Calling startActivity() from outside of an Activity "
Bryce Leef465ea02017-05-02 16:58:22 -07001005 + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
1006 + " Is this really what you want?");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008 mMainThread.getInstrumentation().execStartActivity(
Dianne Hackborna750a632015-06-16 17:18:23 -07001009 getOuterContext(), mMainThread.getApplicationThread(), null,
1010 (Activity) null, intent, -1, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 }
1012
Amith Yamasani258848d2012-08-10 17:06:33 -07001013 /** @hide */
1014 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001015 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
Amith Yamasani258848d2012-08-10 17:06:33 -07001016 try {
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001017 ActivityTaskManager.getService().startActivityAsUser(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001018 mMainThread.getApplicationThread(), getBasePackageName(), intent,
Amith Yamasani258848d2012-08-10 17:06:33 -07001019 intent.resolveTypeIfNeeded(getContentResolver()),
Jeff Hao1b012d32014-08-20 10:35:34 -07001020 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001021 user.getIdentifier());
Dianne Hackborne5c42622015-05-19 16:04:04 -07001022 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001023 throw e.rethrowFromSystemServer();
Amith Yamasani258848d2012-08-10 17:06:33 -07001024 }
1025 }
1026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 @Override
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001028 public void startActivities(Intent[] intents) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001029 warnIfCallingFromSystemProcess();
Dianne Hackborna4972e92012-03-14 10:38:05 -07001030 startActivities(intents, null);
1031 }
1032
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001033 /** @hide */
1034 @Override
Selim Cinek7fa385a2018-01-24 08:35:28 -08001035 public int startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001036 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1037 throw new AndroidRuntimeException(
1038 "Calling startActivities() from outside of an Activity "
1039 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1040 + " Is this really what you want?");
1041 }
Selim Cinek7fa385a2018-01-24 08:35:28 -08001042 return mMainThread.getInstrumentation().execStartActivitiesAsUser(
Dianne Hackborna750a632015-06-16 17:18:23 -07001043 getOuterContext(), mMainThread.getApplicationThread(), null,
1044 (Activity) null, intents, options, userHandle.getIdentifier());
Amith Yamasaniea7e9152012-09-24 16:11:18 -07001045 }
1046
Dianne Hackborna4972e92012-03-14 10:38:05 -07001047 @Override
1048 public void startActivities(Intent[] intents, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001049 warnIfCallingFromSystemProcess();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001050 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1051 throw new AndroidRuntimeException(
1052 "Calling startActivities() from outside of an Activity "
1053 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1054 + " Is this really what you want?");
1055 }
1056 mMainThread.getInstrumentation().execStartActivities(
Dianne Hackborna750a632015-06-16 17:18:23 -07001057 getOuterContext(), mMainThread.getApplicationThread(), null,
1058 (Activity) null, intents, options);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001059 }
1060
1061 @Override
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001062 public void startIntentSender(IntentSender intent,
1063 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
1064 throws IntentSender.SendIntentException {
Dianne Hackborna4972e92012-03-14 10:38:05 -07001065 startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
1066 }
1067
1068 @Override
1069 public void startIntentSender(IntentSender intent, Intent fillInIntent,
1070 int flagsMask, int flagsValues, int extraFlags, Bundle options)
1071 throws IntentSender.SendIntentException {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001072 try {
1073 String resolvedType = null;
1074 if (fillInIntent != null) {
Jeff Sharkeya14acd22013-04-02 18:27:45 -07001075 fillInIntent.migrateExtraStreamToClipData();
Jeff Sharkey344744b2016-01-28 19:03:30 -07001076 fillInIntent.prepareToLeaveProcess(this);
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001077 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
1078 }
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07001079 int result = ActivityTaskManager.getService()
Dianne Hackborn3e6e3852017-05-19 16:12:08 -07001080 .startActivityIntentSender(mMainThread.getApplicationThread(),
1081 intent != null ? intent.getTarget() : null,
1082 intent != null ? intent.getWhitelistToken() : null,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001083 fillInIntent, resolvedType, null, null,
Dianne Hackborna4972e92012-03-14 10:38:05 -07001084 0, flagsMask, flagsValues, options);
1085 if (result == ActivityManager.START_CANCELED) {
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001086 throw new IntentSender.SendIntentException();
1087 }
1088 Instrumentation.checkStartActivityResult(result, null);
1089 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001090 throw e.rethrowFromSystemServer();
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001091 }
1092 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02001093
Dianne Hackbornfa82f222009-09-17 15:14:12 -07001094 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 public void sendBroadcast(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001096 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1098 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001099 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001100 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001101 mMainThread.getApplicationThread(), intent, resolvedType, null,
1102 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
1103 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001105 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 }
1107 }
1108
Amith Yamasani67cf7d32012-02-16 14:31:23 -08001109 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 public void sendBroadcast(Intent intent, String receiverPermission) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001111 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001113 String[] receiverPermissions = receiverPermission == null ? null
1114 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001116 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001117 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001118 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001119 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1120 null, false, false, getUserId());
1121 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001122 throw e.rethrowFromSystemServer();
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001123 }
1124 }
1125
1126 @Override
1127 public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions) {
1128 warnIfCallingFromSystemProcess();
1129 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1130 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001131 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001132 ActivityManager.getService().broadcastIntent(
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001133 mMainThread.getApplicationThread(), intent, resolvedType, null,
1134 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001135 null, false, false, getUserId());
1136 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001137 throw e.rethrowFromSystemServer();
Dianne Hackborna750a632015-06-16 17:18:23 -07001138 }
1139 }
1140
1141 @Override
Tyler Gunnf955e562018-04-26 14:43:31 -07001142 public void sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user,
1143 String[] receiverPermissions) {
Tyler Gunnf955e562018-04-26 14:43:31 -07001144 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1145 try {
1146 intent.prepareToLeaveProcess(this);
1147 ActivityManager.getService().broadcastIntent(
1148 mMainThread.getApplicationThread(), intent, resolvedType, null,
1149 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1150 null, false, false, user.getIdentifier());
1151 } catch (RemoteException e) {
1152 throw e.rethrowFromSystemServer();
1153 }
1154 }
1155
1156 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001157 public void sendBroadcast(Intent intent, String receiverPermission, Bundle options) {
1158 warnIfCallingFromSystemProcess();
1159 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001160 String[] receiverPermissions = receiverPermission == null ? null
1161 : new String[] {receiverPermission};
Dianne Hackborna750a632015-06-16 17:18:23 -07001162 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001163 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001164 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001165 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001166 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001167 options, false, false, getUserId());
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001168 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001169 throw e.rethrowFromSystemServer();
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001170 }
1171 }
1172
1173 @Override
1174 public void sendBroadcast(Intent intent, String receiverPermission, int appOp) {
1175 warnIfCallingFromSystemProcess();
1176 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001177 String[] receiverPermissions = receiverPermission == null ? null
1178 : new String[] {receiverPermission};
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001179 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001180 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001181 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001182 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001183 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
Dianne Hackborna750a632015-06-16 17:18:23 -07001184 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001186 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188 }
1189
1190 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001191 public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001192 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001194 String[] receiverPermissions = receiverPermission == null ? null
1195 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001197 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001198 ActivityManager.getService().broadcastIntent(
Dianne Hackborna750a632015-06-16 17:18:23 -07001199 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001200 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001201 null, true, false, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001203 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205 }
1206
1207 @Override
1208 public void sendOrderedBroadcast(Intent intent,
1209 String receiverPermission, BroadcastReceiver resultReceiver,
1210 Handler scheduler, int initialCode, String initialData,
1211 Bundle initialExtras) {
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001212 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
Dianne Hackborna750a632015-06-16 17:18:23 -07001213 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1214 }
1215
1216 @Override
1217 public void sendOrderedBroadcast(Intent intent,
1218 String receiverPermission, Bundle options, BroadcastReceiver resultReceiver,
1219 Handler scheduler, int initialCode, String initialData,
1220 Bundle initialExtras) {
1221 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
1222 resultReceiver, scheduler, initialCode, initialData, initialExtras, options);
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001223 }
1224
1225 @Override
1226 public void sendOrderedBroadcast(Intent intent,
1227 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1228 Handler scheduler, int initialCode, String initialData,
1229 Bundle initialExtras) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001230 sendOrderedBroadcast(intent, receiverPermission, appOp,
1231 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1232 }
1233
1234 void sendOrderedBroadcast(Intent intent,
1235 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1236 Handler scheduler, int initialCode, String initialData,
1237 Bundle initialExtras, Bundle options) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001238 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001239 IIntentReceiver rd = null;
1240 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001241 if (mPackageInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 if (scheduler == null) {
1243 scheduler = mMainThread.getHandler();
1244 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001245 rd = mPackageInfo.getReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 resultReceiver, getOuterContext(), scheduler,
1247 mMainThread.getInstrumentation(), false);
1248 } else {
1249 if (scheduler == null) {
1250 scheduler = mMainThread.getHandler();
1251 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001252 rd = new LoadedApk.ReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1254 }
1255 }
1256 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001257 String[] receiverPermissions = receiverPermission == null ? null
1258 : new String[] {receiverPermission};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001260 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001261 ActivityManager.getService().broadcastIntent(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 mMainThread.getApplicationThread(), intent, resolvedType, rd,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001263 initialCode, initialData, initialExtras, receiverPermissions, appOp,
Dianne Hackborna750a632015-06-16 17:18:23 -07001264 options, true, false, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001266 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268 }
1269
1270 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001271 public void sendBroadcastAsUser(Intent intent, UserHandle user) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001272 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1273 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001274 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001275 ActivityManager.getService().broadcastIntent(mMainThread.getApplicationThread(),
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001276 intent, resolvedType, null, Activity.RESULT_OK, null, null, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001277 AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001278 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001279 throw e.rethrowFromSystemServer();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001280 }
1281 }
1282
1283 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001284 public void sendBroadcastAsUser(Intent intent, UserHandle user,
1285 String receiverPermission) {
Svet Ganov16a16892015-04-16 10:32:04 -07001286 sendBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE);
1287 }
1288
1289 @Override
Chad Brubaker52c8edc2016-07-25 14:30:26 -07001290 public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission,
1291 Bundle options) {
1292 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1293 String[] receiverPermissions = receiverPermission == null ? null
1294 : new String[] {receiverPermission};
1295 try {
1296 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001297 ActivityManager.getService().broadcastIntent(
Chad Brubaker52c8edc2016-07-25 14:30:26 -07001298 mMainThread.getApplicationThread(), intent, resolvedType, null,
1299 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE,
1300 options, false, false, user.getIdentifier());
1301 } catch (RemoteException e) {
1302 throw e.rethrowFromSystemServer();
1303 }
1304 }
1305
1306 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001307 public void sendBroadcastAsUser(Intent intent, UserHandle user,
1308 String receiverPermission, int appOp) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001309 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001310 String[] receiverPermissions = receiverPermission == null ? null
1311 : new String[] {receiverPermission};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001312 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001313 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001314 ActivityManager.getService().broadcastIntent(
Svet Ganov16a16892015-04-16 10:32:04 -07001315 mMainThread.getApplicationThread(), intent, resolvedType, null,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001316 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false,
Svet Ganov16a16892015-04-16 10:32:04 -07001317 user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001318 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001319 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001320 }
1321 }
1322
1323 @Override
Dianne Hackborn79af1dd2012-08-16 16:42:52 -07001324 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001325 String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001326 int initialCode, String initialData, Bundle initialExtras) {
Amith Yamasani3cf75722014-05-16 12:37:29 -07001327 sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001328 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
Amith Yamasani3cf75722014-05-16 12:37:29 -07001329 }
1330
1331 @Override
1332 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1333 String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001334 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
1335 sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp,
1336 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
1337 }
1338
1339 @Override
1340 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1341 String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver,
1342 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001343 IIntentReceiver rd = null;
1344 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001345 if (mPackageInfo != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001346 if (scheduler == null) {
1347 scheduler = mMainThread.getHandler();
1348 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001349 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001350 resultReceiver, getOuterContext(), scheduler,
1351 mMainThread.getInstrumentation(), false);
1352 } else {
1353 if (scheduler == null) {
1354 scheduler = mMainThread.getHandler();
1355 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001356 rd = new LoadedApk.ReceiverDispatcher(resultReceiver, getOuterContext(),
1357 scheduler, null, false).getIIntentReceiver();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001358 }
1359 }
1360 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001361 String[] receiverPermissions = receiverPermission == null ? null
1362 : new String[] {receiverPermission};
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001363 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001364 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001365 ActivityManager.getService().broadcastIntent(
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001366 mMainThread.getApplicationThread(), intent, resolvedType, rd,
Fyodor Kupolovd4fd8c72015-07-13 19:19:25 -07001367 initialCode, initialData, initialExtras, receiverPermissions,
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001368 appOp, options, true, false, user.getIdentifier());
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001369 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001370 throw e.rethrowFromSystemServer();
Dianne Hackborn7d19e022012-08-07 19:12:33 -07001371 }
1372 }
1373
1374 @Override
Jordan Liu54735532019-10-29 10:33:55 -07001375 public void sendOrderedBroadcast(Intent intent, String receiverPermission,
1376 String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler,
1377 int initialCode, String initialData, @Nullable Bundle initialExtras) {
1378 int intAppOp = AppOpsManager.OP_NONE;
1379 if (!TextUtils.isEmpty(receiverAppOp)) {
1380 intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1381 }
1382 sendOrderedBroadcastAsUser(intent, getUser(),
1383 receiverPermission, intAppOp, resultReceiver, scheduler, initialCode, initialData,
1384 initialExtras);
1385 }
1386
1387 @Override
Peter Wang7701f572019-11-07 16:57:23 -08001388 public void sendOrderedBroadcast(Intent intent, String receiverPermission, String receiverAppOp,
1389 Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode,
1390 String initialData, @Nullable Bundle initialExtras) {
1391 int intAppOp = AppOpsManager.OP_NONE;
1392 if (!TextUtils.isEmpty(receiverAppOp)) {
1393 intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1394 }
1395 sendOrderedBroadcastAsUser(intent, getUser(), receiverPermission, intAppOp, options,
1396 resultReceiver, scheduler, initialCode, initialData, initialExtras);
1397 }
1398
1399 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001400 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 public void sendStickyBroadcast(Intent intent) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001402 warnIfCallingFromSystemProcess();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1404 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001405 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001406 ActivityManager.getService().broadcastIntent(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 mMainThread.getApplicationThread(), intent, resolvedType, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001408 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001409 getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001411 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 }
1414
1415 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001416 @Deprecated
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001417 public void sendStickyOrderedBroadcast(Intent intent,
1418 BroadcastReceiver resultReceiver,
1419 Handler scheduler, int initialCode, String initialData,
1420 Bundle initialExtras) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001421 warnIfCallingFromSystemProcess();
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001422 IIntentReceiver rd = null;
1423 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001424 if (mPackageInfo != null) {
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001425 if (scheduler == null) {
1426 scheduler = mMainThread.getHandler();
1427 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001428 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001429 resultReceiver, getOuterContext(), scheduler,
1430 mMainThread.getInstrumentation(), false);
1431 } else {
1432 if (scheduler == null) {
1433 scheduler = mMainThread.getHandler();
1434 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001435 rd = new LoadedApk.ReceiverDispatcher(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001436 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1437 }
1438 }
1439 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1440 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001441 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001442 ActivityManager.getService().broadcastIntent(
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001443 mMainThread.getApplicationThread(), intent, resolvedType, rd,
1444 initialCode, initialData, initialExtras, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 AppOpsManager.OP_NONE, null, true, true, getUserId());
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001446 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001447 throw e.rethrowFromSystemServer();
Dianne Hackbornefa199f2009-09-19 12:03:15 -07001448 }
1449 }
1450
1451 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001452 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public void removeStickyBroadcast(Intent intent) {
1454 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1455 if (resolvedType != null) {
1456 intent = new Intent(intent);
1457 intent.setDataAndType(intent.getData(), resolvedType);
1458 }
1459 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001460 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001461 ActivityManager.getService().unbroadcastIntent(
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001462 mMainThread.getApplicationThread(), intent, getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001464 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
1466 }
1467
1468 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001469 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001470 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
1471 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1472 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001473 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001474 ActivityManager.getService().broadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001475 mMainThread.getApplicationThread(), intent, resolvedType, null,
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001476 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true,
1477 user.getIdentifier());
1478 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001479 throw e.rethrowFromSystemServer();
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001480 }
1481 }
1482
1483 @Override
1484 @Deprecated
1485 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options) {
1486 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1487 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001488 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001489 ActivityManager.getService().broadcastIntent(
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001490 mMainThread.getApplicationThread(), intent, resolvedType, null,
1491 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, options, false, true,
1492 user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001493 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001494 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001495 }
1496 }
1497
1498 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001499 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001500 public void sendStickyOrderedBroadcastAsUser(Intent intent,
1501 UserHandle user, BroadcastReceiver resultReceiver,
1502 Handler scheduler, int initialCode, String initialData,
1503 Bundle initialExtras) {
1504 IIntentReceiver rd = null;
1505 if (resultReceiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001506 if (mPackageInfo != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001507 if (scheduler == null) {
1508 scheduler = mMainThread.getHandler();
1509 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001510 rd = mPackageInfo.getReceiverDispatcher(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001511 resultReceiver, getOuterContext(), scheduler,
1512 mMainThread.getInstrumentation(), false);
1513 } else {
1514 if (scheduler == null) {
1515 scheduler = mMainThread.getHandler();
1516 }
1517 rd = new LoadedApk.ReceiverDispatcher(
1518 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1519 }
1520 }
1521 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1522 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001523 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001524 ActivityManager.getService().broadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001525 mMainThread.getApplicationThread(), intent, resolvedType, rd,
1526 initialCode, initialData, initialExtras, null,
Dianne Hackborna750a632015-06-16 17:18:23 -07001527 AppOpsManager.OP_NONE, null, true, true, user.getIdentifier());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001528 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001529 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001530 }
1531 }
1532
1533 @Override
Jeff Brown6e539312015-02-24 18:53:21 -08001534 @Deprecated
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001535 public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
1536 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1537 if (resolvedType != null) {
1538 intent = new Intent(intent);
1539 intent.setDataAndType(intent.getData(), resolvedType);
1540 }
1541 try {
Jeff Sharkey344744b2016-01-28 19:03:30 -07001542 intent.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001543 ActivityManager.getService().unbroadcastIntent(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001544 mMainThread.getApplicationThread(), intent, user.getIdentifier());
1545 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001546 throw e.rethrowFromSystemServer();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001547 }
1548 }
1549
1550 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1552 return registerReceiver(receiver, filter, null, null);
1553 }
1554
1555 @Override
1556 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001557 int flags) {
1558 return registerReceiver(receiver, filter, null, null, flags);
Chad Brubaker816c83b2017-03-02 10:27:59 -08001559 }
1560
1561 @Override
1562 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 String broadcastPermission, Handler scheduler) {
Jeff Sharkeyded653b2012-09-27 19:09:24 -07001564 return registerReceiverInternal(receiver, getUserId(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001565 filter, broadcastPermission, scheduler, getOuterContext(), 0);
Chad Brubaker816c83b2017-03-02 10:27:59 -08001566 }
1567
1568 @Override
1569 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001570 String broadcastPermission, Handler scheduler, int flags) {
Chad Brubaker816c83b2017-03-02 10:27:59 -08001571 return registerReceiverInternal(receiver, getUserId(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001572 filter, broadcastPermission, scheduler, getOuterContext(), flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574
Dianne Hackborn20e80982012-08-31 19:00:44 -07001575 @Override
Meng Wang3f9e0362019-11-05 10:43:45 -08001576 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
1577 IntentFilter filter, String broadcastPermission, Handler scheduler) {
1578 return registerReceiverAsUser(receiver, UserHandle.ALL,
1579 filter, broadcastPermission, scheduler);
1580 }
1581
1582 @Override
Dianne Hackborn20e80982012-08-31 19:00:44 -07001583 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
1584 IntentFilter filter, String broadcastPermission, Handler scheduler) {
1585 return registerReceiverInternal(receiver, user.getIdentifier(),
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001586 filter, broadcastPermission, scheduler, getOuterContext(), 0);
Dianne Hackborn20e80982012-08-31 19:00:44 -07001587 }
1588
1589 private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 IntentFilter filter, String broadcastPermission,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001591 Handler scheduler, Context context, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 IIntentReceiver rd = null;
1593 if (receiver != null) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001594 if (mPackageInfo != null && context != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (scheduler == null) {
1596 scheduler = mMainThread.getHandler();
1597 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001598 rd = mPackageInfo.getReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 receiver, context, scheduler,
1600 mMainThread.getInstrumentation(), true);
1601 } else {
1602 if (scheduler == null) {
1603 scheduler = mMainThread.getHandler();
1604 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001605 rd = new LoadedApk.ReceiverDispatcher(
Dianne Hackborn399cccb2010-04-13 22:57:49 -07001606 receiver, context, scheduler, null, true).getIIntentReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608 }
1609 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001610 final Intent intent = ActivityManager.getService().registerReceiver(
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001611 mMainThread.getApplicationThread(), mBasePackageName, rd, filter,
Chad Brubaker6d6015f2017-04-18 11:25:16 -07001612 broadcastPermission, userId, flags);
Jeff Sharkeyd136e512016-03-09 22:30:56 -07001613 if (intent != null) {
1614 intent.setExtrasClassLoader(getClassLoader());
1615 intent.prepareToEnterProcess();
1616 }
1617 return intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001619 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 }
1621 }
1622
1623 @Override
1624 public void unregisterReceiver(BroadcastReceiver receiver) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001625 if (mPackageInfo != null) {
1626 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 getOuterContext(), receiver);
1628 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001629 ActivityManager.getService().unregisterReceiver(rd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001631 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
1633 } else {
1634 throw new RuntimeException("Not supported in system context");
1635 }
1636 }
1637
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001638 private void validateServiceIntent(Intent service) {
1639 if (service.getComponent() == null && service.getPackage() == null) {
Dianne Hackborn955d8d62014-10-07 20:17:19 -07001640 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
Dianne Hackborn10ad9822014-03-17 11:28:36 -07001641 IllegalArgumentException ex = new IllegalArgumentException(
1642 "Service Intent must be explicit: " + service);
1643 throw ex;
1644 } else {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001645 Log.w(TAG, "Implicit intents with startService are not safe: " + service
1646 + " " + Debug.getCallers(2, 3));
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001647 }
1648 }
1649 }
1650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 @Override
1652 public ComponentName startService(Intent service) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001653 warnIfCallingFromSystemProcess();
Christopher Tate242ba3e92017-04-14 15:07:06 -07001654 return startServiceCommon(service, false, mUser);
Christopher Tate42a386b2016-11-07 12:21:21 -08001655 }
1656
1657 @Override
Christopher Tate79047c62017-03-21 11:37:06 -07001658 public ComponentName startForegroundService(Intent service) {
1659 warnIfCallingFromSystemProcess();
Christopher Tate242ba3e92017-04-14 15:07:06 -07001660 return startServiceCommon(service, true, mUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001661 }
1662
1663 @Override
1664 public boolean stopService(Intent service) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001665 warnIfCallingFromSystemProcess();
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001666 return stopServiceCommon(service, mUser);
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001667 }
1668
1669 @Override
1670 public ComponentName startServiceAsUser(Intent service, UserHandle user) {
Christopher Tate242ba3e92017-04-14 15:07:06 -07001671 return startServiceCommon(service, false, user);
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001672 }
1673
Christopher Tate42a386b2016-11-07 12:21:21 -08001674 @Override
Christopher Tate79047c62017-03-21 11:37:06 -07001675 public ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
Christopher Tate242ba3e92017-04-14 15:07:06 -07001676 return startServiceCommon(service, true, user);
Christopher Tate79047c62017-03-21 11:37:06 -07001677 }
1678
Christopher Tate242ba3e92017-04-14 15:07:06 -07001679 private ComponentName startServiceCommon(Intent service, boolean requireForeground,
1680 UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 try {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001682 validateServiceIntent(service);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001683 service.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001684 ComponentName cn = ActivityManager.getService().startService(
Svet Ganov99b60432015-06-27 13:15:22 -07001685 mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
Christopher Tate242ba3e92017-04-14 15:07:06 -07001686 getContentResolver()), requireForeground,
Christopher Tate79047c62017-03-21 11:37:06 -07001687 getOpPackageName(), user.getIdentifier());
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001688 if (cn != null) {
1689 if (cn.getPackageName().equals("!")) {
1690 throw new SecurityException(
1691 "Not allowed to start service " + service
1692 + " without permission " + cn.getClassName());
1693 } else if (cn.getPackageName().equals("!!")) {
1694 throw new SecurityException(
1695 "Unable to start service " + service
1696 + ": " + cn.getClassName());
Dianne Hackborn85e35642017-01-12 15:10:57 -08001697 } else if (cn.getPackageName().equals("?")) {
1698 throw new IllegalStateException(
1699 "Not allowed to start service " + service + ": " + cn.getClassName());
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07001700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 return cn;
1703 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001704 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
1707
1708 @Override
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001709 public boolean stopServiceAsUser(Intent service, UserHandle user) {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001710 return stopServiceCommon(service, user);
1711 }
1712
1713 private boolean stopServiceCommon(Intent service, UserHandle user) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 try {
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001715 validateServiceIntent(service);
Jeff Sharkey344744b2016-01-28 19:03:30 -07001716 service.prepareToLeaveProcess(this);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001717 int res = ActivityManager.getService().stopService(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 mMainThread.getApplicationThread(), service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -07001719 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 if (res < 0) {
1721 throw new SecurityException(
1722 "Not allowed to stop service " + service);
1723 }
1724 return res != 0;
1725 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001726 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 }
1728 }
1729
1730 @Override
Bo Liu58a57662019-03-06 20:21:45 +00001731 public boolean bindService(Intent service, ServiceConnection conn, int flags) {
Amith Yamasanicd757062012-10-19 18:23:52 -07001732 warnIfCallingFromSystemProcess();
Bo Liu58a57662019-03-06 20:21:45 +00001733 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null,
1734 getUser());
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001735 }
1736
1737 @Override
Bo Liu58a57662019-03-06 20:21:45 +00001738 public boolean bindService(
1739 Intent service, int flags, Executor executor, ServiceConnection conn) {
1740 warnIfCallingFromSystemProcess();
1741 return bindServiceCommon(service, conn, flags, null, null, executor, getUser());
1742 }
1743
1744 @Override
1745 public boolean bindIsolatedService(Intent service, int flags, String instanceName,
1746 Executor executor, ServiceConnection conn) {
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001747 warnIfCallingFromSystemProcess();
1748 if (instanceName == null) {
1749 throw new NullPointerException("null instanceName");
1750 }
Bo Liu58a57662019-03-06 20:21:45 +00001751 return bindServiceCommon(service, conn, flags, instanceName, null, executor, getUser());
Amith Yamasani37ce3a82012-02-06 12:04:42 -08001752 }
1753
1754 /** @hide */
1755 @Override
Amith Yamasani27b89e62013-01-16 12:30:11 -08001756 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
1757 UserHandle user) {
Bo Liu58a57662019-03-06 20:21:45 +00001758 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null, user);
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001759 }
1760
Adrian Roos691546e2016-02-09 10:13:41 -08001761 /** @hide */
1762 @Override
1763 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
1764 Handler handler, UserHandle user) {
1765 if (handler == null) {
1766 throw new IllegalArgumentException("handler must not be null.");
1767 }
Bo Liu58a57662019-03-06 20:21:45 +00001768 return bindServiceCommon(service, conn, flags, null, handler, null, user);
Adrian Roos691546e2016-02-09 10:13:41 -08001769 }
1770
Tony Mak46aabe52016-11-14 12:53:06 +00001771 /** @hide */
1772 @Override
1773 public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler,
1774 int flags) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00001775 return mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
Tony Mak46aabe52016-11-14 12:53:06 +00001776 }
1777
1778 /** @hide */
1779 @Override
1780 public IApplicationThread getIApplicationThread() {
1781 return mMainThread.getApplicationThread();
1782 }
1783
Tony Makbf9928d2016-12-22 11:02:45 +00001784 /** @hide */
1785 @Override
1786 public Handler getMainThreadHandler() {
1787 return mMainThread.getHandler();
1788 }
1789
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001790 private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
Bo Liu58a57662019-03-06 20:21:45 +00001791 String instanceName, Handler handler, Executor executor, UserHandle user) {
Tony Mak46aabe52016-11-14 12:53:06 +00001792 // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001793 IServiceConnection sd;
Christopher Tate79b33172012-06-18 14:54:21 -07001794 if (conn == null) {
1795 throw new IllegalArgumentException("connection is null");
1796 }
Bo Liu58a57662019-03-06 20:21:45 +00001797 if (handler != null && executor != null) {
1798 throw new IllegalArgumentException("Handler and Executor both supplied");
1799 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001800 if (mPackageInfo != null) {
Bo Liu58a57662019-03-06 20:21:45 +00001801 if (executor != null) {
1802 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
1803 } else {
1804 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
1805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 } else {
1807 throw new RuntimeException("Not supported in system context");
1808 }
Dianne Hackbornfd6c7b12013-10-03 10:42:26 -07001809 validateServiceIntent(service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001811 IBinder token = getActivityToken();
Todd Kennedy233a0b12018-01-29 20:30:24 +00001812 if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
1813 && mPackageInfo.getApplicationInfo().targetSdkVersion
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001814 < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1815 flags |= BIND_WAIVE_PRIORITY;
1816 }
Jeff Sharkey344744b2016-01-28 19:03:30 -07001817 service.prepareToLeaveProcess(this);
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001818 int res = ActivityManager.getService().bindIsolatedService(
Svet Ganov99b60432015-06-27 13:15:22 -07001819 mMainThread.getApplicationThread(), getActivityToken(), service,
1820 service.resolveTypeIfNeeded(getContentResolver()),
Dianne Hackborn27b4d942018-11-12 15:01:40 -08001821 sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (res < 0) {
1823 throw new SecurityException(
1824 "Not allowed to bind to service " + service);
1825 }
1826 return res != 0;
1827 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001828 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831
1832 @Override
Dianne Hackborna631d562018-11-20 15:58:15 -08001833 public void updateServiceGroup(@NonNull ServiceConnection conn, int group, int importance) {
1834 if (conn == null) {
1835 throw new IllegalArgumentException("connection is null");
1836 }
1837 if (mPackageInfo != null) {
Dianne Hackborn2f55e5a2018-11-30 16:31:31 -08001838 IServiceConnection sd = mPackageInfo.lookupServiceDispatcher(conn, getOuterContext());
1839 if (sd == null) {
1840 throw new IllegalArgumentException("ServiceConnection not currently bound: "
1841 + conn);
1842 }
Dianne Hackborna631d562018-11-20 15:58:15 -08001843 try {
1844 ActivityManager.getService().updateServiceGroup(sd, group, importance);
1845 } catch (RemoteException e) {
1846 throw e.rethrowFromSystemServer();
1847 }
1848 } else {
1849 throw new RuntimeException("Not supported in system context");
1850 }
1851 }
1852
1853 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 public void unbindService(ServiceConnection conn) {
Christopher Tate79b33172012-06-18 14:54:21 -07001855 if (conn == null) {
1856 throw new IllegalArgumentException("connection is null");
1857 }
Todd Kennedy233a0b12018-01-29 20:30:24 +00001858 if (mPackageInfo != null) {
1859 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 getOuterContext(), conn);
1861 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001862 ActivityManager.getService().unbindService(sd);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001864 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 }
1866 } else {
1867 throw new RuntimeException("Not supported in system context");
1868 }
1869 }
1870
1871 @Override
1872 public boolean startInstrumentation(ComponentName className,
1873 String profileFile, Bundle arguments) {
1874 try {
Dianne Hackborn9ecebbf2011-09-28 23:19:47 -04001875 if (arguments != null) {
1876 arguments.setAllowFds(false);
1877 }
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001878 return ActivityManager.getService().startInstrumentation(
Narayan Kamath8dcfefd2014-05-15 18:12:59 +01001879 className, profileFile, 0, arguments, null, null, getUserId(),
1880 null /* ABI override */);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001882 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
1885
1886 @Override
1887 public Object getSystemService(String name) {
Andrii Kulian4a316972020-01-21 21:41:38 -08001888 if (isUiComponent(name) && !isUiContext()) {
1889 Log.w(TAG, name + " should be accessed from Activity or other visual Context");
1890 }
Jeff Brown6e539312015-02-24 18:53:21 -08001891 return SystemServiceRegistry.getSystemService(this, name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
Jeff Brown6e539312015-02-24 18:53:21 -08001894 @Override
1895 public String getSystemServiceName(Class<?> serviceClass) {
1896 return SystemServiceRegistry.getSystemServiceName(serviceClass);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001897 }
1898
Andrii Kulian4a316972020-01-21 21:41:38 -08001899 boolean isUiContext() {
1900 return mIsSystemOrSystemUiContext || mIsUiContext;
1901 }
1902
1903 private static boolean isUiComponent(String name) {
1904 return WINDOW_SERVICE.equals(name) || LAYOUT_INFLATER_SERVICE.equals(name)
1905 || WALLPAPER_SERVICE.equals(name);
1906 }
1907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 @Override
1909 public int checkPermission(String permission, int pid, int uid) {
1910 if (permission == null) {
1911 throw new IllegalArgumentException("permission is null");
1912 }
1913
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001914 final IActivityManager am = ActivityManager.getService();
Jeff Sharkeyd69b0832017-01-23 11:37:24 -07001915 if (am == null) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001916 // Well this is super awkward; we somehow don't have an active
Jeff Sharkeyd69b0832017-01-23 11:37:24 -07001917 // ActivityManager instance. If we're testing a root or system
1918 // UID, then they totally have whatever permission this is.
1919 final int appId = UserHandle.getAppId(uid);
1920 if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
1921 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
1922 return PackageManager.PERMISSION_GRANTED;
1923 }
Erik Wolsheimere21576f2018-03-29 16:21:41 -07001924 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold "
1925 + permission);
1926 return PackageManager.PERMISSION_DENIED;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07001927 }
1928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 try {
Tim Murrayd06c6d292019-05-07 06:53:55 +00001930 return am.checkPermission(permission, pid, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001932 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934 }
1935
Dianne Hackbornff170242014-11-19 10:59:01 -08001936 /** @hide */
1937 @Override
1938 public int checkPermission(String permission, int pid, int uid, IBinder callerToken) {
1939 if (permission == null) {
1940 throw new IllegalArgumentException("permission is null");
1941 }
1942
1943 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001944 return ActivityManager.getService().checkPermissionWithToken(
Dianne Hackbornff170242014-11-19 10:59:01 -08001945 permission, pid, uid, callerToken);
1946 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07001947 throw e.rethrowFromSystemServer();
Dianne Hackbornff170242014-11-19 10:59:01 -08001948 }
1949 }
1950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 @Override
1952 public int checkCallingPermission(String permission) {
1953 if (permission == null) {
1954 throw new IllegalArgumentException("permission is null");
1955 }
1956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 int pid = Binder.getCallingPid();
1958 if (pid != Process.myPid()) {
Amith Yamasani742a6712011-05-04 14:49:28 -07001959 return checkPermission(permission, pid, Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961 return PackageManager.PERMISSION_DENIED;
1962 }
1963
1964 @Override
1965 public int checkCallingOrSelfPermission(String permission) {
1966 if (permission == null) {
1967 throw new IllegalArgumentException("permission is null");
1968 }
1969
1970 return checkPermission(permission, Binder.getCallingPid(),
1971 Binder.getCallingUid());
1972 }
1973
Svetoslavc6d1c342015-02-26 14:44:43 -08001974 @Override
1975 public int checkSelfPermission(String permission) {
1976 if (permission == null) {
1977 throw new IllegalArgumentException("permission is null");
1978 }
1979
1980 return checkPermission(permission, Process.myPid(), Process.myUid());
1981 }
1982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 private void enforce(
1984 String permission, int resultOfCheck,
1985 boolean selfToo, int uid, String message) {
1986 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1987 throw new SecurityException(
1988 (message != null ? (message + ": ") : "") +
1989 (selfToo
1990 ? "Neither user " + uid + " nor current process has "
Tim Murrayd06c6d292019-05-07 06:53:55 +00001991 : "uid " + uid + " does not have ") +
1992 permission +
1993 ".");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995 }
1996
Jeff Brown6e539312015-02-24 18:53:21 -08001997 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 public void enforcePermission(
1999 String permission, int pid, int uid, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002000 enforce(permission,
2001 checkPermission(permission, pid, uid),
2002 false,
2003 uid,
2004 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 }
2006
Jeff Brown6e539312015-02-24 18:53:21 -08002007 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 public void enforceCallingPermission(String permission, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002009 enforce(permission,
2010 checkCallingPermission(permission),
2011 false,
2012 Binder.getCallingUid(),
2013 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
2015
Jeff Brown6e539312015-02-24 18:53:21 -08002016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 public void enforceCallingOrSelfPermission(
2018 String permission, String message) {
Tim Murrayd06c6d292019-05-07 06:53:55 +00002019 enforce(permission,
2020 checkCallingOrSelfPermission(permission),
2021 true,
2022 Binder.getCallingUid(),
2023 message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
2025
2026 @Override
2027 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
2028 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002029 ActivityManager.getService().grantUriPermission(
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002030 mMainThread.getApplicationThread(), toPackage,
2031 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002033 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035 }
2036
2037 @Override
2038 public void revokeUriPermission(Uri uri, int modeFlags) {
2039 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002040 ActivityManager.getService().revokeUriPermission(
Dianne Hackborna47223f2017-03-30 13:49:13 -07002041 mMainThread.getApplicationThread(), null,
2042 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
2043 } catch (RemoteException e) {
2044 throw e.rethrowFromSystemServer();
2045 }
2046 }
2047
2048 @Override
2049 public void revokeUriPermission(String targetPackage, Uri uri, int modeFlags) {
2050 try {
2051 ActivityManager.getService().revokeUriPermission(
2052 mMainThread.getApplicationThread(), targetPackage,
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002053 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002055 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 }
2058
2059 @Override
2060 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002062 return ActivityManager.getService().checkUriPermission(
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002063 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
Dianne Hackbornff170242014-11-19 10:59:01 -08002064 resolveUserId(uri), null);
2065 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002066 throw e.rethrowFromSystemServer();
Dianne Hackbornff170242014-11-19 10:59:01 -08002067 }
2068 }
2069
2070 /** @hide */
2071 @Override
2072 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) {
2073 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08002074 return ActivityManager.getService().checkUriPermission(
Dianne Hackbornff170242014-11-19 10:59:01 -08002075 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
2076 resolveUserId(uri), callerToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 } catch (RemoteException e) {
Jeff Sharkeyf8880562016-02-26 13:03:01 -07002078 throw e.rethrowFromSystemServer();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
2081
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002082 private int resolveUserId(Uri uri) {
2083 return ContentProvider.getUserIdFromUri(uri, getUserId());
2084 }
2085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 @Override
2087 public int checkCallingUriPermission(Uri uri, int modeFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 int pid = Binder.getCallingPid();
2089 if (pid != Process.myPid()) {
2090 return checkUriPermission(uri, pid,
2091 Binder.getCallingUid(), modeFlags);
2092 }
2093 return PackageManager.PERMISSION_DENIED;
2094 }
2095
2096 @Override
2097 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
2098 return checkUriPermission(uri, Binder.getCallingPid(),
2099 Binder.getCallingUid(), modeFlags);
2100 }
2101
2102 @Override
2103 public int checkUriPermission(Uri uri, String readPermission,
2104 String writePermission, int pid, int uid, int modeFlags) {
Mitsuru Oshima569076c2009-07-02 20:06:08 -07002105 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
2107 + readPermission + " writePermission=" + writePermission
2108 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
2109 }
2110 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2111 if (readPermission == null
2112 || checkPermission(readPermission, pid, uid)
2113 == PackageManager.PERMISSION_GRANTED) {
2114 return PackageManager.PERMISSION_GRANTED;
2115 }
2116 }
2117 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2118 if (writePermission == null
2119 || checkPermission(writePermission, pid, uid)
2120 == PackageManager.PERMISSION_GRANTED) {
2121 return PackageManager.PERMISSION_GRANTED;
2122 }
2123 }
2124 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
2125 : PackageManager.PERMISSION_DENIED;
2126 }
2127
2128 private String uriModeFlagToString(int uriModeFlags) {
Jeff Sharkey846318a2014-04-04 12:12:41 -07002129 StringBuilder builder = new StringBuilder();
2130 if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2131 builder.append("read and ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
Jeff Sharkey846318a2014-04-04 12:12:41 -07002133 if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2134 builder.append("write and ");
2135 }
2136 if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
2137 builder.append("persistable and ");
2138 }
2139 if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
2140 builder.append("prefix and ");
2141 }
2142
2143 if (builder.length() > 5) {
2144 builder.setLength(builder.length() - 5);
2145 return builder.toString();
2146 } else {
2147 throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags);
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150
2151 private void enforceForUri(
2152 int modeFlags, int resultOfCheck, boolean selfToo,
2153 int uid, Uri uri, String message) {
2154 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
2155 throw new SecurityException(
2156 (message != null ? (message + ": ") : "") +
2157 (selfToo
2158 ? "Neither user " + uid + " nor current process has "
2159 : "User " + uid + " does not have ") +
2160 uriModeFlagToString(modeFlags) +
2161 " permission on " +
2162 uri +
2163 ".");
2164 }
2165 }
2166
Jeff Brown6e539312015-02-24 18:53:21 -08002167 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 public void enforceUriPermission(
2169 Uri uri, int pid, int uid, int modeFlags, String message) {
2170 enforceForUri(
2171 modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
2172 false, uid, uri, message);
2173 }
2174
Jeff Brown6e539312015-02-24 18:53:21 -08002175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 public void enforceCallingUriPermission(
2177 Uri uri, int modeFlags, String message) {
2178 enforceForUri(
2179 modeFlags, checkCallingUriPermission(uri, modeFlags),
Amith Yamasani742a6712011-05-04 14:49:28 -07002180 false,
2181 Binder.getCallingUid(), uri, message);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 }
2183
Jeff Brown6e539312015-02-24 18:53:21 -08002184 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 public void enforceCallingOrSelfUriPermission(
2186 Uri uri, int modeFlags, String message) {
2187 enforceForUri(
2188 modeFlags,
2189 checkCallingOrSelfUriPermission(uri, modeFlags), true,
2190 Binder.getCallingUid(), uri, message);
2191 }
2192
Jeff Brown6e539312015-02-24 18:53:21 -08002193 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 public void enforceUriPermission(
2195 Uri uri, String readPermission, String writePermission,
2196 int pid, int uid, int modeFlags, String message) {
2197 enforceForUri(modeFlags,
2198 checkUriPermission(
2199 uri, readPermission, writePermission, pid, uid,
2200 modeFlags),
2201 false,
2202 uid,
2203 uri,
2204 message);
2205 }
2206
Tom O'Neill365632e2013-09-09 09:34:58 -07002207 /**
2208 * Logs a warning if the system process directly called a method such as
2209 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
2210 * The "AsUser" variants allow us to properly enforce the user's restrictions.
2211 */
Amith Yamasanicd757062012-10-19 18:23:52 -07002212 private void warnIfCallingFromSystemProcess() {
2213 if (Process.myUid() == Process.SYSTEM_UID) {
2214 Slog.w(TAG, "Calling a method in the system process without a qualified user: "
Dianne Hackborn40e9f292012-11-27 19:12:23 -08002215 + Debug.getCallers(5));
Amith Yamasanicd757062012-10-19 18:23:52 -07002216 }
2217 }
2218
Todd Kennedy233a0b12018-01-29 20:30:24 +00002219 private static Resources createResources(IBinder activityToken, LoadedApk pi, String splitName,
Winson710e3ec2019-02-25 13:38:20 -08002220 int displayId, Configuration overrideConfig, CompatibilityInfo compatInfo) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002221 final String[] splitResDirs;
2222 final ClassLoader classLoader;
2223 try {
2224 splitResDirs = pi.getSplitPaths(splitName);
2225 classLoader = pi.getSplitClassLoader(splitName);
2226 } catch (NameNotFoundException e) {
2227 throw new RuntimeException(e);
2228 }
2229 return ResourcesManager.getInstance().getResources(activityToken,
2230 pi.getResDir(),
2231 splitResDirs,
Winson710e3ec2019-02-25 13:38:20 -08002232 pi.getOverlayDirs(),
Todd Kennedy233a0b12018-01-29 20:30:24 +00002233 pi.getApplicationInfo().sharedLibraryFiles,
2234 displayId,
2235 overrideConfig,
2236 compatInfo,
2237 classLoader);
2238 }
2239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 @Override
Svetoslav976e8bd2014-07-16 15:12:03 -07002241 public Context createApplicationContext(ApplicationInfo application, int flags)
2242 throws NameNotFoundException {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002243 LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(),
Svetoslav976e8bd2014-07-16 15:12:03 -07002244 flags | CONTEXT_REGISTER_PACKAGE);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002245 if (pi != null) {
Andrii Kulian4a316972020-01-21 21:41:38 -08002246 ContextImpl c = new ContextImpl(this, mMainThread, pi, null, null, mToken,
Makoto Onuki4becc352019-01-30 13:30:41 -08002247 new UserHandle(UserHandle.getUserId(application.uid)), flags, null, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002248
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002249 final int displayId = getDisplayId();
Winson710e3ec2019-02-25 13:38:20 -08002250
Andrii Kulian4a316972020-01-21 21:41:38 -08002251 c.setResources(createResources(mToken, pi, null, displayId, null,
Winson710e3ec2019-02-25 13:38:20 -08002252 getDisplayAdjustments(displayId).getCompatibilityInfo()));
Svetoslav976e8bd2014-07-16 15:12:03 -07002253 if (c.mResources != null) {
2254 return c;
2255 }
2256 }
2257
2258 throw new PackageManager.NameNotFoundException(
2259 "Application package " + application.packageName + " not found");
2260 }
2261
2262 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 public Context createPackageContext(String packageName, int flags)
Jeff Sharkey6d515712012-09-20 16:06:08 -07002264 throws NameNotFoundException {
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002265 return createPackageContextAsUser(packageName, flags, mUser);
Jeff Sharkey6d515712012-09-20 16:06:08 -07002266 }
2267
2268 @Override
2269 public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
2270 throws NameNotFoundException {
Kenny Guyc2a40602014-09-08 18:51:15 +00002271 if (packageName.equals("system") || packageName.equals("android")) {
Adam Lesinski8fa71072016-11-18 18:13:55 -08002272 // The system resources are loaded in every application, so we can safely copy
2273 // the context without reloading Resources.
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002274 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, null,
Andrii Kulian4a316972020-01-21 21:41:38 -08002275 mToken, user, flags, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002276 }
2277
Todd Kennedy233a0b12018-01-29 20:30:24 +00002278 LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
Dianne Hackbornfee756f2014-07-16 17:31:10 -07002279 flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
Todd Kennedy233a0b12018-01-29 20:30:24 +00002280 if (pi != null) {
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002281 ContextImpl c = new ContextImpl(this, mMainThread, pi, mFeatureId, null,
Andrii Kulian4a316972020-01-21 21:41:38 -08002282 mToken, user, flags, null, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002283
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002284 final int displayId = getDisplayId();
Adam Lesinski8fa71072016-11-18 18:13:55 -08002285
Andrii Kulian4a316972020-01-21 21:41:38 -08002286 c.setResources(createResources(mToken, pi, null, displayId, null,
Winson710e3ec2019-02-25 13:38:20 -08002287 getDisplayAdjustments(displayId).getCompatibilityInfo()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 if (c.mResources != null) {
2289 return c;
2290 }
2291 }
2292
2293 // Should be a better exception.
2294 throw new PackageManager.NameNotFoundException(
Jeff Browndefd4a62014-03-10 21:24:37 -07002295 "Application package " + packageName + " not found");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Romain Guy870e09f2009-07-06 16:35:25 -07002298 @Override
Makoto Onukie5449f02019-10-11 20:19:58 -07002299 public Context createContextAsUser(UserHandle user, @CreatePackageOptions int flags) {
Makoto Onukib8440012019-10-09 15:33:11 -07002300 try {
Makoto Onukie5449f02019-10-11 20:19:58 -07002301 return createPackageContextAsUser(getPackageName(), flags, user);
Makoto Onukib8440012019-10-09 15:33:11 -07002302 } catch (NameNotFoundException e) {
2303 throw new IllegalStateException("Own package not found: package=" + getPackageName());
2304 }
2305 }
2306
2307 @Override
Adam Lesinski4e862812016-11-21 16:02:24 -08002308 public Context createContextForSplit(String splitName) throws NameNotFoundException {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002309 if (!mPackageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
Adam Lesinski4e862812016-11-21 16:02:24 -08002310 // All Splits are always loaded.
2311 return this;
2312 }
2313
Todd Kennedy233a0b12018-01-29 20:30:24 +00002314 final ClassLoader classLoader = mPackageInfo.getSplitClassLoader(splitName);
2315 final String[] paths = mPackageInfo.getSplitPaths(splitName);
Adam Lesinski4e862812016-11-21 16:02:24 -08002316
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002317 final ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo,
Andrii Kulian4a316972020-01-21 21:41:38 -08002318 mFeatureId, splitName, mToken, mUser, mFlags, classLoader, null);
Adam Lesinski4e862812016-11-21 16:02:24 -08002319
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002320 final int displayId = getDisplayId();
Adam Lesinski4e862812016-11-21 16:02:24 -08002321
Todd Kennedy233a0b12018-01-29 20:30:24 +00002322 context.setResources(ResourcesManager.getInstance().getResources(
Andrii Kulian4a316972020-01-21 21:41:38 -08002323 mToken,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002324 mPackageInfo.getResDir(),
2325 paths,
2326 mPackageInfo.getOverlayDirs(),
2327 mPackageInfo.getApplicationInfo().sharedLibraryFiles,
2328 displayId,
2329 null,
2330 mPackageInfo.getCompatibilityInfo(),
2331 classLoader));
Adam Lesinski4e862812016-11-21 16:02:24 -08002332 return context;
2333 }
2334
2335 @Override
Dianne Hackborn756220b2012-08-14 16:45:30 -07002336 public Context createConfigurationContext(Configuration overrideConfiguration) {
Jeff Browna492c3a2012-08-23 19:48:44 -07002337 if (overrideConfiguration == null) {
2338 throw new IllegalArgumentException("overrideConfiguration must not be null");
2339 }
2340
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002341 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
Andrii Kulian4a316972020-01-21 21:41:38 -08002342 mSplitName, mToken, mUser, mFlags, mClassLoader, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002343
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002344 final int displayId = getDisplayId();
Andrii Kulian4a316972020-01-21 21:41:38 -08002345 context.setResources(createResources(mToken, mPackageInfo, mSplitName, displayId,
Winson710e3ec2019-02-25 13:38:20 -08002346 overrideConfiguration, getDisplayAdjustments(displayId).getCompatibilityInfo()));
Adam Lesinski8fa71072016-11-18 18:13:55 -08002347 return context;
Dianne Hackborn756220b2012-08-14 16:45:30 -07002348 }
2349
2350 @Override
Jeff Browna492c3a2012-08-23 19:48:44 -07002351 public Context createDisplayContext(Display display) {
2352 if (display == null) {
2353 throw new IllegalArgumentException("display must not be null");
2354 }
2355
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002356 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
Andrii Kulian4a316972020-01-21 21:41:38 -08002357 mSplitName, mToken, mUser, mFlags, mClassLoader, null);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002358
2359 final int displayId = display.getDisplayId();
Andrii Kulian4a316972020-01-21 21:41:38 -08002360 context.setResources(createResources(mToken, mPackageInfo, mSplitName, displayId,
Winson710e3ec2019-02-25 13:38:20 -08002361 null, getDisplayAdjustments(displayId).getCompatibilityInfo()));
Adam Lesinski8fa71072016-11-18 18:13:55 -08002362 context.mDisplay = display;
2363 return context;
Jeff Browna492c3a2012-08-23 19:48:44 -07002364 }
2365
Jeff Browna492c3a2012-08-23 19:48:44 -07002366 @Override
Andrii Kulian4a316972020-01-21 21:41:38 -08002367 public @NonNull WindowContext createWindowContext(int type) {
2368 if (getDisplay() == null) {
2369 throw new UnsupportedOperationException("WindowContext can only be created from "
2370 + "other visual contexts, such as Activity or one created with "
2371 + "Context#createDisplayContext(Display)");
2372 }
2373 return new WindowContext(this, null /* token */, type);
2374 }
2375
2376 ContextImpl createBaseWindowContext(IBinder token) {
2377 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId,
2378 mSplitName, token, mUser, mFlags, mClassLoader, null);
2379 context.mIsUiContext = true;
2380 return context;
2381 }
2382
2383 @Override
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002384 public @NonNull Context createFeatureContext(@Nullable String featureId) {
2385 return new ContextImpl(this, mMainThread, mPackageInfo, featureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002386 mToken, mUser, mFlags, mClassLoader, null);
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002387 }
2388
2389 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002390 public Context createDeviceProtectedStorageContext() {
2391 final int flags = (mFlags & ~Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE)
2392 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002393 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002394 mToken, mUser, flags, mClassLoader, null);
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002395 }
2396
2397 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002398 public Context createCredentialProtectedStorageContext() {
2399 final int flags = (mFlags & ~Context.CONTEXT_DEVICE_PROTECTED_STORAGE)
2400 | Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002401 return new ContextImpl(this, mMainThread, mPackageInfo, mFeatureId, mSplitName,
Andrii Kulian4a316972020-01-21 21:41:38 -08002402 mToken, mUser, flags, mClassLoader, null);
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002403 }
2404
2405 @Override
Romain Guy870e09f2009-07-06 16:35:25 -07002406 public boolean isRestricted() {
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002407 return (mFlags & Context.CONTEXT_RESTRICTED) != 0;
2408 }
2409
2410 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002411 public boolean isDeviceProtectedStorage() {
2412 return (mFlags & Context.CONTEXT_DEVICE_PROTECTED_STORAGE) != 0;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002413 }
2414
2415 @Override
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002416 public boolean isCredentialProtectedStorage() {
2417 return (mFlags & Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE) != 0;
Romain Guy870e09f2009-07-06 16:35:25 -07002418 }
2419
Jeff Brown98365d72012-08-19 20:30:52 -07002420 @Override
Seigo Nonaka6d6cd682017-06-22 08:22:18 -07002421 public boolean canLoadUnsafeResources() {
2422 if (getPackageName().equals(getOpPackageName())) {
2423 return true;
2424 }
2425 return (mFlags & Context.CONTEXT_IGNORE_SECURITY) != 0;
2426 }
2427
2428 @Override
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002429 public Display getDisplay() {
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002430 if (mDisplay == null) {
2431 return mResourcesManager.getAdjustedDisplay(Display.DEFAULT_DISPLAY,
Bryce Lee609bf652017-02-09 16:50:13 -08002432 mResources);
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002433 }
2434
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002435 return mDisplay;
2436 }
2437
2438 @Override
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002439 public int getDisplayId() {
Andrii Kulian4a316972020-01-21 21:41:38 -08002440 final Display display = getDisplay();
2441 return display != null ? display.getDisplayId() : Display.DEFAULT_DISPLAY;
Yohei Yukawa5281b6b2018-10-15 07:38:25 +08002442 }
2443
2444 @Override
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002445 public void updateDisplay(int displayId) {
Bryce Lee609bf652017-02-09 16:50:13 -08002446 mDisplay = mResourcesManager.getAdjustedDisplay(displayId, mResources);
Andrii Kulianb047b8b2017-02-08 18:38:26 -08002447 }
2448
2449 @Override
Craig Mautner48d0d182013-06-11 07:53:06 -07002450 public DisplayAdjustments getDisplayAdjustments(int displayId) {
Adam Lesinski4ece3d62016-06-16 18:05:41 -07002451 return mResources.getDisplayAdjustments();
Jeff Brown98365d72012-08-19 20:30:52 -07002452 }
2453
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -07002454 @Override
2455 public File getDataDir() {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002456 if (mPackageInfo != null) {
Jeff Sharkey35871f22016-01-29 17:13:29 -07002457 File res = null;
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002458 if (isCredentialProtectedStorage()) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002459 res = mPackageInfo.getCredentialProtectedDataDirFile();
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002460 } else if (isDeviceProtectedStorage()) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002461 res = mPackageInfo.getDeviceProtectedDataDirFile();
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002462 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002463 res = mPackageInfo.getDataDirFile();
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002464 }
Jeff Sharkey35871f22016-01-29 17:13:29 -07002465
2466 if (res != null) {
Jeff Sharkey21f50722016-04-27 12:38:02 -06002467 if (!res.exists() && android.os.Process.myUid() == android.os.Process.SYSTEM_UID) {
Jeff Sharkey24492ae2016-04-25 13:20:25 -06002468 Log.wtf(TAG, "Data directory doesn't exist for package " + getPackageName(),
2469 new Throwable());
2470 }
Jeff Sharkey35871f22016-01-29 17:13:29 -07002471 return res;
2472 } else {
2473 throw new RuntimeException(
2474 "No data directory found for package " + getPackageName());
2475 }
2476 } else {
2477 throw new RuntimeException(
2478 "No package details found for package " + getPackageName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
2481
2482 @Override
2483 public File getDir(String name, int mode) {
Jeff Sharkey634dc422016-01-30 17:44:15 -07002484 checkMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002485 name = "app_" + name;
Jeff Sharkey2c1ba9a2016-02-17 15:29:38 -07002486 File file = makeFilename(getDataDir(), name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 if (!file.exists()) {
2488 file.mkdir();
2489 setFilePermissionsFromMode(file.getPath(), mode,
2490 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
2491 }
2492 return file;
2493 }
2494
Jeff Sharkeyded653b2012-09-27 19:09:24 -07002495 /** {@hide} */
Jeff Brown6e539312015-02-24 18:53:21 -08002496 @Override
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002497 public UserHandle getUser() {
2498 return mUser;
2499 }
2500
2501 /** {@hide} */
2502 @Override
Jeff Sharkeyded653b2012-09-27 19:09:24 -07002503 public int getUserId() {
2504 return mUser.getIdentifier();
2505 }
2506
Felipe Lemebb567ae2017-10-04 09:56:21 -07002507 /** @hide */
2508 @Override
2509 public AutofillClient getAutofillClient() {
2510 return mAutofillClient;
2511 }
2512
2513 /** @hide */
2514 @Override
2515 public void setAutofillClient(AutofillClient client) {
2516 mAutofillClient = client;
2517 }
2518
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002519 /** @hide */
2520 @Override
Felipe Lemea4f39cd2019-02-19 15:08:59 -08002521 public AutofillOptions getAutofillOptions() {
2522 return mAutofillOptions;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002523 }
2524
2525 /** @hide */
2526 @Override
Felipe Lemea4f39cd2019-02-19 15:08:59 -08002527 public void setAutofillOptions(AutofillOptions options) {
2528 mAutofillOptions = options;
Svetoslav Ganov24c90452017-12-27 15:17:14 -08002529 }
2530
Felipe Lemeecb08be2018-11-27 15:48:47 -08002531 /** @hide */
2532 @Override
Felipe Leme326f15a2019-02-19 09:42:24 -08002533 public ContentCaptureOptions getContentCaptureOptions() {
2534 return mContentCaptureOptions;
Felipe Lemeecb08be2018-11-27 15:48:47 -08002535 }
2536
2537 /** @hide */
2538 @Override
Felipe Leme326f15a2019-02-19 09:42:24 -08002539 public void setContentCaptureOptions(ContentCaptureOptions options) {
2540 mContentCaptureOptions = options;
Felipe Lemeecb08be2018-11-27 15:48:47 -08002541 }
2542
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002543 @UnsupportedAppUsage
Dianne Hackborn21556372010-02-04 16:34:40 -08002544 static ContextImpl createSystemContext(ActivityThread mainThread) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002545 LoadedApk packageInfo = new LoadedApk(mainThread);
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002546 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
2547 0, null, null);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002548 context.setResources(packageInfo.getResources());
Jeff Browndefd4a62014-03-10 21:24:37 -07002549 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
Adam Lesinski7f3f4992016-03-30 10:32:15 -07002550 context.mResourcesManager.getDisplayMetrics());
Andrii Kulian4a316972020-01-21 21:41:38 -08002551 context.mIsSystemOrSystemUiContext = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 return context;
2553 }
2554
Adam Lesinskia82b6262017-03-21 16:56:17 -07002555 /**
2556 * System Context to be used for UI. This Context has resources that can be themed.
Adam Lesinski6f1a9172017-04-10 16:35:19 -07002557 * Make sure that the created system UI context shares the same LoadedApk as the system context.
lumark0b05f9e2018-11-26 15:09:06 +08002558 * @param systemContext The system context which created by
2559 * {@link #createSystemContext(ActivityThread)}.
2560 * @param displayId The ID of the display where the UI is shown.
Adam Lesinskia82b6262017-03-21 16:56:17 -07002561 */
lumark0b05f9e2018-11-26 15:09:06 +08002562 static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002563 final LoadedApk packageInfo = systemContext.mPackageInfo;
2564 ContextImpl context = new ContextImpl(null, systemContext.mMainThread, packageInfo, null,
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002565 null, null, null, 0, null, null);
lumark0b05f9e2018-11-26 15:09:06 +08002566 context.setResources(createResources(null, packageInfo, null, displayId, null,
Winson710e3ec2019-02-25 13:38:20 -08002567 packageInfo.getCompatibilityInfo()));
lumark0b05f9e2018-11-26 15:09:06 +08002568 context.updateDisplay(displayId);
Andrii Kulian4a316972020-01-21 21:41:38 -08002569 context.mIsSystemOrSystemUiContext = true;
Adam Lesinskia82b6262017-03-21 16:56:17 -07002570 return context;
2571 }
2572
lumark0b05f9e2018-11-26 15:09:06 +08002573 /**
2574 * The overloaded method of {@link #createSystemUiContext(ContextImpl, int)}.
2575 * Uses {@Code Display.DEFAULT_DISPLAY} as the target display.
2576 */
2577 static ContextImpl createSystemUiContext(ContextImpl systemContext) {
2578 return createSystemUiContext(systemContext, Display.DEFAULT_DISPLAY);
2579 }
2580
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002581 @UnsupportedAppUsage
Todd Kennedy233a0b12018-01-29 20:30:24 +00002582 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
Makoto Onuki4becc352019-01-30 13:30:41 -08002583 return createAppContext(mainThread, packageInfo, null);
2584 }
2585
2586 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
2587 String opPackageName) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002588 if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002589 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, null,
2590 0, null, opPackageName);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002591 context.setResources(packageInfo.getResources());
Adam Lesinski8fa71072016-11-18 18:13:55 -08002592 return context;
Jeff Browndefd4a62014-03-10 21:24:37 -07002593 }
2594
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002595 @UnsupportedAppUsage
Jeff Browndefd4a62014-03-10 21:24:37 -07002596 static ContextImpl createActivityContext(ActivityThread mainThread,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002597 LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
Adam Lesinski082614c2016-03-04 14:33:47 -08002598 Configuration overrideConfiguration) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002599 if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
Adam Lesinski8fa71072016-11-18 18:13:55 -08002600
Todd Kennedy233a0b12018-01-29 20:30:24 +00002601 String[] splitDirs = packageInfo.getSplitResDirs();
2602 ClassLoader classLoader = packageInfo.getClassLoader();
Adam Lesinski4e862812016-11-21 16:02:24 -08002603
Todd Kennedy233a0b12018-01-29 20:30:24 +00002604 if (packageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
Adam Lesinski4e862812016-11-21 16:02:24 -08002605 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "SplitDependencies");
2606 try {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002607 classLoader = packageInfo.getSplitClassLoader(activityInfo.splitName);
2608 splitDirs = packageInfo.getSplitPaths(activityInfo.splitName);
Adam Lesinski4e862812016-11-21 16:02:24 -08002609 } catch (NameNotFoundException e) {
2610 // Nothing above us can handle a NameNotFoundException, better crash.
2611 throw new RuntimeException(e);
2612 } finally {
2613 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2614 }
2615 }
2616
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002617 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null,
2618 activityInfo.splitName, activityToken, null, 0, classLoader, null);
Andrii Kulian4a316972020-01-21 21:41:38 -08002619 context.mIsUiContext = true;
Adam Lesinski8fa71072016-11-18 18:13:55 -08002620
2621 // Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY.
2622 displayId = (displayId != Display.INVALID_DISPLAY) ? displayId : Display.DEFAULT_DISPLAY;
2623
2624 final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY)
Todd Kennedy233a0b12018-01-29 20:30:24 +00002625 ? packageInfo.getCompatibilityInfo()
Adam Lesinski8fa71072016-11-18 18:13:55 -08002626 : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
2627
Adam Lesinskic9701942016-11-28 19:44:19 -08002628 final ResourcesManager resourcesManager = ResourcesManager.getInstance();
2629
2630 // Create the base resources for which all configuration contexts for this Activity
2631 // will be rebased upon.
Jason Monkbd983642017-02-24 16:57:40 -05002632 context.setResources(resourcesManager.createBaseActivityResources(activityToken,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002633 packageInfo.getResDir(),
Adam Lesinski4e862812016-11-21 16:02:24 -08002634 splitDirs,
Todd Kennedy233a0b12018-01-29 20:30:24 +00002635 packageInfo.getOverlayDirs(),
2636 packageInfo.getApplicationInfo().sharedLibraryFiles,
Adam Lesinskic9701942016-11-28 19:44:19 -08002637 displayId,
2638 overrideConfiguration,
2639 compatInfo,
Jason Monkbd983642017-02-24 16:57:40 -05002640 classLoader));
Adam Lesinskic9701942016-11-28 19:44:19 -08002641 context.mDisplay = resourcesManager.getAdjustedDisplay(displayId,
Bryce Lee609bf652017-02-09 16:50:13 -08002642 context.getResources());
Adam Lesinski8fa71072016-11-18 18:13:55 -08002643 return context;
Jeff Browndefd4a62014-03-10 21:24:37 -07002644 }
2645
Adam Lesinski1665d0f2017-03-10 14:46:57 -08002646 private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002647 @NonNull LoadedApk packageInfo, @Nullable String featureId,
2648 @Nullable String splitName, @Nullable IBinder activityToken, @Nullable UserHandle user,
2649 int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 mOuterContext = this;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002652 // If creator didn't specify which storage to use, use the default
2653 // location for application.
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002654 if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
2655 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002656 final File dataDir = packageInfo.getDataDirFile();
2657 if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) {
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002658 flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
Todd Kennedy233a0b12018-01-29 20:30:24 +00002659 } else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) {
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002660 flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002661 }
2662 }
2663
Jeff Browndefd4a62014-03-10 21:24:37 -07002664 mMainThread = mainThread;
Andrii Kulian4a316972020-01-21 21:41:38 -08002665 mToken = activityToken;
Jeff Sharkey7a30a302015-12-08 14:20:06 -07002666 mFlags = flags;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667
Jeff Browndefd4a62014-03-10 21:24:37 -07002668 if (user == null) {
2669 user = Process.myUserHandle();
2670 }
2671 mUser = user;
Mitsuru Oshimaba3ba572009-07-08 18:49:26 -07002672
Todd Kennedy233a0b12018-01-29 20:30:24 +00002673 mPackageInfo = packageInfo;
Adam Lesinski1665d0f2017-03-10 14:46:57 -08002674 mSplitName = splitName;
Adam Lesinski4e862812016-11-21 16:02:24 -08002675 mClassLoader = classLoader;
Jeff Browndefd4a62014-03-10 21:24:37 -07002676 mResourcesManager = ResourcesManager.getInstance();
Jeff Browndefd4a62014-03-10 21:24:37 -07002677
Makoto Onuki4becc352019-01-30 13:30:41 -08002678 String opPackageName;
2679
Jeff Browndefd4a62014-03-10 21:24:37 -07002680 if (container != null) {
2681 mBasePackageName = container.mBasePackageName;
Makoto Onuki4becc352019-01-30 13:30:41 -08002682 opPackageName = container.mOpPackageName;
Jason Monkbd983642017-02-24 16:57:40 -05002683 setResources(container.mResources);
Adam Lesinski8fa71072016-11-18 18:13:55 -08002684 mDisplay = container.mDisplay;
Andrii Kulian4a316972020-01-21 21:41:38 -08002685 mIsSystemOrSystemUiContext = container.mIsSystemOrSystemUiContext;
Dianne Hackborn95d78532013-09-11 09:51:14 -07002686 } else {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002687 mBasePackageName = packageInfo.mPackageName;
2688 ApplicationInfo ainfo = packageInfo.getApplicationInfo();
Dianne Hackborn95d78532013-09-11 09:51:14 -07002689 if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
2690 // Special case: system components allow themselves to be loaded in to other
2691 // processes. For purposes of app ops, we must then consider the context as
2692 // belonging to the package of this process, not the system itself, otherwise
2693 // the package+uid verifications in app ops will fail.
Makoto Onuki4becc352019-01-30 13:30:41 -08002694 opPackageName = ActivityThread.currentPackageName();
Dianne Hackborn95d78532013-09-11 09:51:14 -07002695 } else {
Makoto Onuki4becc352019-01-30 13:30:41 -08002696 opPackageName = mBasePackageName;
Dianne Hackborn95d78532013-09-11 09:51:14 -07002697 }
2698 }
Xin Guan2bcb97b2014-09-10 15:24:30 -05002699
Makoto Onuki4becc352019-01-30 13:30:41 -08002700 mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName;
Philip P. Moltmann59076d82019-08-19 15:00:40 -07002701 mFeatureId = featureId;
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002702 mContentResolver = new ApplicationContentResolver(this, mainThread);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704
Jason Monkbd983642017-02-24 16:57:40 -05002705 void setResources(Resources r) {
Jason Monkbd60e5b2017-03-02 12:55:00 -05002706 if (r instanceof CompatResources) {
2707 ((CompatResources) r).setContext(this);
Jason Monkbd983642017-02-24 16:57:40 -05002708 }
Jason Monkbd60e5b2017-03-02 12:55:00 -05002709 mResources = r;
Jason Monkbd983642017-02-24 16:57:40 -05002710 }
2711
Narayan Kamath29564cd2014-08-07 10:57:40 +01002712 void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
Todd Kennedy233a0b12018-01-29 20:30:24 +00002713 mPackageInfo.installSystemApplicationInfo(info, classLoader);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
2715
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002716 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 final void scheduleFinalCleanup(String who, String what) {
2718 mMainThread.scheduleContextCleanup(this, who, what);
2719 }
2720
2721 final void performFinalCleanup(String who, String what) {
2722 //Log.i(TAG, "Cleanup up context: " + this);
Todd Kennedy233a0b12018-01-29 20:30:24 +00002723 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
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 Context getReceiverRestrictedContext() {
2728 if (mReceiverRestrictedContext != null) {
2729 return mReceiverRestrictedContext;
2730 }
2731 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
2732 }
2733
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002734 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 final void setOuterContext(Context context) {
2736 mOuterContext = context;
2737 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002738
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002739 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 final Context getOuterContext() {
2741 return mOuterContext;
2742 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002743
Tony Mak46aabe52016-11-14 12:53:06 +00002744 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002745 @UnsupportedAppUsage
Tony Mak46aabe52016-11-14 12:53:06 +00002746 public IBinder getActivityToken() {
Andrii Kulian4a316972020-01-21 21:41:38 -08002747 return mToken;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 }
2749
Jeff Sharkey634dc422016-01-30 17:44:15 -07002750 private void checkMode(int mode) {
2751 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
2752 if ((mode & MODE_WORLD_READABLE) != 0) {
2753 throw new SecurityException("MODE_WORLD_READABLE no longer supported");
2754 }
2755 if ((mode & MODE_WORLD_WRITEABLE) != 0) {
2756 throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported");
2757 }
2758 }
2759 }
2760
Jeff Brown6e539312015-02-24 18:53:21 -08002761 @SuppressWarnings("deprecation")
Brad Fitzpatrickd3da4402010-11-10 08:27:11 -08002762 static void setFilePermissionsFromMode(String name, int mode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 int extraPermissions) {
2764 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
2765 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
2766 |extraPermissions;
2767 if ((mode&MODE_WORLD_READABLE) != 0) {
2768 perms |= FileUtils.S_IROTH;
2769 }
2770 if ((mode&MODE_WORLD_WRITEABLE) != 0) {
2771 perms |= FileUtils.S_IWOTH;
2772 }
Mitsuru Oshima569076c2009-07-02 20:06:08 -07002773 if (DEBUG) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
2775 + ", perms=0x" + Integer.toHexString(perms));
2776 }
2777 FileUtils.setPermissions(name, perms, -1, -1);
2778 }
2779
2780 private File makeFilename(File base, String name) {
2781 if (name.indexOf(File.separatorChar) < 0) {
Jeff Sharkeydd02e332018-06-27 14:41:57 -06002782 final File res = new File(base, name);
2783 // We report as filesystem access here to give us the best shot at
2784 // detecting apps that will pass the path down to native code.
2785 BlockGuard.getVmPolicy().onPathAccess(res.getPath());
2786 return res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 }
2788 throw new IllegalArgumentException(
Oscar Montemayora8529f62009-11-18 10:14:20 -08002789 "File " + name + " contains a path separator");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 }
2791
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002792 /**
2793 * Ensure that given directories exist, trying to create them if missing. If
2794 * unable to create, they are filtered by replacing with {@code null}.
2795 */
Jeff Sharkey35871f22016-01-29 17:13:29 -07002796 private File[] ensureExternalDirsExistOrFilter(File[] dirs) {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002797 final StorageManager sm = getSystemService(StorageManager.class);
2798 final File[] result = new File[dirs.length];
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002799 for (int i = 0; i < dirs.length; i++) {
2800 File dir = dirs[i];
2801 if (!dir.exists()) {
2802 if (!dir.mkdirs()) {
Christopher Tatecc866da2013-10-02 18:11:01 -07002803 // recheck existence in case of cross-process race
2804 if (!dir.exists()) {
2805 // Failing to mkdir() may be okay, since we might not have
2806 // enough permissions; ask vold to create on our behalf.
Christopher Tatecc866da2013-10-02 18:11:01 -07002807 try {
Jeff Sharkeyae266462017-11-27 13:32:24 -07002808 sm.mkdirs(dir);
Jeff Sharkey983294592015-07-13 10:25:31 -07002809 } catch (Exception e) {
2810 Log.w(TAG, "Failed to ensure " + dir + ": " + e);
Christopher Tatecc866da2013-10-02 18:11:01 -07002811 dir = null;
2812 }
Jeff Sharkey2d8b4e82013-09-17 17:30:33 -07002813 }
Jeff Sharkey1abdb712013-08-11 16:28:14 -07002814 }
2815 }
2816 result[i] = dir;
2817 }
2818 return result;
2819 }
2820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 // ----------------------------------------------------------------------
2822 // ----------------------------------------------------------------------
2823 // ----------------------------------------------------------------------
2824
2825 private static final class ApplicationContentResolver extends ContentResolver {
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002826 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07002827 private final ActivityThread mMainThread;
Jeff Sharkey6d515712012-09-20 16:06:08 -07002828
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002829 public ApplicationContentResolver(Context context, ActivityThread mainThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 super(context);
Daulet Zhanguzin0af97d62019-12-30 15:41:28 +00002831 mMainThread = Objects.requireNonNull(mainThread);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 }
2833
2834 @Override
Mathew Inwood61e8ae62018-08-14 14:17:44 +01002835 @UnsupportedAppUsage
Jeff Sharkey6d515712012-09-20 16:06:08 -07002836 protected IContentProvider acquireProvider(Context context, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002837 return mMainThread.acquireProvider(context,
2838 ContentProvider.getAuthorityWithoutUserId(auth),
2839 resolveUserIdFromAuthority(auth), true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 }
2841
2842 @Override
Jeff Sharkey6d515712012-09-20 16:06:08 -07002843 protected IContentProvider acquireExistingProvider(Context context, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002844 return mMainThread.acquireExistingProvider(context,
2845 ContentProvider.getAuthorityWithoutUserId(auth),
2846 resolveUserIdFromAuthority(auth), true);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07002847 }
2848
2849 @Override
2850 public boolean releaseProvider(IContentProvider provider) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07002851 return mMainThread.releaseProvider(provider, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 }
Christian Mehlmauer5f5acca2010-06-25 19:06:18 +02002853
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002854 @Override
Jeff Sharkey6d515712012-09-20 16:06:08 -07002855 protected IContentProvider acquireUnstableProvider(Context c, String auth) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002856 return mMainThread.acquireProvider(c,
2857 ContentProvider.getAuthorityWithoutUserId(auth),
2858 resolveUserIdFromAuthority(auth), false);
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002859 }
2860
2861 @Override
2862 public boolean releaseUnstableProvider(IContentProvider icp) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07002863 return mMainThread.releaseProvider(icp, false);
2864 }
2865
2866 @Override
2867 public void unstableProviderDied(IContentProvider icp) {
2868 mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
Dianne Hackborn652b6d12012-05-09 18:18:40 -07002869 }
Jeff Sharkey7aa76012013-09-30 14:26:27 -07002870
2871 @Override
2872 public void appNotRespondingViaProvider(IContentProvider icp) {
2873 mMainThread.appNotRespondingViaProvider(icp.asBinder());
2874 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002875
2876 /** @hide */
2877 protected int resolveUserIdFromAuthority(String auth) {
Jeff Sharkeyad357d12018-02-02 13:25:31 -07002878 return ContentProvider.getUserIdFromAuthority(auth, getUserId());
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881}