1 /*
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 
17 package android.app;
18 
19 import static android.content.pm.PackageManager.PERMISSION_DENIED;
20 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
21 import static android.os.StrictMode.vmIncorrectContextUseEnabled;
22 import static android.permission.flags.Flags.shouldRegisterAttributionSource;
23 import static android.view.WindowManager.LayoutParams.WindowType;
24 
25 import android.Manifest;
26 import android.annotation.CallbackExecutor;
27 import android.annotation.IntDef;
28 import android.annotation.NonNull;
29 import android.annotation.Nullable;
30 import android.annotation.SuppressLint;
31 import android.annotation.UiContext;
32 import android.companion.virtual.VirtualDevice;
33 import android.companion.virtual.VirtualDeviceManager;
34 import android.compat.annotation.UnsupportedAppUsage;
35 import android.content.AttributionSource;
36 import android.content.AutofillOptions;
37 import android.content.BroadcastReceiver;
38 import android.content.ComponentName;
39 import android.content.ContentCaptureOptions;
40 import android.content.ContentProvider;
41 import android.content.ContentResolver;
42 import android.content.Context;
43 import android.content.ContextParams;
44 import android.content.ContextWrapper;
45 import android.content.IContentProvider;
46 import android.content.IIntentReceiver;
47 import android.content.Intent;
48 import android.content.IntentFilter;
49 import android.content.IntentSender;
50 import android.content.ReceiverCallNotAllowedException;
51 import android.content.ServiceConnection;
52 import android.content.SharedPreferences;
53 import android.content.pm.ActivityInfo;
54 import android.content.pm.ApplicationInfo;
55 import android.content.pm.IPackageManager;
56 import android.content.pm.PackageManager;
57 import android.content.pm.PackageManager.NameNotFoundException;
58 import android.content.res.AssetManager;
59 import android.content.res.CompatResources;
60 import android.content.res.CompatibilityInfo;
61 import android.content.res.Configuration;
62 import android.content.res.Resources;
63 import android.content.res.loader.ResourcesLoader;
64 import android.database.DatabaseErrorHandler;
65 import android.database.sqlite.SQLiteDatabase;
66 import android.database.sqlite.SQLiteDatabase.CursorFactory;
67 import android.graphics.Bitmap;
68 import android.graphics.drawable.Drawable;
69 import android.net.Uri;
70 import android.os.Binder;
71 import android.os.Build;
72 import android.os.Bundle;
73 import android.os.Debug;
74 import android.os.Environment;
75 import android.os.FileUtils;
76 import android.os.Handler;
77 import android.os.IBinder;
78 import android.os.Looper;
79 import android.os.Process;
80 import android.os.RemoteException;
81 import android.os.StrictMode;
82 import android.os.Trace;
83 import android.os.UserHandle;
84 import android.os.UserManager;
85 import android.os.storage.StorageManager;
86 import android.permission.PermissionControllerManager;
87 import android.permission.PermissionManager;
88 import android.system.ErrnoException;
89 import android.system.Os;
90 import android.system.OsConstants;
91 import android.system.StructStat;
92 import android.text.TextUtils;
93 import android.util.AndroidRuntimeException;
94 import android.util.ArrayMap;
95 import android.util.Log;
96 import android.util.Slog;
97 import android.view.Display;
98 import android.view.DisplayAdjustments;
99 import android.view.autofill.AutofillManager.AutofillClient;
100 import android.window.WindowContext;
101 import android.window.WindowTokenClient;
102 import android.window.WindowTokenClientController;
103 
104 import com.android.internal.annotations.GuardedBy;
105 import com.android.internal.util.Preconditions;
106 
107 import dalvik.system.BlockGuard;
108 
109 import libcore.io.Memory;
110 
111 import java.io.File;
112 import java.io.FileInputStream;
113 import java.io.FileNotFoundException;
114 import java.io.FileOutputStream;
115 import java.io.FilenameFilter;
116 import java.io.IOException;
117 import java.io.InputStream;
118 import java.lang.annotation.Retention;
119 import java.lang.annotation.RetentionPolicy;
120 import java.nio.ByteOrder;
121 import java.nio.file.Path;
122 import java.util.ArrayList;
123 import java.util.Arrays;
124 import java.util.Collection;
125 import java.util.List;
126 import java.util.Objects;
127 import java.util.Set;
128 import java.util.concurrent.Executor;
129 import java.util.function.IntConsumer;
130 
131 class ReceiverRestrictedContext extends ContextWrapper {
132     @UnsupportedAppUsage
ReceiverRestrictedContext(Context base)133     ReceiverRestrictedContext(Context base) {
134         super(base);
135     }
136 
137     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)138     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
139         return registerReceiver(receiver, filter, null, null);
140     }
141 
142     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)143     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
144             String broadcastPermission, Handler scheduler) {
145         if (receiver == null) {
146             // Allow retrieving current sticky broadcast; this is safe since we
147             // aren't actually registering a receiver.
148             return super.registerReceiver(null, filter, broadcastPermission, scheduler);
149         } else {
150             throw new ReceiverCallNotAllowedException(
151                     "BroadcastReceiver components are not allowed to register to receive intents");
152         }
153     }
154 
155     @Override
registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)156     public Intent registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter,
157             String broadcastPermission, Handler scheduler) {
158         return registerReceiverAsUser(
159                 receiver, UserHandle.ALL, filter, broadcastPermission, scheduler);
160     }
161 
162     @Override
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)163     public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
164             IntentFilter filter, String broadcastPermission, Handler scheduler) {
165         if (receiver == null) {
166             // Allow retrieving current sticky broadcast; this is safe since we
167             // aren't actually registering a receiver.
168             return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
169         } else {
170             throw new ReceiverCallNotAllowedException(
171                     "BroadcastReceiver components are not allowed to register to receive intents");
172         }
173     }
174 
175     @Override
bindService(Intent service, ServiceConnection conn, int flags)176     public boolean bindService(Intent service, ServiceConnection conn, int flags) {
177         throw new ReceiverCallNotAllowedException(
178                 "BroadcastReceiver components are not allowed to bind to services");
179     }
180 
181     @Override
bindService( Intent service, int flags, Executor executor, ServiceConnection conn)182     public boolean bindService(
183           Intent service, int flags, Executor executor, ServiceConnection conn) {
184         throw new ReceiverCallNotAllowedException(
185             "BroadcastReceiver components are not allowed to bind to services");
186     }
187 
188     @Override
bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)189     public boolean bindIsolatedService(Intent service, int flags, String instanceName,
190             Executor executor, ServiceConnection conn) {
191         throw new ReceiverCallNotAllowedException(
192             "BroadcastReceiver components are not allowed to bind to services");
193     }
194 }
195 
196 /**
197  * Common implementation of Context API, which provides the base
198  * context object for Activity and other application components.
199  */
200 class ContextImpl extends Context {
201     private final static String TAG = "ContextImpl";
202     private final static boolean DEBUG = false;
203 
204     private static final String XATTR_INODE_CACHE = "user.inode_cache";
205     private static final String XATTR_INODE_CODE_CACHE = "user.inode_code_cache";
206 
207     /**
208      * Map from package name, to preference name, to cached preferences.
209      */
210     @GuardedBy("ContextImpl.class")
211     @UnsupportedAppUsage
212     private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;
213 
214     /**
215      * Map from preference name to generated path.
216      */
217     @GuardedBy("ContextImpl.class")
218     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
219     private ArrayMap<String, File> mSharedPrefsPaths;
220 
221     @UnsupportedAppUsage
222     final @NonNull ActivityThread mMainThread;
223     @UnsupportedAppUsage
224     final @NonNull LoadedApk mPackageInfo;
225     @UnsupportedAppUsage
226     private @Nullable ClassLoader mClassLoader;
227 
228     /**
229      * The {@link com.android.server.wm.WindowToken} representing this instance if it is
230      * {@link #CONTEXT_TYPE_WINDOW_CONTEXT} or {@link #CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI}.
231      * If the type is {@link #CONTEXT_TYPE_ACTIVITY}, then represents the
232      * {@link android.window.WindowContainerToken} of the activity.
233      */
234     private final @Nullable IBinder mToken;
235 
236     private final @NonNull UserHandle mUser;
237 
238     @UnsupportedAppUsage
239     private final ApplicationContentResolver mContentResolver;
240 
241     @UnsupportedAppUsage
242     private final String mBasePackageName;
243     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
244     private final String mOpPackageName;
245     private final @NonNull ContextParams mParams;
246     private @NonNull AttributionSource mAttributionSource;
247 
248     private final @NonNull ResourcesManager mResourcesManager;
249     @UnsupportedAppUsage
250     private @NonNull Resources mResources;
251     private @Nullable Display mDisplay; // may be null if invalid display or not initialized yet.
252     private int mDeviceId = Context.DEVICE_ID_DEFAULT;
253 
254     /**
255      * If set to {@code true} the resources for this context will be configured for mDisplay which
256      * will override the display configuration inherited from {@link #mToken} (or the global
257      * configuration if mToken is null). Typically set for display contexts and contexts derived
258      * from display contexts where changes to the activity display and the global configuration
259      * display should not impact their resources.
260      */
261     private boolean mForceDisplayOverrideInResources;
262 
263     /** @see Context#isConfigurationContext() */
264     private boolean mIsConfigurationBasedContext;
265 
266     /**
267      *  Indicates that this context was created with an explicit device ID association via
268      *  Context#createDeviceContext and under no circumstances will it ever change, even if
269      *  this context is not associated with a display id, or if the associated display id changes.
270      */
271     private boolean mIsExplicitDeviceId = false;
272 
273     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
274     private final int mFlags;
275 
276     @UnsupportedAppUsage
277     private Context mOuterContext;
278 
279     private final Object mThemeLock = new Object();
280     @UnsupportedAppUsage
281     @GuardedBy("mThemeLock")
282     private int mThemeResource = 0;
283     @UnsupportedAppUsage
284     @GuardedBy("mThemeLock")
285     private Resources.Theme mTheme = null;
286 
287     @UnsupportedAppUsage
288     private PackageManager mPackageManager;
289     private Context mReceiverRestrictedContext = null;
290 
291     // The name of the split this Context is representing. May be null.
292     private @Nullable String mSplitName = null;
293 
294     private @Nullable AutofillClient mAutofillClient = null;
295     private @Nullable AutofillOptions mAutofillOptions;
296 
297     private ContentCaptureOptions mContentCaptureOptions = null;
298 
299     /**
300      * Indicates this {@link Context} can not handle UI components properly and is not associated
301      * with a {@link Display} instance.
302      */
303     private static final int CONTEXT_TYPE_NON_UI = 0;
304     /**
305      * Indicates this {@link Context} is associated with a {@link Display} instance but should not
306      * be handled UI components properly because it doesn't receive configuration changes
307      * regardless of display property updates.
308      */
309     private static final int CONTEXT_TYPE_DISPLAY_CONTEXT = 1;
310     /**
311      * Indicates this {@link Context} is an {@link Activity} or {@link Activity} derived
312      * {@link Context}.
313      */
314     private static final int CONTEXT_TYPE_ACTIVITY = 2;
315     /**
316      * Indicates this {@link Context} is a {@link WindowContext} or {@link WindowContext} derived
317      * {@link Context}.
318      */
319     private static final int CONTEXT_TYPE_WINDOW_CONTEXT = 3;
320 
321     // TODO(b/170369943): Remove after WindowContext migration
322     /**
323      * Indicates this {@link Context} is created from {@link #createSystemContext(ActivityThread)}
324      * or {@link #createSystemUiContext(ContextImpl, int)} or any {@link Context} that system UI
325      * uses.
326      */
327     private static final int CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI = 4;
328 
329     @IntDef(prefix = "CONTEXT_TYPE_", value = {
330             CONTEXT_TYPE_NON_UI,
331             CONTEXT_TYPE_DISPLAY_CONTEXT,
332             CONTEXT_TYPE_ACTIVITY,
333             CONTEXT_TYPE_WINDOW_CONTEXT,
334             CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI
335     })
336     @Retention(RetentionPolicy.SOURCE)
337     private @interface ContextType {}
338 
339     @ContextType
340     private int mContextType;
341 
342     /**
343      * {@code true} to indicate that the {@link Context} owns the {@link #getWindowContextToken()}
344      * and is responsible for detaching the token when the Context is released.
345      *
346      * @see #finalize()
347      */
348     private boolean mOwnsToken = false;
349 
350     private final Object mDatabasesDirLock = new Object();
351     @GuardedBy("mDatabasesDirLock")
352     private File mDatabasesDir;
353 
354     private final Object mPreferencesDirLock = new Object();
355     @UnsupportedAppUsage
356     @GuardedBy("mPreferencesDirLock")
357     private File mPreferencesDir;
358 
359     private final Object mFilesDirLock = new Object();
360     @GuardedBy("mFilesDirLock")
361     private File mFilesDir;
362 
363     private final Object mCratesDirLock = new Object();
364     @GuardedBy("mCratesDirLock")
365     private File mCratesDir;
366 
367     private final Object mNoBackupFilesDirLock = new Object();
368     @GuardedBy("mNoBackupFilesDirLock")
369     private File mNoBackupFilesDir;
370 
371     private final Object mCacheDirLock = new Object();
372     @GuardedBy("mCacheDirLock")
373     private File mCacheDir;
374 
375     private final Object mCodeCacheDirLock = new Object();
376     @GuardedBy("mCodeCacheDirLock")
377     private File mCodeCacheDir;
378 
379     private final Object mMiscDirsLock = new Object();
380 
381     // The system service cache for the system services that are cached per-ContextImpl.
382     @UnsupportedAppUsage
383     final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
384 
385     static final int STATE_UNINITIALIZED = 0;
386     static final int STATE_INITIALIZING = 1;
387     static final int STATE_READY = 2;
388     static final int STATE_NOT_FOUND = 3;
389 
390     /** @hide */
391     @IntDef(prefix = { "STATE_" }, value = {
392             STATE_UNINITIALIZED,
393             STATE_INITIALIZING,
394             STATE_READY,
395             STATE_NOT_FOUND,
396     })
397     @Retention(RetentionPolicy.SOURCE)
398     @interface ServiceInitializationState {}
399 
400     /**
401      * Initialization state for each service. Any of {@link #STATE_UNINITIALIZED},
402      * {@link #STATE_INITIALIZING} or {@link #STATE_READY},
403      */
404     @ServiceInitializationState
405     final int[] mServiceInitializationStateArray = new int[mServiceCache.length];
406 
407     private final Object mDeviceIdListenerLock = new Object();
408     /**
409      * List of listeners for deviceId changes and their associated Executor.
410      * List is lazy-initialized on first registration
411      */
412     @GuardedBy("mDeviceIdListenerLock")
413     @Nullable
414     private ArrayList<DeviceIdChangeListenerDelegate> mDeviceIdChangeListeners;
415 
416     private static class DeviceIdChangeListenerDelegate {
417         final @NonNull IntConsumer mListener;
418         final @NonNull Executor mExecutor;
DeviceIdChangeListenerDelegate(IntConsumer listener, Executor executor)419         DeviceIdChangeListenerDelegate(IntConsumer listener, Executor executor) {
420             mListener = listener;
421             mExecutor = executor;
422         }
423     }
424 
425     @UnsupportedAppUsage
getImpl(Context context)426     static ContextImpl getImpl(Context context) {
427         Context nextContext;
428         while ((context instanceof ContextWrapper) &&
429                 (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
430             context = nextContext;
431         }
432         return (ContextImpl)context;
433     }
434 
435     @Override
getAssets()436     public AssetManager getAssets() {
437         return getResources().getAssets();
438     }
439 
440     @Override
getResources()441     public Resources getResources() {
442         return mResources;
443     }
444 
445     @Override
getPackageManager()446     public PackageManager getPackageManager() {
447         if (mPackageManager != null) {
448             return mPackageManager;
449         }
450 
451         final IPackageManager pm = ActivityThread.getPackageManager();
452         if (pm != null) {
453             // Doesn't matter if we make more than one instance.
454             return (mPackageManager = new ApplicationPackageManager(this, pm));
455         }
456 
457         return null;
458     }
459 
460     @Override
getContentResolver()461     public ContentResolver getContentResolver() {
462         return mContentResolver;
463     }
464 
465     @Override
getMainLooper()466     public Looper getMainLooper() {
467         return mMainThread.getLooper();
468     }
469 
470     @Override
getMainExecutor()471     public Executor getMainExecutor() {
472         return mMainThread.getExecutor();
473     }
474 
475     @Override
getApplicationContext()476     public Context getApplicationContext() {
477         return (mPackageInfo != null) ?
478                 mPackageInfo.getApplication() : mMainThread.getApplication();
479     }
480 
481     @Override
setTheme(int resId)482     public void setTheme(int resId) {
483         synchronized (mThemeLock) {
484             if (mThemeResource != resId) {
485                 mThemeResource = resId;
486                 initializeTheme();
487             }
488         }
489     }
490 
491     @Override
getThemeResId()492     public int getThemeResId() {
493         synchronized (mThemeLock) {
494             return mThemeResource;
495         }
496     }
497 
498     @Override
getTheme()499     public Resources.Theme getTheme() {
500         synchronized (mThemeLock) {
501             if (mTheme != null) {
502                 return mTheme;
503             }
504 
505             mThemeResource = Resources.selectDefaultTheme(mThemeResource,
506                     getOuterContext().getApplicationInfo().targetSdkVersion);
507             initializeTheme();
508 
509             return mTheme;
510         }
511     }
512 
initializeTheme()513     private void initializeTheme() {
514         if (mTheme == null) {
515             mTheme = mResources.newTheme();
516         }
517         mTheme.applyStyle(mThemeResource, true);
518     }
519 
520     @Override
getClassLoader()521     public ClassLoader getClassLoader() {
522         return mClassLoader != null ? mClassLoader : (mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader());
523     }
524 
525     @Override
getPackageName()526     public String getPackageName() {
527         if (mPackageInfo != null) {
528             return mPackageInfo.getPackageName();
529         }
530         // No mPackageInfo means this is a Context for the system itself,
531         // and this here is its name.
532         return "android";
533     }
534 
535     /** @hide */
536     @Override
getBasePackageName()537     public String getBasePackageName() {
538         return mBasePackageName != null ? mBasePackageName : getPackageName();
539     }
540 
541     /** @hide */
542     @Override
getOpPackageName()543     public String getOpPackageName() {
544         return mAttributionSource.getPackageName();
545     }
546 
547     /** @hide */
548     @Override
getAttributionTag()549     public @Nullable String getAttributionTag() {
550         return mAttributionSource.getAttributionTag();
551     }
552 
553     @Override
getParams()554     public @Nullable ContextParams getParams() {
555         return mParams;
556     }
557 
558     @Override
getAttributionSource()559     public @NonNull AttributionSource getAttributionSource() {
560         return mAttributionSource;
561     }
562 
563     @Override
getApplicationInfo()564     public ApplicationInfo getApplicationInfo() {
565         if (mPackageInfo != null) {
566             return mPackageInfo.getApplicationInfo();
567         }
568         throw new RuntimeException("Not supported in system context");
569     }
570 
571     @Override
getPackageResourcePath()572     public String getPackageResourcePath() {
573         if (mPackageInfo != null) {
574             return mPackageInfo.getResDir();
575         }
576         throw new RuntimeException("Not supported in system context");
577     }
578 
579     @Override
getPackageCodePath()580     public String getPackageCodePath() {
581         if (mPackageInfo != null) {
582             return mPackageInfo.getAppDir();
583         }
584         throw new RuntimeException("Not supported in system context");
585     }
586 
587     @Override
getSharedPreferences(String name, int mode)588     public SharedPreferences getSharedPreferences(String name, int mode) {
589         // At least one application in the world actually passes in a null
590         // name.  This happened to work because when we generated the file name
591         // we would stringify it to "null.xml".  Nice.
592         if (mPackageInfo.getApplicationInfo().targetSdkVersion <
593                 Build.VERSION_CODES.KITKAT) {
594             if (name == null) {
595                 name = "null";
596             }
597         }
598 
599         File file;
600         synchronized (ContextImpl.class) {
601             if (mSharedPrefsPaths == null) {
602                 mSharedPrefsPaths = new ArrayMap<>();
603             }
604             file = mSharedPrefsPaths.get(name);
605             if (file == null) {
606                 file = getSharedPreferencesPath(name);
607                 mSharedPrefsPaths.put(name, file);
608             }
609         }
610         return getSharedPreferences(file, mode);
611     }
612 
613     @Override
getSharedPreferences(File file, int mode)614     public SharedPreferences getSharedPreferences(File file, int mode) {
615         SharedPreferencesImpl sp;
616         synchronized (ContextImpl.class) {
617             final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
618             sp = cache.get(file);
619             if (sp == null) {
620                 checkMode(mode);
621                 if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
622                     if (isCredentialProtectedStorage()) {
623                         final UserManager um = getSystemService(UserManager.class);
624                         if (um == null) {
625                             throw new IllegalStateException("SharedPreferences cannot be accessed "
626                                     + "if UserManager is not available. "
627                                     + "(e.g. from inside an isolated process)");
628                         }
629                         if (!um.isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
630                             throw new IllegalStateException("SharedPreferences in "
631                                     + "credential encrypted storage are not available until after "
632                                     + "user (id " + UserHandle.myUserId() + ") is unlocked");
633                         }
634                     }
635                 }
636                 sp = new SharedPreferencesImpl(file, mode);
637                 cache.put(file, sp);
638                 return sp;
639             }
640         }
641         if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
642             getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
643             // If somebody else (some other process) changed the prefs
644             // file behind our back, we reload it.  This has been the
645             // historical (if undocumented) behavior.
646             sp.startReloadIfChangedUnexpectedly();
647         }
648         return sp;
649     }
650 
651     @GuardedBy("ContextImpl.class")
getSharedPreferencesCacheLocked()652     private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
653         if (sSharedPrefsCache == null) {
654             sSharedPrefsCache = new ArrayMap<>();
655         }
656 
657         final String packageName = getPackageName();
658         ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
659         if (packagePrefs == null) {
660             packagePrefs = new ArrayMap<>();
661             sSharedPrefsCache.put(packageName, packagePrefs);
662         }
663 
664         return packagePrefs;
665     }
666 
667     @Override
reloadSharedPreferences()668     public void reloadSharedPreferences() {
669         // Build the list of all per-context impls (i.e. caches) we know about
670         ArrayList<SharedPreferencesImpl> spImpls = new ArrayList<>();
671         synchronized (ContextImpl.class) {
672             final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
673             for (int i = 0; i < cache.size(); i++) {
674                 final SharedPreferencesImpl sp = cache.valueAt(i);
675                 if (sp != null) {
676                     spImpls.add(sp);
677                 }
678             }
679         }
680 
681         // Issue the reload outside the cache lock
682         for (int i = 0; i < spImpls.size(); i++) {
683             spImpls.get(i).startReloadIfChangedUnexpectedly();
684         }
685     }
686 
687     /**
688      * Try our best to migrate all files from source to target that match
689      * requested prefix.
690      *
691      * @return the number of files moved, or -1 if there was trouble.
692      */
moveFiles(File sourceDir, File targetDir, final String prefix)693     private static int moveFiles(File sourceDir, File targetDir, final String prefix) {
694         final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() {
695             @Override
696             public boolean accept(File dir, String name) {
697                 return name.startsWith(prefix);
698             }
699         });
700 
701         int res = 0;
702         for (File sourceFile : sourceFiles) {
703             final File targetFile = new File(targetDir, sourceFile.getName());
704             Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile);
705             try {
706                 FileUtils.copyFileOrThrow(sourceFile, targetFile);
707                 FileUtils.copyPermissions(sourceFile, targetFile);
708                 if (!sourceFile.delete()) {
709                     throw new IOException("Failed to clean up " + sourceFile);
710                 }
711                 if (res != -1) {
712                     res++;
713                 }
714             } catch (IOException e) {
715                 Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e);
716                 res = -1;
717             }
718         }
719         return res;
720     }
721 
722     @Override
moveSharedPreferencesFrom(Context sourceContext, String name)723     public boolean moveSharedPreferencesFrom(Context sourceContext, String name) {
724         synchronized (ContextImpl.class) {
725             final File source = sourceContext.getSharedPreferencesPath(name);
726             final File target = getSharedPreferencesPath(name);
727 
728             final int res = moveFiles(source.getParentFile(), target.getParentFile(),
729                     source.getName());
730             if (res > 0) {
731                 // We moved at least one file, so evict any in-memory caches for
732                 // either location
733                 final ArrayMap<File, SharedPreferencesImpl> cache =
734                         getSharedPreferencesCacheLocked();
735                 cache.remove(source);
736                 cache.remove(target);
737             }
738             return res != -1;
739         }
740     }
741 
742     @Override
deleteSharedPreferences(String name)743     public boolean deleteSharedPreferences(String name) {
744         synchronized (ContextImpl.class) {
745             final File prefs = getSharedPreferencesPath(name);
746             final File prefsBackup = SharedPreferencesImpl.makeBackupFile(prefs);
747 
748             // Evict any in-memory caches
749             final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
750             cache.remove(prefs);
751 
752             prefs.delete();
753             prefsBackup.delete();
754 
755             // We failed if files are still lingering
756             return !(prefs.exists() || prefsBackup.exists());
757         }
758     }
759 
760     @UnsupportedAppUsage
getPreferencesDir()761     private File getPreferencesDir() {
762         synchronized (mPreferencesDirLock) {
763             if (mPreferencesDir == null) {
764                 mPreferencesDir = new File(getDataDir(), "shared_prefs");
765             }
766             return ensurePrivateDirExists(mPreferencesDir);
767         }
768     }
769 
770     @Override
openFileInput(String name)771     public FileInputStream openFileInput(String name)
772         throws FileNotFoundException {
773         File f = makeFilename(getFilesDir(), name);
774         return new FileInputStream(f);
775     }
776 
777     @Override
openFileOutput(String name, int mode)778     public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException {
779         checkMode(mode);
780         final boolean append = (mode&MODE_APPEND) != 0;
781         File f = makeFilename(getFilesDir(), name);
782         try {
783             FileOutputStream fos = new FileOutputStream(f, append);
784             setFilePermissionsFromMode(f.getPath(), mode, 0);
785             return fos;
786         } catch (FileNotFoundException e) {
787         }
788 
789         File parent = f.getParentFile();
790         parent.mkdir();
791         FileUtils.setPermissions(
792             parent.getPath(),
793             FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
794             -1, -1);
795         FileOutputStream fos = new FileOutputStream(f, append);
796         setFilePermissionsFromMode(f.getPath(), mode, 0);
797         return fos;
798     }
799 
800     @Override
deleteFile(String name)801     public boolean deleteFile(String name) {
802         File f = makeFilename(getFilesDir(), name);
803         return f.delete();
804     }
805 
806     /**
807      * Common-path handling of app data dir creation
808      */
ensurePrivateDirExists(File file)809     private static File ensurePrivateDirExists(File file) {
810         return ensurePrivateDirExists(file, 0771, -1, null);
811     }
812 
ensurePrivateCacheDirExists(File file, String xattr)813     private static File ensurePrivateCacheDirExists(File file, String xattr) {
814         final int gid = UserHandle.getCacheAppGid(Process.myUid());
815         return ensurePrivateDirExists(file, 02771, gid, xattr);
816     }
817 
ensurePrivateDirExists(File file, int mode, int gid, String xattr)818     private static File ensurePrivateDirExists(File file, int mode, int gid, String xattr) {
819         if (!file.exists()) {
820             final String path = file.getAbsolutePath();
821             try {
822                 Os.mkdir(path, mode);
823                 Os.chmod(path, mode);
824                 if (gid != -1) {
825                     Os.chown(path, -1, gid);
826                 }
827             } catch (ErrnoException e) {
828                 if (e.errno == OsConstants.EEXIST) {
829                     // We must have raced with someone; that's okay
830                 } else {
831                     Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
832                 }
833             }
834 
835             if (xattr != null) {
836                 try {
837                     final StructStat stat = Os.stat(file.getAbsolutePath());
838                     final byte[] value = new byte[8];
839                     Memory.pokeLong(value, 0, stat.st_ino, ByteOrder.nativeOrder());
840                     Os.setxattr(file.getParentFile().getAbsolutePath(), xattr, value, 0);
841                 } catch (ErrnoException e) {
842                     Log.w(TAG, "Failed to update " + xattr + ": " + e.getMessage());
843                 }
844             }
845         }
846         return file;
847     }
848 
849     @Override
getFilesDir()850     public File getFilesDir() {
851         synchronized (mFilesDirLock) {
852             if (mFilesDir == null) {
853                 mFilesDir = new File(getDataDir(), "files");
854             }
855             return ensurePrivateDirExists(mFilesDir);
856         }
857     }
858 
859     @Override
getCrateDir(@onNull String crateId)860     public File getCrateDir(@NonNull String crateId) {
861         Preconditions.checkArgument(FileUtils.isValidExtFilename(crateId), "invalidated crateId");
862         final Path cratesRootPath = getDataDir().toPath().resolve("crates");
863         final Path absoluteNormalizedCratePath = cratesRootPath.resolve(crateId)
864                 .toAbsolutePath().normalize();
865 
866         synchronized (mCratesDirLock) {
867             if (mCratesDir == null) {
868                 mCratesDir = cratesRootPath.toFile();
869             }
870             ensurePrivateDirExists(mCratesDir);
871         }
872 
873         File cratedDir = absoluteNormalizedCratePath.toFile();
874         return ensurePrivateDirExists(cratedDir);
875     }
876 
877     @Override
getNoBackupFilesDir()878     public File getNoBackupFilesDir() {
879         synchronized (mNoBackupFilesDirLock) {
880             if (mNoBackupFilesDir == null) {
881                 mNoBackupFilesDir = new File(getDataDir(), "no_backup");
882             }
883             return ensurePrivateDirExists(mNoBackupFilesDir);
884         }
885     }
886 
887     @Override
getExternalFilesDir(String type)888     public File getExternalFilesDir(String type) {
889         // Operates on primary external storage
890         final File[] dirs = getExternalFilesDirs(type);
891         return (dirs != null && dirs.length > 0) ? dirs[0] : null;
892     }
893 
894     @Override
getExternalFilesDirs(String type)895     public File[] getExternalFilesDirs(String type) {
896         synchronized (mMiscDirsLock) {
897             File[] dirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
898             if (type != null) {
899                 dirs = Environment.buildPaths(dirs, type);
900             }
901             return ensureExternalDirsExistOrFilter(dirs, true /* tryCreateInProcess */);
902         }
903     }
904 
905     @Override
getObbDir()906     public File getObbDir() {
907         // Operates on primary external storage
908         final File[] dirs = getObbDirs();
909         return (dirs != null && dirs.length > 0) ? dirs[0] : null;
910     }
911 
912     @Override
getObbDirs()913     public File[] getObbDirs() {
914         synchronized (mMiscDirsLock) {
915             File[] dirs = Environment.buildExternalStorageAppObbDirs(getPackageName());
916             return ensureExternalDirsExistOrFilter(dirs, true /* tryCreateInProcess */);
917         }
918     }
919 
920     @Override
getCacheDir()921     public File getCacheDir() {
922         synchronized (mCacheDirLock) {
923             if (mCacheDir == null) {
924                 mCacheDir = new File(getDataDir(), "cache");
925             }
926             return ensurePrivateCacheDirExists(mCacheDir, XATTR_INODE_CACHE);
927         }
928     }
929 
930     @Override
getCodeCacheDir()931     public File getCodeCacheDir() {
932         synchronized (mCodeCacheDirLock) {
933             if (mCodeCacheDir == null) {
934                 mCodeCacheDir = getCodeCacheDirBeforeBind(getDataDir());
935             }
936             return ensurePrivateCacheDirExists(mCodeCacheDir, XATTR_INODE_CODE_CACHE);
937         }
938     }
939 
940     /**
941      * Helper for getting code-cache dir potentially before application bind.
942      *
943      * @hide
944      */
getCodeCacheDirBeforeBind(File dataDir)945     static File getCodeCacheDirBeforeBind(File dataDir) {
946         return new File(dataDir, "code_cache");
947     }
948 
949     @Override
getExternalCacheDir()950     public File getExternalCacheDir() {
951         // Operates on primary external storage
952         final File[] dirs = getExternalCacheDirs();
953         return (dirs != null && dirs.length > 0) ? dirs[0] : null;
954     }
955 
956     @Override
getExternalCacheDirs()957     public File[] getExternalCacheDirs() {
958         synchronized (mMiscDirsLock) {
959             File[] dirs = Environment.buildExternalStorageAppCacheDirs(getPackageName());
960             // We don't try to create cache directories in-process, because they need special
961             // setup for accurate quota tracking. This ensures the cache dirs are always
962             // created through StorageManagerService.
963             return ensureExternalDirsExistOrFilter(dirs, false /* tryCreateInProcess */);
964         }
965     }
966 
967     @Override
getExternalMediaDirs()968     public File[] getExternalMediaDirs() {
969         synchronized (mMiscDirsLock) {
970             File[] dirs = Environment.buildExternalStorageAppMediaDirs(getPackageName());
971             return ensureExternalDirsExistOrFilter(dirs, true /* tryCreateInProcess */);
972         }
973     }
974 
975     /**
976      * @hide
977      */
978     @Nullable
979     @Override
getPreloadsFileCache()980     public File getPreloadsFileCache() {
981         return Environment.getDataPreloadsFileCacheDirectory(getPackageName());
982     }
983 
984     @Override
getFileStreamPath(String name)985     public File getFileStreamPath(String name) {
986         return makeFilename(getFilesDir(), name);
987     }
988 
989     @Override
getSharedPreferencesPath(String name)990     public File getSharedPreferencesPath(String name) {
991         return makeFilename(getPreferencesDir(), name + ".xml");
992     }
993 
994     @Override
fileList()995     public String[] fileList() {
996         return FileUtils.listOrEmpty(getFilesDir());
997     }
998 
999     @Override
openOrCreateDatabase(String name, int mode, CursorFactory factory)1000     public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
1001         return openOrCreateDatabase(name, mode, factory, null);
1002     }
1003 
1004     @Override
openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler)1005     public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
1006             DatabaseErrorHandler errorHandler) {
1007         checkMode(mode);
1008         File f = getDatabasePath(name);
1009         int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
1010         if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
1011             flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
1012         }
1013         if ((mode & MODE_NO_LOCALIZED_COLLATORS) != 0) {
1014             flags |= SQLiteDatabase.NO_LOCALIZED_COLLATORS;
1015         }
1016         SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
1017         setFilePermissionsFromMode(f.getPath(), mode, 0);
1018         return db;
1019     }
1020 
1021     @Override
moveDatabaseFrom(Context sourceContext, String name)1022     public boolean moveDatabaseFrom(Context sourceContext, String name) {
1023         synchronized (ContextImpl.class) {
1024             final File source = sourceContext.getDatabasePath(name);
1025             final File target = getDatabasePath(name);
1026             return moveFiles(source.getParentFile(), target.getParentFile(),
1027                     source.getName()) != -1;
1028         }
1029     }
1030 
1031     @Override
deleteDatabase(String name)1032     public boolean deleteDatabase(String name) {
1033         try {
1034             File f = getDatabasePath(name);
1035             return SQLiteDatabase.deleteDatabase(f);
1036         } catch (Exception e) {
1037         }
1038         return false;
1039     }
1040 
1041     @Override
getDatabasePath(String name)1042     public File getDatabasePath(String name) {
1043         File dir;
1044         File f;
1045 
1046         if (name.charAt(0) == File.separatorChar) {
1047             String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
1048             dir = new File(dirPath);
1049             name = name.substring(name.lastIndexOf(File.separatorChar));
1050             f = new File(dir, name);
1051 
1052             if (!dir.isDirectory() && dir.mkdir()) {
1053                 FileUtils.setPermissions(dir.getPath(),
1054                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1055                     -1, -1);
1056             }
1057         } else {
1058             dir = getDatabasesDir();
1059             f = makeFilename(dir, name);
1060         }
1061 
1062         return f;
1063     }
1064 
1065     @Override
databaseList()1066     public String[] databaseList() {
1067         return FileUtils.listOrEmpty(getDatabasesDir());
1068     }
1069 
getDatabasesDir()1070     private File getDatabasesDir() {
1071         synchronized (mDatabasesDirLock) {
1072             if (mDatabasesDir == null) {
1073                 if ("android".equals(getPackageName())) {
1074                     mDatabasesDir = new File("/data/system");
1075                 } else {
1076                     mDatabasesDir = new File(getDataDir(), "databases");
1077                 }
1078             }
1079             return ensurePrivateDirExists(mDatabasesDir);
1080         }
1081     }
1082 
1083     @Override
1084     @Deprecated
getWallpaper()1085     public Drawable getWallpaper() {
1086         return getWallpaperManager().getDrawable();
1087     }
1088 
1089     @Override
1090     @Deprecated
peekWallpaper()1091     public Drawable peekWallpaper() {
1092         return getWallpaperManager().peekDrawable();
1093     }
1094 
1095     @Override
1096     @Deprecated
getWallpaperDesiredMinimumWidth()1097     public int getWallpaperDesiredMinimumWidth() {
1098         return getWallpaperManager().getDesiredMinimumWidth();
1099     }
1100 
1101     @Override
1102     @Deprecated
getWallpaperDesiredMinimumHeight()1103     public int getWallpaperDesiredMinimumHeight() {
1104         return getWallpaperManager().getDesiredMinimumHeight();
1105     }
1106 
1107     @Override
1108     @Deprecated
setWallpaper(Bitmap bitmap)1109     public void setWallpaper(Bitmap bitmap) throws IOException {
1110         getWallpaperManager().setBitmap(bitmap);
1111     }
1112 
1113     @Override
1114     @Deprecated
setWallpaper(InputStream data)1115     public void setWallpaper(InputStream data) throws IOException {
1116         getWallpaperManager().setStream(data);
1117     }
1118 
1119     @Override
1120     @Deprecated
clearWallpaper()1121     public void clearWallpaper() throws IOException {
1122         getWallpaperManager().clear();
1123     }
1124 
getWallpaperManager()1125     private WallpaperManager getWallpaperManager() {
1126         return getSystemService(WallpaperManager.class);
1127     }
1128 
1129     @Override
startActivity(Intent intent)1130     public void startActivity(Intent intent) {
1131         warnIfCallingFromSystemProcess();
1132         startActivity(intent, null);
1133     }
1134 
1135     /** @hide */
1136     @Override
startActivityAsUser(Intent intent, UserHandle user)1137     public void startActivityAsUser(Intent intent, UserHandle user) {
1138         startActivityAsUser(intent, null, user);
1139     }
1140 
1141     @Override
startActivity(Intent intent, Bundle options)1142     public void startActivity(Intent intent, Bundle options) {
1143         warnIfCallingFromSystemProcess();
1144 
1145         // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is
1146         // generally not allowed, except if the caller specifies the task id the activity should
1147         // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We
1148         // maintain this for backwards compatibility.
1149         final int targetSdkVersion = getApplicationInfo().targetSdkVersion;
1150 
1151         if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
1152                 && (targetSdkVersion < Build.VERSION_CODES.N
1153                         || targetSdkVersion >= Build.VERSION_CODES.P)
1154                 && (options == null
1155                         || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
1156             throw new AndroidRuntimeException(
1157                     "Calling startActivity() from outside of an Activity"
1158                             + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
1159                             + " Is this really what you want?");
1160         }
1161         mMainThread.getInstrumentation().execStartActivity(
1162                 getOuterContext(), mMainThread.getApplicationThread(), null,
1163                 (Activity) null, intent, -1, options);
1164     }
1165 
1166     /** @hide */
1167     @Override
startActivityAsUser(Intent intent, Bundle options, UserHandle user)1168     public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
1169         try {
1170             ActivityTaskManager.getService().startActivityAsUser(
1171                     mMainThread.getApplicationThread(), getOpPackageName(), getAttributionTag(),
1172                     intent, intent.resolveTypeIfNeeded(getContentResolver()),
1173                     null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
1174                     user.getIdentifier());
1175         } catch (RemoteException e) {
1176             throw e.rethrowFromSystemServer();
1177         }
1178     }
1179 
1180     @Override
startActivities(Intent[] intents)1181     public void startActivities(Intent[] intents) {
1182         warnIfCallingFromSystemProcess();
1183         startActivities(intents, null);
1184     }
1185 
1186     /** @hide */
1187     @Override
startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle)1188     public int startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
1189         if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1190             throw new AndroidRuntimeException(
1191                     "Calling startActivities() from outside of an Activity"
1192                     + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1193                     + " Is this really what you want?");
1194         }
1195         return mMainThread.getInstrumentation().execStartActivitiesAsUser(
1196                 getOuterContext(), mMainThread.getApplicationThread(), null,
1197                 (Activity) null, intents, options, userHandle.getIdentifier());
1198     }
1199 
1200     @Override
startActivities(Intent[] intents, Bundle options)1201     public void startActivities(Intent[] intents, Bundle options) {
1202         warnIfCallingFromSystemProcess();
1203         if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1204             throw new AndroidRuntimeException(
1205                     "Calling startActivities() from outside of an Activity"
1206                     + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1207                     + " Is this really what you want?");
1208         }
1209         mMainThread.getInstrumentation().execStartActivities(
1210                 getOuterContext(), mMainThread.getApplicationThread(), null,
1211                 (Activity) null, intents, options);
1212     }
1213 
1214     @Override
startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)1215     public void startIntentSender(IntentSender intent,
1216             Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
1217             throws IntentSender.SendIntentException {
1218         startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
1219     }
1220 
1221     @Override
startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)1222     public void startIntentSender(IntentSender intent, Intent fillInIntent,
1223             int flagsMask, int flagsValues, int extraFlags, Bundle options)
1224             throws IntentSender.SendIntentException {
1225         try {
1226             String resolvedType = null;
1227             if (fillInIntent != null) {
1228                 fillInIntent.migrateExtraStreamToClipData(this);
1229                 fillInIntent.prepareToLeaveProcess(this);
1230                 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
1231             }
1232             int result = ActivityTaskManager.getService()
1233                 .startActivityIntentSender(mMainThread.getApplicationThread(),
1234                         intent != null ? intent.getTarget() : null,
1235                         intent != null ? intent.getWhitelistToken() : null,
1236                         fillInIntent, resolvedType, null, null,
1237                         0, flagsMask, flagsValues, options);
1238             if (result == ActivityManager.START_CANCELED) {
1239                 throw new IntentSender.SendIntentException();
1240             }
1241             Instrumentation.checkStartActivityResult(result, null);
1242         } catch (RemoteException e) {
1243             throw e.rethrowFromSystemServer();
1244         }
1245     }
1246 
1247     @Override
sendBroadcast(Intent intent)1248     public void sendBroadcast(Intent intent) {
1249         warnIfCallingFromSystemProcess();
1250         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1251         try {
1252             intent.prepareToLeaveProcess(this);
1253             ActivityManager.getService().broadcastIntentWithFeature(
1254                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1255                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1256                     null, AppOpsManager.OP_NONE, null, false, false, getUserId());
1257         } catch (RemoteException e) {
1258             throw e.rethrowFromSystemServer();
1259         }
1260     }
1261 
1262     @Override
sendBroadcast(Intent intent, String receiverPermission)1263     public void sendBroadcast(Intent intent, String receiverPermission) {
1264         warnIfCallingFromSystemProcess();
1265         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1266         String[] receiverPermissions = receiverPermission == null ? null
1267                 : new String[] {receiverPermission};
1268         try {
1269             intent.prepareToLeaveProcess(this);
1270             ActivityManager.getService().broadcastIntentWithFeature(
1271                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1272                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1273                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
1274                     getUserId());
1275         } catch (RemoteException e) {
1276             throw e.rethrowFromSystemServer();
1277         }
1278     }
1279 
1280     @Override
sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions)1281     public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions) {
1282         warnIfCallingFromSystemProcess();
1283         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1284         try {
1285             intent.prepareToLeaveProcess(this);
1286             ActivityManager.getService().broadcastIntentWithFeature(
1287                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1288                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1289                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
1290                     getUserId());
1291         } catch (RemoteException e) {
1292             throw e.rethrowFromSystemServer();
1293         }
1294     }
1295 
1296     @Override
sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions, Bundle options)1297     public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions,
1298             Bundle options) {
1299         warnIfCallingFromSystemProcess();
1300         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1301         try {
1302             intent.prepareToLeaveProcess(this);
1303             ActivityManager.getService().broadcastIntentWithFeature(
1304                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1305                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1306                     null /*excludedPermissions=*/, null /*excludedPackages*/,
1307                     AppOpsManager.OP_NONE, options, false, false, getUserId());
1308         } catch (RemoteException e) {
1309             throw e.rethrowFromSystemServer();
1310         }
1311     }
1312 
1313     @Override
sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user, String[] receiverPermissions)1314     public void sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user,
1315             String[] receiverPermissions) {
1316         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1317         try {
1318             intent.prepareToLeaveProcess(this);
1319             ActivityManager.getService().broadcastIntentWithFeature(
1320                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1321                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1322                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, false, false,
1323                     user.getIdentifier());
1324         } catch (RemoteException e) {
1325             throw e.rethrowFromSystemServer();
1326         }
1327     }
1328 
1329     @Override
sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions, String[] excludedPermissions, String[] excludedPackages, BroadcastOptions options)1330     public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions,
1331             String[] excludedPermissions, String[] excludedPackages, BroadcastOptions options) {
1332         warnIfCallingFromSystemProcess();
1333         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1334         try {
1335             intent.prepareToLeaveProcess(this);
1336             ActivityManager.getService().broadcastIntentWithFeature(
1337                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1338                     null, Activity.RESULT_OK, null, null, receiverPermissions, excludedPermissions,
1339                     excludedPackages, AppOpsManager.OP_NONE,
1340                     options == null ? null : options.toBundle(), false, false, getUserId());
1341         } catch (RemoteException e) {
1342             throw e.rethrowFromSystemServer();
1343         }
1344     }
1345 
1346     @Override
sendBroadcast(Intent intent, String receiverPermission, Bundle options)1347     public void sendBroadcast(Intent intent, String receiverPermission, Bundle options) {
1348         warnIfCallingFromSystemProcess();
1349         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1350         String[] receiverPermissions = receiverPermission == null ? null
1351                 : new String[] {receiverPermission};
1352         String[] excludedPermissions = null;
1353         if (options != null) {
1354             String[] receiverPermissionsBundle = options.getStringArray(
1355                     BroadcastOptions.KEY_REQUIRE_ALL_OF_PERMISSIONS);
1356             if (receiverPermissionsBundle != null) {
1357                 receiverPermissions = receiverPermissionsBundle;
1358             }
1359             excludedPermissions = options.getStringArray(
1360                     BroadcastOptions.KEY_REQUIRE_NONE_OF_PERMISSIONS);
1361         }
1362         try {
1363             intent.prepareToLeaveProcess(this);
1364             ActivityManager.getService().broadcastIntentWithFeature(
1365                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1366                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1367                     excludedPermissions, null, AppOpsManager.OP_NONE, options, false, false,
1368                     getUserId());
1369         } catch (RemoteException e) {
1370             throw e.rethrowFromSystemServer();
1371         }
1372     }
1373 
1374     @Override
sendBroadcast(Intent intent, String receiverPermission, int appOp)1375     public void sendBroadcast(Intent intent, String receiverPermission, int appOp) {
1376         warnIfCallingFromSystemProcess();
1377         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1378         String[] receiverPermissions = receiverPermission == null ? null
1379                 : new String[] {receiverPermission};
1380         try {
1381             intent.prepareToLeaveProcess(this);
1382             ActivityManager.getService().broadcastIntentWithFeature(
1383                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1384                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1385                     null /*excludedPermissions=*/, null, appOp, null, false, false, getUserId());
1386         } catch (RemoteException e) {
1387             throw e.rethrowFromSystemServer();
1388         }
1389     }
1390 
1391     @Override
1392     @SuppressLint("AndroidFrameworkRequiresPermission")
sendOrderedBroadcast(Intent intent, String receiverPermission)1393     public void sendOrderedBroadcast(Intent intent, String receiverPermission) {
1394         sendOrderedBroadcast(intent, receiverPermission, /*options=*/ null);
1395     }
1396 
1397     @Override
sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options)1398     public void sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options) {
1399         warnIfCallingFromSystemProcess();
1400         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1401         String[] receiverPermissions = receiverPermission == null ? null
1402                 : new String[] {receiverPermission};
1403         try {
1404             intent.prepareToLeaveProcess(this);
1405             ActivityManager.getService().broadcastIntentWithFeature(
1406                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1407                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1408                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, options, true,
1409                     false, getUserId());
1410         } catch (RemoteException e) {
1411             throw e.rethrowFromSystemServer();
1412         }
1413     }
1414 
1415     @Override
sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1416     public void sendOrderedBroadcast(Intent intent,
1417             String receiverPermission, BroadcastReceiver resultReceiver,
1418             Handler scheduler, int initialCode, String initialData,
1419             Bundle initialExtras) {
1420         sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
1421                 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1422     }
1423 
1424     @Override
sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1425     public void sendOrderedBroadcast(Intent intent,
1426             String receiverPermission, Bundle options, BroadcastReceiver resultReceiver,
1427             Handler scheduler, int initialCode, String initialData,
1428             Bundle initialExtras) {
1429         sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
1430                 resultReceiver, scheduler, initialCode, initialData, initialExtras, options);
1431     }
1432 
1433     @Override
sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1434     public void sendOrderedBroadcast(Intent intent,
1435             String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1436             Handler scheduler, int initialCode, String initialData,
1437             Bundle initialExtras) {
1438         sendOrderedBroadcast(intent, receiverPermission, appOp,
1439                 resultReceiver, scheduler, initialCode, initialData, initialExtras, null);
1440     }
1441 
sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras, Bundle options)1442     void sendOrderedBroadcast(Intent intent,
1443             String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1444             Handler scheduler, int initialCode, String initialData,
1445             Bundle initialExtras, Bundle options) {
1446         warnIfCallingFromSystemProcess();
1447         IIntentReceiver rd = null;
1448         if (resultReceiver != null) {
1449             if (mPackageInfo != null) {
1450                 if (scheduler == null) {
1451                     scheduler = mMainThread.getHandler();
1452                 }
1453                 rd = mPackageInfo.getReceiverDispatcher(
1454                     resultReceiver, getOuterContext(), scheduler,
1455                     mMainThread.getInstrumentation(), false);
1456             } else {
1457                 if (scheduler == null) {
1458                     scheduler = mMainThread.getHandler();
1459                 }
1460                 rd = new LoadedApk.ReceiverDispatcher(mMainThread.getApplicationThread(),
1461                         resultReceiver, getOuterContext(), scheduler, null, false)
1462                                 .getIIntentReceiver();
1463             }
1464         }
1465         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1466         String[] receiverPermissions = receiverPermission == null ? null
1467                 : new String[] {receiverPermission};
1468         try {
1469             intent.prepareToLeaveProcess(this);
1470             ActivityManager.getService().broadcastIntentWithFeature(
1471                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1472                     rd, initialCode, initialData, initialExtras, receiverPermissions,
1473                     null /*excludedPermissions=*/, null, appOp, options, true, false, getUserId());
1474         } catch (RemoteException e) {
1475             throw e.rethrowFromSystemServer();
1476         }
1477     }
1478 
1479     @Override
sendBroadcastAsUser(Intent intent, UserHandle user)1480     public void sendBroadcastAsUser(Intent intent, UserHandle user) {
1481         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1482         try {
1483             intent.prepareToLeaveProcess(this);
1484             ActivityManager.getService().broadcastIntentWithFeature(
1485                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1486                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1487                     null, AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
1488         } catch (RemoteException e) {
1489             throw e.rethrowFromSystemServer();
1490         }
1491     }
1492 
1493     @Override
sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission)1494     public void sendBroadcastAsUser(Intent intent, UserHandle user,
1495             String receiverPermission) {
1496         sendBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE);
1497     }
1498 
1499     @Override
sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, Bundle options)1500     public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission,
1501             Bundle options) {
1502         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1503         String[] receiverPermissions = receiverPermission == null ? null
1504                 : new String[] {receiverPermission};
1505         try {
1506             intent.prepareToLeaveProcess(this);
1507             ActivityManager.getService().broadcastIntentWithFeature(
1508                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1509                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1510                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, options, false,
1511                     false, user.getIdentifier());
1512         } catch (RemoteException e) {
1513             throw e.rethrowFromSystemServer();
1514         }
1515     }
1516 
1517     @Override
sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp)1518     public void sendBroadcastAsUser(Intent intent, UserHandle user,
1519             String receiverPermission, int appOp) {
1520         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1521         String[] receiverPermissions = receiverPermission == null ? null
1522                 : new String[] {receiverPermission};
1523         try {
1524             intent.prepareToLeaveProcess(this);
1525             ActivityManager.getService().broadcastIntentWithFeature(
1526                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1527                     null, Activity.RESULT_OK, null, null, receiverPermissions,
1528                     null /*excludedPermissions=*/, null, appOp, null, false, false,
1529                     user.getIdentifier());
1530         } catch (RemoteException e) {
1531             throw e.rethrowFromSystemServer();
1532         }
1533     }
1534 
1535     @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1536     public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1537             String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
1538             int initialCode, String initialData, Bundle initialExtras) {
1539         sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE,
1540                 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
1541     }
1542 
1543     @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1544     public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1545             String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1546             Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
1547         sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp,
1548                 null, resultReceiver, scheduler, initialCode, initialData, initialExtras);
1549     }
1550 
1551     @Override
sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1552     public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1553             String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver,
1554             Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
1555         IIntentReceiver rd = null;
1556         if (resultReceiver != null) {
1557             if (mPackageInfo != null) {
1558                 if (scheduler == null) {
1559                     scheduler = mMainThread.getHandler();
1560                 }
1561                 rd = mPackageInfo.getReceiverDispatcher(
1562                     resultReceiver, getOuterContext(), scheduler,
1563                     mMainThread.getInstrumentation(), false);
1564             } else {
1565                 if (scheduler == null) {
1566                     scheduler = mMainThread.getHandler();
1567                 }
1568                 rd = new LoadedApk.ReceiverDispatcher(mMainThread.getApplicationThread(),
1569                         resultReceiver, getOuterContext(), scheduler, null, false)
1570                                 .getIIntentReceiver();
1571             }
1572         }
1573         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1574         String[] receiverPermissions = receiverPermission == null ? null
1575                 : new String[] {receiverPermission};
1576         try {
1577             intent.prepareToLeaveProcess(this);
1578             ActivityManager.getService().broadcastIntentWithFeature(
1579                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1580                     rd, initialCode, initialData, initialExtras, receiverPermissions,
1581                     null /*excludedPermissions=*/, null, appOp, options, true, false,
1582                     user.getIdentifier());
1583         } catch (RemoteException e) {
1584             throw e.rethrowFromSystemServer();
1585         }
1586     }
1587 
1588     @Override
sendOrderedBroadcast(Intent intent, String receiverPermission, String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, @Nullable Bundle initialExtras)1589     public void sendOrderedBroadcast(Intent intent, String receiverPermission,
1590             String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler,
1591             int initialCode, String initialData, @Nullable Bundle initialExtras) {
1592         int intAppOp = AppOpsManager.OP_NONE;
1593         if (!TextUtils.isEmpty(receiverAppOp)) {
1594             intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1595         }
1596         sendOrderedBroadcastAsUser(intent, getUser(),
1597                 receiverPermission, intAppOp, resultReceiver, scheduler, initialCode, initialData,
1598                 initialExtras);
1599     }
1600 
1601     @Override
sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission, String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, String initialData, @Nullable Bundle initialExtras, Bundle options)1602     public void sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission,
1603             String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler,
1604             String initialData, @Nullable Bundle initialExtras, Bundle options) {
1605         int intAppOp = AppOpsManager.OP_NONE;
1606         if (!TextUtils.isEmpty(receiverAppOp)) {
1607             intAppOp = AppOpsManager.strOpToOp(receiverAppOp);
1608         }
1609         sendOrderedBroadcastAsUser(intent, getUser(), receiverPermission, intAppOp, options,
1610                 resultReceiver, scheduler, initialCode, initialData, initialExtras);
1611     }
1612 
1613     @Override
1614     @Deprecated
sendStickyBroadcast(Intent intent)1615     public void sendStickyBroadcast(Intent intent) {
1616         warnIfCallingFromSystemProcess();
1617         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1618         try {
1619             intent.prepareToLeaveProcess(this);
1620             ActivityManager.getService().broadcastIntentWithFeature(
1621                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1622                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1623                     null, AppOpsManager.OP_NONE, null, false, true, getUserId());
1624         } catch (RemoteException e) {
1625             throw e.rethrowFromSystemServer();
1626         }
1627     }
1628 
1629     /**
1630      * <p>Perform a {@link #sendBroadcast(Intent)} that is "sticky," meaning the
1631      * Intent you are sending stays around after the broadcast is complete,
1632      * so that others can quickly retrieve that data through the return
1633      * value of {@link #registerReceiver(BroadcastReceiver, IntentFilter)}.  In
1634      * all other ways, this behaves the same as
1635      * {@link #sendBroadcast(Intent)}.
1636      *
1637      * @deprecated Sticky broadcasts should not be used.  They provide no security (anyone
1638      * can access them), no protection (anyone can modify them), and many other problems.
1639      * The recommended pattern is to use a non-sticky broadcast to report that <em>something</em>
1640      * has changed, with another mechanism for apps to retrieve the current value whenever
1641      * desired.
1642      *
1643      * @param intent The Intent to broadcast; all receivers matching this
1644      * Intent will receive the broadcast, and the Intent will be held to
1645      * be re-broadcast to future receivers.
1646      * @param options (optional) Additional sending options, generated from a
1647      * {@link android.app.BroadcastOptions}.
1648      *
1649      * @see #sendBroadcast(Intent)
1650      * @see #sendStickyOrderedBroadcast(Intent, BroadcastReceiver, Handler, int, String, Bundle)
1651      */
1652     @Override
1653     @Deprecated
sendStickyBroadcast(@onNull Intent intent, @Nullable Bundle options)1654     public void sendStickyBroadcast(@NonNull Intent intent, @Nullable Bundle options) {
1655         warnIfCallingFromSystemProcess();
1656         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1657         try {
1658             intent.prepareToLeaveProcess(this);
1659             ActivityManager.getService().broadcastIntentWithFeature(
1660                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1661                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1662                     null, AppOpsManager.OP_NONE, options, false, true, getUserId());
1663         } catch (RemoteException e) {
1664             throw e.rethrowFromSystemServer();
1665         }
1666     }
1667 
1668     @Override
1669     @Deprecated
sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1670     public void sendStickyOrderedBroadcast(Intent intent,
1671             BroadcastReceiver resultReceiver,
1672             Handler scheduler, int initialCode, String initialData,
1673             Bundle initialExtras) {
1674         warnIfCallingFromSystemProcess();
1675         IIntentReceiver rd = null;
1676         if (resultReceiver != null) {
1677             if (mPackageInfo != null) {
1678                 if (scheduler == null) {
1679                     scheduler = mMainThread.getHandler();
1680                 }
1681                 rd = mPackageInfo.getReceiverDispatcher(
1682                     resultReceiver, getOuterContext(), scheduler,
1683                     mMainThread.getInstrumentation(), false);
1684             } else {
1685                 if (scheduler == null) {
1686                     scheduler = mMainThread.getHandler();
1687                 }
1688                 rd = new LoadedApk.ReceiverDispatcher(mMainThread.getApplicationThread(),
1689                         resultReceiver, getOuterContext(), scheduler, null, false)
1690                                 .getIIntentReceiver();
1691             }
1692         }
1693         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1694         try {
1695             intent.prepareToLeaveProcess(this);
1696             ActivityManager.getService().broadcastIntentWithFeature(
1697                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1698                     rd, initialCode, initialData, initialExtras, null,
1699                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, true, true,
1700                     getUserId());
1701         } catch (RemoteException e) {
1702             throw e.rethrowFromSystemServer();
1703         }
1704     }
1705 
1706     @Override
1707     @Deprecated
removeStickyBroadcast(Intent intent)1708     public void removeStickyBroadcast(Intent intent) {
1709         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1710         if (resolvedType != null) {
1711             intent = new Intent(intent);
1712             intent.setDataAndType(intent.getData(), resolvedType);
1713         }
1714         try {
1715             intent.prepareToLeaveProcess(this);
1716             ActivityManager.getService().unbroadcastIntent(
1717                     mMainThread.getApplicationThread(), intent, getUserId());
1718         } catch (RemoteException e) {
1719             throw e.rethrowFromSystemServer();
1720         }
1721     }
1722 
1723     @Override
1724     @Deprecated
sendStickyBroadcastAsUser(Intent intent, UserHandle user)1725     public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
1726         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1727         try {
1728             intent.prepareToLeaveProcess(this);
1729             ActivityManager.getService().broadcastIntentWithFeature(
1730                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1731                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1732                     null, AppOpsManager.OP_NONE, null, false, true, user.getIdentifier());
1733         } catch (RemoteException e) {
1734             throw e.rethrowFromSystemServer();
1735         }
1736     }
1737 
1738     @Override
1739     @Deprecated
sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options)1740     public void sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options) {
1741         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1742         try {
1743             intent.prepareToLeaveProcess(this);
1744             ActivityManager.getService().broadcastIntentWithFeature(
1745                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1746                     null, Activity.RESULT_OK, null, null, null, null /*excludedPermissions=*/,
1747                     null, AppOpsManager.OP_NONE, options, false, true, user.getIdentifier());
1748         } catch (RemoteException e) {
1749             throw e.rethrowFromSystemServer();
1750         }
1751     }
1752 
1753     @Override
1754     @Deprecated
sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1755     public void sendStickyOrderedBroadcastAsUser(Intent intent,
1756             UserHandle user, BroadcastReceiver resultReceiver,
1757             Handler scheduler, int initialCode, String initialData,
1758             Bundle initialExtras) {
1759         IIntentReceiver rd = null;
1760         if (resultReceiver != null) {
1761             if (mPackageInfo != null) {
1762                 if (scheduler == null) {
1763                     scheduler = mMainThread.getHandler();
1764                 }
1765                 rd = mPackageInfo.getReceiverDispatcher(
1766                     resultReceiver, getOuterContext(), scheduler,
1767                     mMainThread.getInstrumentation(), false);
1768             } else {
1769                 if (scheduler == null) {
1770                     scheduler = mMainThread.getHandler();
1771                 }
1772                 rd = new LoadedApk.ReceiverDispatcher(mMainThread.getApplicationThread(),
1773                         resultReceiver, getOuterContext(), scheduler, null, false)
1774                                 .getIIntentReceiver();
1775             }
1776         }
1777         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1778         try {
1779             intent.prepareToLeaveProcess(this);
1780             ActivityManager.getService().broadcastIntentWithFeature(
1781                     mMainThread.getApplicationThread(), getAttributionTag(), intent, resolvedType,
1782                     rd, initialCode, initialData, initialExtras, null,
1783                     null /*excludedPermissions=*/, null, AppOpsManager.OP_NONE, null, true, true,
1784                     user.getIdentifier());
1785         } catch (RemoteException e) {
1786             throw e.rethrowFromSystemServer();
1787         }
1788     }
1789 
1790     @Override
1791     @Deprecated
removeStickyBroadcastAsUser(Intent intent, UserHandle user)1792     public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
1793         String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1794         if (resolvedType != null) {
1795             intent = new Intent(intent);
1796             intent.setDataAndType(intent.getData(), resolvedType);
1797         }
1798         try {
1799             intent.prepareToLeaveProcess(this);
1800             ActivityManager.getService().unbroadcastIntent(
1801                     mMainThread.getApplicationThread(), intent, user.getIdentifier());
1802         } catch (RemoteException e) {
1803             throw e.rethrowFromSystemServer();
1804         }
1805     }
1806 
1807     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)1808     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1809         return registerReceiver(receiver, filter, null, null);
1810     }
1811 
1812     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags)1813     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1814             int flags) {
1815         return registerReceiver(receiver, filter, null, null, flags);
1816     }
1817 
1818     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)1819     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1820             String broadcastPermission, Handler scheduler) {
1821         return registerReceiverInternal(receiver, getUserId(),
1822                 filter, broadcastPermission, scheduler, getOuterContext(), 0);
1823     }
1824 
1825     @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)1826     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1827             String broadcastPermission, Handler scheduler, int flags) {
1828         return registerReceiverInternal(receiver, getUserId(),
1829                 filter, broadcastPermission, scheduler, getOuterContext(), flags);
1830     }
1831 
1832     @Override
registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)1833     public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
1834             IntentFilter filter, String broadcastPermission, Handler scheduler) {
1835         return registerReceiverAsUser(receiver, UserHandle.ALL,
1836                 filter, broadcastPermission, scheduler);
1837     }
1838 
1839     @Override
registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)1840     public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
1841             IntentFilter filter, String broadcastPermission, Handler scheduler, int flags) {
1842         return registerReceiverAsUser(receiver, UserHandle.ALL,
1843                 filter, broadcastPermission, scheduler, flags);
1844     }
1845 
1846     @Override
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)1847     public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
1848             IntentFilter filter, String broadcastPermission, Handler scheduler) {
1849         return registerReceiverInternal(receiver, user.getIdentifier(),
1850                 filter, broadcastPermission, scheduler, getOuterContext(), 0);
1851     }
1852 
1853     @Override
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)1854     public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
1855             IntentFilter filter, String broadcastPermission, Handler scheduler, int flags) {
1856         return registerReceiverInternal(receiver, user.getIdentifier(),
1857                 filter, broadcastPermission, scheduler, getOuterContext(), flags);
1858     }
1859 
registerReceiverInternal(BroadcastReceiver receiver, int userId, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context, int flags)1860     private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
1861             IntentFilter filter, String broadcastPermission,
1862             Handler scheduler, Context context, int flags) {
1863         IIntentReceiver rd = null;
1864         if (receiver != null) {
1865             if (mPackageInfo != null && context != null) {
1866                 if (scheduler == null) {
1867                     scheduler = mMainThread.getHandler();
1868                 }
1869                 rd = mPackageInfo.getReceiverDispatcher(
1870                     receiver, context, scheduler,
1871                     mMainThread.getInstrumentation(), true);
1872             } else {
1873                 if (scheduler == null) {
1874                     scheduler = mMainThread.getHandler();
1875                 }
1876                 rd = new LoadedApk.ReceiverDispatcher(mMainThread.getApplicationThread(),
1877                         receiver, context, scheduler, null, true).getIIntentReceiver();
1878             }
1879         }
1880         try {
1881             final Intent intent = ActivityManager.getService().registerReceiverWithFeature(
1882                     mMainThread.getApplicationThread(), mBasePackageName, getAttributionTag(),
1883                     AppOpsManager.toReceiverId(receiver), rd, filter, broadcastPermission, userId,
1884                     flags);
1885             if (intent != null) {
1886                 intent.setExtrasClassLoader(getClassLoader());
1887                 // TODO: determine at registration time if caller is
1888                 // protecting themselves with signature permission
1889                 intent.prepareToEnterProcess(ActivityThread.isProtectedBroadcast(intent),
1890                         getAttributionSource());
1891             }
1892             return intent;
1893         } catch (RemoteException e) {
1894             throw e.rethrowFromSystemServer();
1895         }
1896     }
1897 
1898     @Override
unregisterReceiver(BroadcastReceiver receiver)1899     public void unregisterReceiver(BroadcastReceiver receiver) {
1900         if (mPackageInfo != null) {
1901             IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
1902                     getOuterContext(), receiver);
1903             try {
1904                 ActivityManager.getService().unregisterReceiver(rd);
1905             } catch (RemoteException e) {
1906                 throw e.rethrowFromSystemServer();
1907             }
1908         } else {
1909             throw new RuntimeException("Not supported in system context");
1910         }
1911     }
1912 
validateServiceIntent(Intent service)1913     private void validateServiceIntent(Intent service) {
1914         if (service.getComponent() == null && service.getPackage() == null) {
1915             if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1916                 IllegalArgumentException ex = new IllegalArgumentException(
1917                         "Service Intent must be explicit: " + service);
1918                 throw ex;
1919             } else {
1920                 Log.w(TAG, "Implicit intents with startService are not safe: " + service
1921                         + " " + Debug.getCallers(2, 3));
1922             }
1923         }
1924     }
1925 
1926     @Override
startService(Intent service)1927     public ComponentName startService(Intent service) {
1928         warnIfCallingFromSystemProcess();
1929         return startServiceCommon(service, false, mUser);
1930     }
1931 
1932     @Override
startForegroundService(Intent service)1933     public ComponentName startForegroundService(Intent service) {
1934         warnIfCallingFromSystemProcess();
1935         return startServiceCommon(service, true, mUser);
1936     }
1937 
1938     @Override
stopService(Intent service)1939     public boolean stopService(Intent service) {
1940         warnIfCallingFromSystemProcess();
1941         return stopServiceCommon(service, mUser);
1942     }
1943 
1944     @Override
startServiceAsUser(Intent service, UserHandle user)1945     public ComponentName startServiceAsUser(Intent service, UserHandle user) {
1946         return startServiceCommon(service, false, user);
1947     }
1948 
1949     @Override
startForegroundServiceAsUser(Intent service, UserHandle user)1950     public ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) {
1951         return startServiceCommon(service, true, user);
1952     }
1953 
startServiceCommon(Intent service, boolean requireForeground, UserHandle user)1954     private ComponentName startServiceCommon(Intent service, boolean requireForeground,
1955             UserHandle user) {
1956         // Keep this in sync with ActivityManagerLocal.startSdkSandboxService
1957         try {
1958             validateServiceIntent(service);
1959             service.prepareToLeaveProcess(this);
1960             ComponentName cn = ActivityManager.getService().startService(
1961                     mMainThread.getApplicationThread(), service,
1962                     service.resolveTypeIfNeeded(getContentResolver()), requireForeground,
1963                     getOpPackageName(), getAttributionTag(), user.getIdentifier());
1964             if (cn != null) {
1965                 if (cn.getPackageName().equals("!")) {
1966                     throw new SecurityException(
1967                             "Not allowed to start service " + service
1968                             + " without permission " + cn.getClassName());
1969                 } else if (cn.getPackageName().equals("!!")) {
1970                     throw new SecurityException(
1971                             "Unable to start service " + service
1972                             + ": " + cn.getClassName());
1973                 } else if (cn.getPackageName().equals("?")) {
1974                     throw ServiceStartNotAllowedException.newInstance(requireForeground,
1975                             "Not allowed to start service " + service + ": " + cn.getClassName());
1976                 }
1977             }
1978             // If we started a foreground service in the same package, remember the stack trace.
1979             if (cn != null && requireForeground) {
1980                 if (cn.getPackageName().equals(getOpPackageName())) {
1981                     Service.setStartForegroundServiceStackTrace(cn.getClassName(),
1982                             new StackTrace("Last startServiceCommon() call for this service was "
1983                                     + "made here"));
1984                 }
1985             }
1986             return cn;
1987         } catch (RemoteException e) {
1988             throw e.rethrowFromSystemServer();
1989         }
1990     }
1991 
1992     @Override
stopServiceAsUser(Intent service, UserHandle user)1993     public boolean stopServiceAsUser(Intent service, UserHandle user) {
1994         return stopServiceCommon(service, user);
1995     }
1996 
stopServiceCommon(Intent service, UserHandle user)1997     private boolean stopServiceCommon(Intent service, UserHandle user) {
1998         // // Keep this in sync with ActivityManagerLocal.stopSdkSandboxService
1999         try {
2000             validateServiceIntent(service);
2001             service.prepareToLeaveProcess(this);
2002             int res = ActivityManager.getService().stopService(
2003                 mMainThread.getApplicationThread(), service,
2004                 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
2005             if (res < 0) {
2006                 throw new SecurityException(
2007                         "Not allowed to stop service " + service);
2008             }
2009             return res != 0;
2010         } catch (RemoteException e) {
2011             throw e.rethrowFromSystemServer();
2012         }
2013     }
2014 
2015     @Override
bindService(Intent service, ServiceConnection conn, int flags)2016     public boolean bindService(Intent service, ServiceConnection conn, int flags) {
2017         warnIfCallingFromSystemProcess();
2018         return bindServiceCommon(service, conn, Integer.toUnsignedLong(flags), null,
2019                 mMainThread.getHandler(), null, getUser());
2020     }
2021 
2022     @Override
bindService(Intent service, ServiceConnection conn, @NonNull BindServiceFlags flags)2023     public boolean bindService(Intent service, ServiceConnection conn,
2024             @NonNull BindServiceFlags flags) {
2025         warnIfCallingFromSystemProcess();
2026         return bindServiceCommon(service, conn, flags.getValue(), null, mMainThread.getHandler(),
2027                 null, getUser());
2028     }
2029 
2030     @Override
bindService( Intent service, int flags, Executor executor, ServiceConnection conn)2031     public boolean bindService(
2032             Intent service, int flags, Executor executor, ServiceConnection conn) {
2033         return bindServiceCommon(service, conn, Integer.toUnsignedLong(flags), null, null, executor,
2034                 getUser());
2035     }
2036 
2037     @Override
bindService(Intent service, @NonNull BindServiceFlags flags, Executor executor, ServiceConnection conn)2038     public boolean bindService(Intent service, @NonNull BindServiceFlags flags, Executor executor,
2039             ServiceConnection conn) {
2040         return bindServiceCommon(service, conn, flags.getValue(), null, null, executor,
2041                 getUser());
2042     }
2043 
2044     @Override
bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)2045     public boolean bindIsolatedService(Intent service, int flags, String instanceName,
2046             Executor executor, ServiceConnection conn) {
2047         warnIfCallingFromSystemProcess();
2048         if (instanceName == null) {
2049             throw new NullPointerException("null instanceName");
2050         }
2051         return bindServiceCommon(service, conn, Integer.toUnsignedLong(flags), instanceName, null, executor,
2052                 getUser());
2053     }
2054 
2055     @Override
bindIsolatedService(Intent service, @NonNull BindServiceFlags flags, String instanceName, Executor executor, ServiceConnection conn)2056     public boolean bindIsolatedService(Intent service, @NonNull BindServiceFlags flags,
2057             String instanceName, Executor executor, ServiceConnection conn) {
2058         warnIfCallingFromSystemProcess();
2059         if (instanceName == null) {
2060             throw new NullPointerException("null instanceName");
2061         }
2062         return bindServiceCommon(service, conn, flags.getValue(), instanceName, null, executor,
2063                 getUser());
2064     }
2065 
2066     @Override
bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user)2067     public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
2068             UserHandle user) {
2069         return bindServiceCommon(service, conn, Integer.toUnsignedLong(flags), null,
2070                 mMainThread.getHandler(), null, user);
2071     }
2072 
2073     @Override
bindServiceAsUser(Intent service, ServiceConnection conn, @NonNull BindServiceFlags flags, UserHandle user)2074     public boolean bindServiceAsUser(Intent service, ServiceConnection conn,
2075             @NonNull BindServiceFlags flags, UserHandle user) {
2076         return bindServiceCommon(service, conn, flags.getValue(), null,
2077                 mMainThread.getHandler(), null, user);
2078     }
2079 
2080     /** @hide */
2081     @Override
bindServiceAsUser(Intent service, ServiceConnection conn, int flags, Handler handler, UserHandle user)2082     public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
2083             Handler handler, UserHandle user) {
2084         if (handler == null) {
2085             throw new IllegalArgumentException("handler must not be null.");
2086         }
2087         return bindServiceCommon(service, conn, Integer.toUnsignedLong(flags), null, handler,
2088                 null, user);
2089     }
2090 
2091     @Override
bindServiceAsUser(Intent service, ServiceConnection conn, @NonNull BindServiceFlags flags, Handler handler, UserHandle user)2092     public boolean bindServiceAsUser(Intent service, ServiceConnection conn,
2093             @NonNull BindServiceFlags flags, Handler handler, UserHandle user) {
2094         if (handler == null) {
2095             throw new IllegalArgumentException("handler must not be null.");
2096         }
2097         return bindServiceCommon(service, conn, flags.getValue(), null, handler,
2098                 null, user);
2099     }
2100 
2101     /** @hide */
2102     @Override
getServiceDispatcher(ServiceConnection conn, Handler handler, long flags)2103     public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler,
2104             long flags) {
2105         return mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
2106     }
2107 
2108     /** @hide */
2109     @Override
getIApplicationThread()2110     public IApplicationThread getIApplicationThread() {
2111         return mMainThread.getApplicationThread();
2112     }
2113 
2114     /** @hide */
2115     @NonNull
2116     @Override
getProcessToken()2117     public IBinder getProcessToken() {
2118         return getIApplicationThread().asBinder();
2119     }
2120 
2121     /** @hide */
2122     @Override
getMainThreadHandler()2123     public Handler getMainThreadHandler() {
2124         return mMainThread.getHandler();
2125     }
2126 
bindServiceCommon(Intent service, ServiceConnection conn, long flags, String instanceName, Handler handler, Executor executor, UserHandle user)2127     private boolean bindServiceCommon(Intent service, ServiceConnection conn, long flags,
2128             String instanceName, Handler handler, Executor executor, UserHandle user) {
2129         // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser and
2130         // ActivityManagerLocal.bindSdkSandboxService
2131         IServiceConnection sd;
2132         if (conn == null) {
2133             throw new IllegalArgumentException("connection is null");
2134         }
2135         if (handler != null && executor != null) {
2136             throw new IllegalArgumentException("Handler and Executor both supplied");
2137         }
2138         if (mPackageInfo != null) {
2139             if (executor != null) {
2140                 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
2141             } else {
2142                 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
2143             }
2144         } else {
2145             throw new RuntimeException("Not supported in system context");
2146         }
2147         validateServiceIntent(service);
2148         try {
2149             IBinder token = getActivityToken();
2150             if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
2151                     && mPackageInfo.getApplicationInfo().targetSdkVersion
2152                     < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
2153                 flags |= BIND_WAIVE_PRIORITY;
2154             }
2155             service.prepareToLeaveProcess(this);
2156             int res = ActivityManager.getService().bindServiceInstance(
2157                     mMainThread.getApplicationThread(), getActivityToken(), service,
2158                     service.resolveTypeIfNeeded(getContentResolver()),
2159                     sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
2160             if (res < 0) {
2161                 throw new SecurityException(
2162                         "Not allowed to bind to service " + service);
2163             }
2164             return res != 0;
2165         } catch (RemoteException e) {
2166             throw e.rethrowFromSystemServer();
2167         }
2168     }
2169 
2170     @Override
updateServiceGroup(@onNull ServiceConnection conn, int group, int importance)2171     public void updateServiceGroup(@NonNull ServiceConnection conn, int group, int importance) {
2172         if (conn == null) {
2173             throw new IllegalArgumentException("connection is null");
2174         }
2175         if (mPackageInfo != null) {
2176             IServiceConnection sd = mPackageInfo.lookupServiceDispatcher(conn, getOuterContext());
2177             if (sd == null) {
2178                 throw new IllegalArgumentException("ServiceConnection not currently bound: "
2179                         + conn);
2180             }
2181             try {
2182                 ActivityManager.getService().updateServiceGroup(sd, group, importance);
2183             } catch (RemoteException e) {
2184                 throw e.rethrowFromSystemServer();
2185             }
2186         } else {
2187             throw new RuntimeException("Not supported in system context");
2188         }
2189     }
2190 
2191     @Override
unbindService(ServiceConnection conn)2192     public void unbindService(ServiceConnection conn) {
2193         if (conn == null) {
2194             throw new IllegalArgumentException("connection is null");
2195         }
2196         if (mPackageInfo != null) {
2197             IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
2198                     getOuterContext(), conn);
2199             try {
2200                 ActivityManager.getService().unbindService(sd);
2201             } catch (RemoteException e) {
2202                 throw e.rethrowFromSystemServer();
2203             }
2204         } else {
2205             throw new RuntimeException("Not supported in system context");
2206         }
2207     }
2208 
2209     @Override
startInstrumentation(ComponentName className, String profileFile, Bundle arguments)2210     public boolean startInstrumentation(ComponentName className,
2211             String profileFile, Bundle arguments) {
2212         try {
2213             if (arguments != null) {
2214                 arguments.setAllowFds(false);
2215             }
2216             return ActivityManager.getService().startInstrumentation(
2217                     className, profileFile, 0, arguments, null, null, getUserId(),
2218                     null /* ABI override */);
2219         } catch (RemoteException e) {
2220             throw e.rethrowFromSystemServer();
2221         }
2222     }
2223 
2224     @Override
getSystemService(String name)2225     public Object getSystemService(String name) {
2226         if (vmIncorrectContextUseEnabled()) {
2227             // Check incorrect Context usage.
2228             if (WINDOW_SERVICE.equals(name) && !isUiContext()) {
2229                 final String errorMessage = "Tried to access visual service "
2230                         + SystemServiceRegistry.getSystemServiceClassName(name)
2231                         + " from a non-visual Context:" + getOuterContext();
2232                 final String message = "WindowManager should be accessed from Activity or other "
2233                         + "visual Context. Use an Activity or a Context created with "
2234                         + "Context#createWindowContext(int, Bundle), which are adjusted to "
2235                         + "the configuration and visual bounds of an area on screen.";
2236                 final Exception exception = new IllegalAccessException(errorMessage);
2237                 StrictMode.onIncorrectContextUsed(message, exception);
2238                 Log.e(TAG, errorMessage + " " + message, exception);
2239             }
2240         }
2241         return SystemServiceRegistry.getSystemService(this, name);
2242     }
2243 
2244     @Override
getSystemServiceName(Class<?> serviceClass)2245     public String getSystemServiceName(Class<?> serviceClass) {
2246         return SystemServiceRegistry.getSystemServiceName(serviceClass);
2247     }
2248 
2249     /** @hide */
2250     @Override
isUiContext()2251     public boolean isUiContext() {
2252         switch (mContextType) {
2253             case CONTEXT_TYPE_ACTIVITY:
2254             case CONTEXT_TYPE_WINDOW_CONTEXT:
2255             case CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI:
2256                 return true;
2257             case CONTEXT_TYPE_DISPLAY_CONTEXT:
2258             case CONTEXT_TYPE_NON_UI: {
2259                 return false;
2260             }
2261             default:
2262                 return false;
2263         }
2264     }
2265 
2266     /** @hide */
2267     @Override
isConfigurationContext()2268     public boolean isConfigurationContext() {
2269         return isUiContext() || mIsConfigurationBasedContext;
2270     }
2271 
2272     /**
2273      * Temporary workaround to permit incorrect usages of Context by SystemUI.
2274      * TODO(b/147647877): Fix usages and remove.
2275      */
2276     @SuppressWarnings("AndroidFrameworkClientSidePermissionCheck")
isSystemOrSystemUI(Context context)2277     private static boolean isSystemOrSystemUI(Context context) {
2278         return ActivityThread.isSystem() || context.checkPermission(
2279                 "android.permission.STATUS_BAR_SERVICE",
2280                 Binder.getCallingPid(),
2281                 Binder.getCallingUid()) == PERMISSION_GRANTED;
2282     }
2283 
2284     @Override
checkPermission(String permission, int pid, int uid)2285     public int checkPermission(String permission, int pid, int uid) {
2286         if (permission == null) {
2287             throw new IllegalArgumentException("permission is null");
2288         }
2289         if (mParams.isRenouncedPermission(permission)
2290                 && pid == android.os.Process.myPid() && uid == android.os.Process.myUid()) {
2291             Log.v(TAG, "Treating renounced permission " + permission + " as denied");
2292             return PERMISSION_DENIED;
2293         }
2294 
2295         // When checking a device-aware permission on a remote device, if the permission is CAMERA
2296         // or RECORD_AUDIO we need to check remote device's corresponding capability. If the remote
2297         // device doesn't have capability fall back to checking permission on the default device.
2298         // Note: we only perform permission check redirection when the device id is not explicitly
2299         // set in the context.
2300         int deviceId = getDeviceId();
2301         if (deviceId != Context.DEVICE_ID_DEFAULT
2302                 && !mIsExplicitDeviceId
2303                 && PermissionManager.DEVICE_AWARE_PERMISSIONS.contains(permission)) {
2304             VirtualDeviceManager virtualDeviceManager =
2305                     getSystemService(VirtualDeviceManager.class);
2306             VirtualDevice virtualDevice = virtualDeviceManager.getVirtualDevice(deviceId);
2307             if (virtualDevice != null) {
2308                 if ((Objects.equals(permission, Manifest.permission.RECORD_AUDIO)
2309                                 && !virtualDevice.hasCustomAudioInputSupport())
2310                         || (Objects.equals(permission, Manifest.permission.CAMERA)
2311                                 && !virtualDevice.hasCustomCameraSupport())) {
2312                     deviceId = Context.DEVICE_ID_DEFAULT;
2313                 }
2314             } else {
2315                 Slog.e(
2316                         TAG,
2317                         "virtualDevice is not found when device id is not default. deviceId = "
2318                                 + deviceId);
2319             }
2320         }
2321 
2322         return PermissionManager.checkPermission(permission, pid, uid, deviceId);
2323     }
2324 
2325     /** @hide */
2326     @Override
checkPermission(String permission, int pid, int uid, IBinder callerToken)2327     public int checkPermission(String permission, int pid, int uid, IBinder callerToken) {
2328         if (permission == null) {
2329             throw new IllegalArgumentException("permission is null");
2330         }
2331         if (mParams.isRenouncedPermission(permission)
2332                 && pid == android.os.Process.myPid() && uid == android.os.Process.myUid()) {
2333             Log.v(TAG, "Treating renounced permission " + permission + " as denied");
2334             return PERMISSION_DENIED;
2335         }
2336         return checkPermission(permission, pid, uid);
2337     }
2338 
2339     @Override
revokeSelfPermissionsOnKill(@onNull Collection<String> permissions)2340     public void revokeSelfPermissionsOnKill(@NonNull Collection<String> permissions) {
2341         getSystemService(PermissionControllerManager.class).revokeSelfPermissionsOnKill(
2342                 getPackageName(), new ArrayList<String>(permissions));
2343     }
2344 
2345     @Override
checkCallingPermission(String permission)2346     public int checkCallingPermission(String permission) {
2347         if (permission == null) {
2348             throw new IllegalArgumentException("permission is null");
2349         }
2350 
2351         int pid = Binder.getCallingPid();
2352         if (pid != Process.myPid()) {
2353             return checkPermission(permission, pid, Binder.getCallingUid());
2354         }
2355         return PackageManager.PERMISSION_DENIED;
2356     }
2357 
2358     @Override
checkCallingOrSelfPermission(String permission)2359     public int checkCallingOrSelfPermission(String permission) {
2360         if (permission == null) {
2361             throw new IllegalArgumentException("permission is null");
2362         }
2363 
2364         return checkPermission(permission, Binder.getCallingPid(),
2365                 Binder.getCallingUid());
2366     }
2367 
2368     @Override
checkSelfPermission(String permission)2369     public int checkSelfPermission(String permission) {
2370         if (permission == null) {
2371             throw new IllegalArgumentException("permission is null");
2372         }
2373         if (mParams.isRenouncedPermission(permission)) {
2374             Log.v(TAG, "Treating renounced permission " + permission + " as denied");
2375             return PERMISSION_DENIED;
2376         }
2377 
2378         return checkPermission(permission, Process.myPid(), Process.myUid());
2379     }
2380 
enforce( String permission, int resultOfCheck, boolean selfToo, int uid, String message)2381     private void enforce(
2382             String permission, int resultOfCheck,
2383             boolean selfToo, int uid, String message) {
2384         if (resultOfCheck != PERMISSION_GRANTED) {
2385             throw new SecurityException(
2386                     (message != null ? (message + ": ") : "") +
2387                     (selfToo
2388                      ? "Neither user " + uid + " nor current process has "
2389                      : "uid " + uid + " does not have ") +
2390                     permission +
2391                     ".");
2392         }
2393     }
2394 
2395     @Override
enforcePermission( String permission, int pid, int uid, String message)2396     public void enforcePermission(
2397             String permission, int pid, int uid, String message) {
2398         enforce(permission,
2399                 checkPermission(permission, pid, uid),
2400                 false,
2401                 uid,
2402                 message);
2403     }
2404 
2405     @Override
enforceCallingPermission(String permission, String message)2406     public void enforceCallingPermission(String permission, String message) {
2407         enforce(permission,
2408                 checkCallingPermission(permission),
2409                 false,
2410                 Binder.getCallingUid(),
2411                 message);
2412     }
2413 
2414     @Override
enforceCallingOrSelfPermission( String permission, String message)2415     public void enforceCallingOrSelfPermission(
2416             String permission, String message) {
2417         enforce(permission,
2418                 checkCallingOrSelfPermission(permission),
2419                 true,
2420                 Binder.getCallingUid(),
2421                 message);
2422     }
2423 
2424     @Override
grantUriPermission(String toPackage, Uri uri, int modeFlags)2425     public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
2426          try {
2427             ActivityManager.getService().grantUriPermission(
2428                     mMainThread.getApplicationThread(), toPackage,
2429                     ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
2430         } catch (RemoteException e) {
2431             throw e.rethrowFromSystemServer();
2432         }
2433     }
2434 
2435     @Override
revokeUriPermission(Uri uri, int modeFlags)2436     public void revokeUriPermission(Uri uri, int modeFlags) {
2437          try {
2438             ActivityManager.getService().revokeUriPermission(
2439                     mMainThread.getApplicationThread(), null,
2440                     ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
2441         } catch (RemoteException e) {
2442             throw e.rethrowFromSystemServer();
2443         }
2444     }
2445 
2446     @Override
revokeUriPermission(String targetPackage, Uri uri, int modeFlags)2447     public void revokeUriPermission(String targetPackage, Uri uri, int modeFlags) {
2448         try {
2449             ActivityManager.getService().revokeUriPermission(
2450                     mMainThread.getApplicationThread(), targetPackage,
2451                     ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
2452         } catch (RemoteException e) {
2453             throw e.rethrowFromSystemServer();
2454         }
2455     }
2456 
2457     @Override
checkUriPermission(Uri uri, int pid, int uid, int modeFlags)2458     public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
2459         try {
2460             return ActivityManager.getService().checkUriPermission(
2461                     ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
2462                     resolveUserId(uri), null);
2463         } catch (RemoteException e) {
2464             throw e.rethrowFromSystemServer();
2465         }
2466     }
2467 
2468     @Override
checkContentUriPermissionFull(Uri uri, int pid, int uid, int modeFlags)2469     public int checkContentUriPermissionFull(Uri uri, int pid, int uid, int modeFlags) {
2470         try {
2471             return ActivityManager.getService().checkContentUriPermissionFull(
2472                     ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
2473                     resolveUserId(uri));
2474         } catch (RemoteException e) {
2475             throw e.rethrowFromSystemServer();
2476         }
2477     }
2478 
2479     @NonNull
2480     @Override
checkUriPermissions(@onNull List<Uri> uris, int pid, int uid, int modeFlags)2481     public int[] checkUriPermissions(@NonNull List<Uri> uris, int pid, int uid,
2482             int modeFlags) {
2483         try {
2484             return ActivityManager.getService().checkUriPermissions(uris, pid, uid, modeFlags,
2485                     getUserId(), null);
2486         } catch (RemoteException e) {
2487             throw e.rethrowFromSystemServer();
2488         }
2489     }
2490 
2491     /** @hide */
2492     @Override
checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken)2493     public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) {
2494         try {
2495             return ActivityManager.getService().checkUriPermission(
2496                     ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
2497                     resolveUserId(uri), callerToken);
2498         } catch (RemoteException e) {
2499             throw e.rethrowFromSystemServer();
2500         }
2501     }
2502 
resolveUserId(Uri uri)2503     private int resolveUserId(Uri uri) {
2504         return ContentProvider.getUserIdFromUri(uri, getUserId());
2505     }
2506 
2507     @Override
checkCallingUriPermission(Uri uri, int modeFlags)2508     public int checkCallingUriPermission(Uri uri, int modeFlags) {
2509         int pid = Binder.getCallingPid();
2510         if (pid != Process.myPid()) {
2511             return checkUriPermission(uri, pid,
2512                     Binder.getCallingUid(), modeFlags);
2513         }
2514         return PackageManager.PERMISSION_DENIED;
2515     }
2516 
2517     @NonNull
2518     @Override
checkCallingUriPermissions(@onNull List<Uri> uris, int modeFlags)2519     public int[] checkCallingUriPermissions(@NonNull List<Uri> uris, int modeFlags) {
2520         int pid = Binder.getCallingPid();
2521         if (pid != Process.myPid()) {
2522             return checkUriPermissions(uris, pid, Binder.getCallingUid(), modeFlags);
2523         }
2524         int[] res = new int[uris.size()];
2525         Arrays.fill(res, PERMISSION_DENIED);
2526         return res;
2527     }
2528 
2529     @Override
checkCallingOrSelfUriPermission(Uri uri, int modeFlags)2530     public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
2531         return checkUriPermission(uri, Binder.getCallingPid(),
2532                 Binder.getCallingUid(), modeFlags);
2533     }
2534 
2535     @NonNull
2536     @Override
checkCallingOrSelfUriPermissions(@onNull List<Uri> uris, int modeFlags)2537     public int[] checkCallingOrSelfUriPermissions(@NonNull List<Uri> uris, int modeFlags) {
2538         return checkUriPermissions(uris, Binder.getCallingPid(), Binder.getCallingUid(), modeFlags);
2539     }
2540 
2541     @Override
checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)2542     public int checkUriPermission(Uri uri, String readPermission,
2543             String writePermission, int pid, int uid, int modeFlags) {
2544         if (DEBUG) {
2545             Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
2546                     + readPermission + " writePermission=" + writePermission
2547                     + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
2548         }
2549         if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2550             if (readPermission == null
2551                     || checkPermission(readPermission, pid, uid)
2552                     == PERMISSION_GRANTED) {
2553                 return PERMISSION_GRANTED;
2554             }
2555         }
2556         if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2557             if (writePermission == null
2558                     || checkPermission(writePermission, pid, uid)
2559                     == PERMISSION_GRANTED) {
2560                 return PERMISSION_GRANTED;
2561             }
2562         }
2563         return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
2564                 : PackageManager.PERMISSION_DENIED;
2565     }
2566 
uriModeFlagToString(int uriModeFlags)2567     private String uriModeFlagToString(int uriModeFlags) {
2568         StringBuilder builder = new StringBuilder();
2569         if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2570             builder.append("read and ");
2571         }
2572         if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2573             builder.append("write and ");
2574         }
2575         if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
2576             builder.append("persistable and ");
2577         }
2578         if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
2579             builder.append("prefix and ");
2580         }
2581 
2582         if (builder.length() > 5) {
2583             builder.setLength(builder.length() - 5);
2584             return builder.toString();
2585         } else {
2586             throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags);
2587         }
2588     }
2589 
enforceForUri( int modeFlags, int resultOfCheck, boolean selfToo, int uid, Uri uri, String message)2590     private void enforceForUri(
2591             int modeFlags, int resultOfCheck, boolean selfToo,
2592             int uid, Uri uri, String message) {
2593         if (resultOfCheck != PERMISSION_GRANTED) {
2594             throw new SecurityException(
2595                     (message != null ? (message + ": ") : "") +
2596                     (selfToo
2597                      ? "Neither user " + uid + " nor current process has "
2598                      : "User " + uid + " does not have ") +
2599                     uriModeFlagToString(modeFlags) +
2600                     " permission on " +
2601                     uri +
2602                     ".");
2603         }
2604     }
2605 
2606     @Override
enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message)2607     public void enforceUriPermission(
2608             Uri uri, int pid, int uid, int modeFlags, String message) {
2609         enforceForUri(
2610                 modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
2611                 false, uid, uri, message);
2612     }
2613 
2614     @Override
enforceCallingUriPermission( Uri uri, int modeFlags, String message)2615     public void enforceCallingUriPermission(
2616             Uri uri, int modeFlags, String message) {
2617         enforceForUri(
2618                 modeFlags, checkCallingUriPermission(uri, modeFlags),
2619                 false,
2620                 Binder.getCallingUid(), uri, message);
2621     }
2622 
2623     @Override
enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message)2624     public void enforceCallingOrSelfUriPermission(
2625             Uri uri, int modeFlags, String message) {
2626         enforceForUri(
2627                 modeFlags,
2628                 checkCallingOrSelfUriPermission(uri, modeFlags), true,
2629                 Binder.getCallingUid(), uri, message);
2630     }
2631 
2632     @Override
enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)2633     public void enforceUriPermission(
2634             Uri uri, String readPermission, String writePermission,
2635             int pid, int uid, int modeFlags, String message) {
2636         enforceForUri(modeFlags,
2637                       checkUriPermission(
2638                               uri, readPermission, writePermission, pid, uid,
2639                               modeFlags),
2640                       false,
2641                       uid,
2642                       uri,
2643                       message);
2644     }
2645 
2646     /**
2647      * Logs a warning if the system process directly called a method such as
2648      * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
2649      * The "AsUser" variants allow us to properly enforce the user's restrictions.
2650      */
warnIfCallingFromSystemProcess()2651     private void warnIfCallingFromSystemProcess() {
2652         if (Process.myUid() == Process.SYSTEM_UID) {
2653             Slog.w(TAG, "Calling a method in the system process without a qualified user: "
2654                     + Debug.getCallers(5));
2655         }
2656     }
2657 
createResources(IBinder activityToken, LoadedApk pi, String splitName, @Nullable Integer overrideDisplayId, Configuration overrideConfig, CompatibilityInfo compatInfo, List<ResourcesLoader> resourcesLoader)2658     private static Resources createResources(IBinder activityToken, LoadedApk pi, String splitName,
2659             @Nullable Integer overrideDisplayId, Configuration overrideConfig,
2660             CompatibilityInfo compatInfo, List<ResourcesLoader> resourcesLoader) {
2661         final String[] splitResDirs;
2662         final ClassLoader classLoader;
2663         try {
2664             splitResDirs = pi.getSplitPaths(splitName);
2665             classLoader = pi.getSplitClassLoader(splitName);
2666         } catch (NameNotFoundException e) {
2667             throw new RuntimeException(e);
2668         }
2669         return ResourcesManager.getInstance().getResources(activityToken,
2670                 pi.getResDir(),
2671                 splitResDirs,
2672                 pi.getOverlayDirs(),
2673                 pi.getOverlayPaths(),
2674                 pi.getApplicationInfo().sharedLibraryFiles,
2675                 overrideDisplayId,
2676                 overrideConfig,
2677                 compatInfo,
2678                 classLoader,
2679                 resourcesLoader);
2680     }
2681 
2682     @Override
createApplicationContext(ApplicationInfo application, int flags)2683     public Context createApplicationContext(ApplicationInfo application, int flags)
2684             throws NameNotFoundException {
2685         final UserHandle user = new UserHandle(UserHandle.getUserId(application.uid));
2686         return createApplicationContextAsUser(application, flags, user);
2687     }
2688 
createApplicationContextAsUser(ApplicationInfo application, int flags, UserHandle user)2689     private Context createApplicationContextAsUser(ApplicationInfo application, int flags,
2690                                                    UserHandle user) throws NameNotFoundException {
2691         LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(),
2692                 flags | CONTEXT_REGISTER_PACKAGE);
2693         if (pi != null) {
2694             ContextImpl c = new ContextImpl(this, mMainThread, pi, ContextParams.EMPTY,
2695                     mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), null,
2696                     mToken, user, flags, null,
2697                     null, mDeviceId, mIsExplicitDeviceId);
2698 
2699             final int displayId = getDisplayId();
2700             final Integer overrideDisplayId = mForceDisplayOverrideInResources
2701                     ? displayId : null;
2702 
2703             c.setResources(createResources(mToken, pi, null, overrideDisplayId, null,
2704                     getDisplayAdjustments(displayId).getCompatibilityInfo(), null));
2705             if (c.mResources != null) {
2706                 return c;
2707             }
2708         }
2709 
2710         throw new PackageManager.NameNotFoundException(
2711                 "Application package " + application.packageName + " not found");
2712     }
2713 
2714     @Override
createContextForSdkInSandbox(ApplicationInfo sdkInfo, int flags)2715     public Context createContextForSdkInSandbox(ApplicationInfo sdkInfo, int flags)
2716             throws NameNotFoundException {
2717         if (!Process.isSdkSandbox()) {
2718             throw new SecurityException("API can only be called from SdkSandbox process");
2719         }
2720 
2721         final UserHandle user = sdkInfo.uid >= 0
2722                 ? new UserHandle(UserHandle.getUserId(sdkInfo.uid)) : Process.myUserHandle();
2723         ContextImpl ctx = (ContextImpl) createApplicationContextAsUser(sdkInfo, flags, user);
2724 
2725         // Set sandbox app's context as the application context for sdk context
2726         ctx.mPackageInfo.makeApplicationInner(/*forceDefaultAppClass=*/false,
2727                 /*instrumentation=*/null);
2728 
2729         return ctx;
2730     }
2731 
2732     @Override
createPackageContext(String packageName, int flags)2733     public Context createPackageContext(String packageName, int flags)
2734             throws NameNotFoundException {
2735         return createPackageContextAsUser(packageName, flags, mUser);
2736     }
2737 
2738     @Override
createPackageContextAsUser(String packageName, int flags, UserHandle user)2739     public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
2740             throws NameNotFoundException {
2741         if (packageName.equals("system") || packageName.equals("android")) {
2742             // The system resources are loaded in every application, so we can safely copy
2743             // the context without reloading Resources.
2744             return new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2745                     mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), null,
2746                     mToken, user, flags, null, null, mDeviceId, mIsExplicitDeviceId);
2747         }
2748 
2749         LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
2750                 flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
2751         if (pi != null) {
2752             ContextImpl c = new ContextImpl(this, mMainThread, pi, mParams,
2753                     mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), null,
2754                     mToken, user, flags, null, null, mDeviceId, mIsExplicitDeviceId);
2755 
2756             final int displayId = getDisplayId();
2757             final Integer overrideDisplayId = mForceDisplayOverrideInResources
2758                     ? displayId : null;
2759 
2760             c.setResources(createResources(mToken, pi, null, overrideDisplayId, null,
2761                     getDisplayAdjustments(displayId).getCompatibilityInfo(), null));
2762             if (c.mResources != null) {
2763                 return c;
2764             }
2765         }
2766 
2767         // Should be a better exception.
2768         throw new PackageManager.NameNotFoundException(
2769                 "Application package " + packageName + " not found");
2770     }
2771 
2772     @Override
createContextAsUser(UserHandle user, @CreatePackageOptions int flags)2773     public Context createContextAsUser(UserHandle user, @CreatePackageOptions int flags) {
2774         try {
2775             return createPackageContextAsUser(getPackageName(), flags, user);
2776         } catch (NameNotFoundException e) {
2777             throw new IllegalStateException("Own package not found for user "
2778                     + user.getIdentifier() + ": package=" + getPackageName());
2779         }
2780     }
2781 
2782     @Override
createContextForSplit(String splitName)2783     public Context createContextForSplit(String splitName) throws NameNotFoundException {
2784         if (!mPackageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
2785             // All Splits are always loaded.
2786             return this;
2787         }
2788 
2789         final ClassLoader classLoader = mPackageInfo.getSplitClassLoader(splitName);
2790         final String[] paths = mPackageInfo.getSplitPaths(splitName);
2791 
2792         final ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2793                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), splitName,
2794                 mToken, mUser, mFlags, classLoader, null, mDeviceId, mIsExplicitDeviceId);
2795 
2796         context.setResources(ResourcesManager.getInstance().getResources(
2797                 mToken,
2798                 mPackageInfo.getResDir(),
2799                 paths,
2800                 mPackageInfo.getOverlayDirs(),
2801                 mPackageInfo.getOverlayPaths(),
2802                 mPackageInfo.getApplicationInfo().sharedLibraryFiles,
2803                 mForceDisplayOverrideInResources ? getDisplayId() : null,
2804                 null,
2805                 mPackageInfo.getCompatibilityInfo(),
2806                 classLoader,
2807                 mResources.getLoaders()));
2808         return context;
2809     }
2810 
2811     @Override
createConfigurationContext(Configuration overrideConfiguration)2812     public Context createConfigurationContext(Configuration overrideConfiguration) {
2813         if (overrideConfiguration == null) {
2814             throw new IllegalArgumentException("overrideConfiguration must not be null");
2815         }
2816 
2817         if (mForceDisplayOverrideInResources) {
2818             // Ensure the resources display metrics are adjusted to match the display this context
2819             // is based on.
2820             Configuration displayAdjustedConfig = new Configuration();
2821             displayAdjustedConfig.setTo(mDisplay.getDisplayAdjustments().getConfiguration(),
2822                     ActivityInfo.CONFIG_WINDOW_CONFIGURATION, 1);
2823             displayAdjustedConfig.updateFrom(overrideConfiguration);
2824             overrideConfiguration = displayAdjustedConfig;
2825         }
2826 
2827         ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2828                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
2829                 mToken, mUser, mFlags, mClassLoader, null, mDeviceId,
2830                 mIsExplicitDeviceId);
2831         context.mIsConfigurationBasedContext = true;
2832 
2833         final int displayId = getDisplayId();
2834         final Integer overrideDisplayId = mForceDisplayOverrideInResources
2835                 ? displayId : null;
2836         context.setResources(createResources(mToken, mPackageInfo, mSplitName, overrideDisplayId,
2837                 overrideConfiguration, getDisplayAdjustments(displayId).getCompatibilityInfo(),
2838                 mResources.getLoaders()));
2839         return context;
2840     }
2841 
2842     @Override
createDisplayContext(Display display)2843     public Context createDisplayContext(Display display) {
2844         if (display == null) {
2845             throw new IllegalArgumentException("display must not be null");
2846         }
2847 
2848         ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2849                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
2850                 mToken, mUser, mFlags, mClassLoader, null, mDeviceId, mIsExplicitDeviceId);
2851 
2852         final int displayId = display.getDisplayId();
2853 
2854         // Ensure the resources display metrics are adjusted to match the provided display.
2855         Configuration overrideConfig = new Configuration();
2856         overrideConfig.setTo(display.getDisplayAdjustments().getConfiguration(),
2857                 ActivityInfo.CONFIG_WINDOW_CONFIGURATION, 1);
2858 
2859         context.setResources(createResources(mToken, mPackageInfo, mSplitName, displayId,
2860                 overrideConfig, display.getDisplayAdjustments().getCompatibilityInfo(),
2861                 mResources.getLoaders()));
2862         context.setDisplay(display);
2863         // Inherit context type if the container is from System or System UI context to bypass
2864         // UI context check.
2865         context.mContextType = mContextType == CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI
2866                 ? CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI : CONTEXT_TYPE_DISPLAY_CONTEXT;
2867         // Display contexts and any context derived from a display context should always override
2868         // the display that would otherwise be inherited from mToken (or the global configuration if
2869         // mToken is null).
2870         context.mForceDisplayOverrideInResources = true;
2871         // The configuration is overridden by display adjustments' configuration and won't receive
2872         // configuration changes. This context won't be regarded as having the proper configuration
2873         // anymore.
2874         context.mIsConfigurationBasedContext = false;
2875         return context;
2876     }
2877 
setDisplay(Display display)2878     private void setDisplay(Display display) {
2879         mDisplay = display;
2880         if (display != null) {
2881             updateDeviceIdIfChanged(display.getDisplayId());
2882         }
2883     }
2884 
2885     @Override
createDeviceContext(int deviceId)2886     public @NonNull Context createDeviceContext(int deviceId) {
2887         if (deviceId != Context.DEVICE_ID_DEFAULT) {
2888             VirtualDeviceManager vdm = getSystemService(VirtualDeviceManager.class);
2889             if (vdm == null || !vdm.isValidVirtualDeviceId(deviceId)) {
2890                 throw new IllegalArgumentException(
2891                         "Not a valid ID of the default device or any virtual device: " + deviceId);
2892             }
2893         }
2894 
2895         return new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2896                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
2897                 mToken, mUser, mFlags, mClassLoader, null, deviceId, true);
2898     }
2899 
2900     @NonNull
2901     @Override
createWindowContext(@indowType int type, @Nullable Bundle options)2902     public WindowContext createWindowContext(@WindowType int type,
2903             @Nullable Bundle options) {
2904         if (getDisplay() == null) {
2905             throw new UnsupportedOperationException("Please call this API with context associated"
2906                     + " with a display instance, such as Activity or context created via"
2907                     + " Context#createDisplayContext(Display), or try to invoke"
2908                     + " Context#createWindowContext(Display, int, Bundle)");
2909         }
2910         return createWindowContextInternal(getDisplay(), type, options);
2911     }
2912 
2913     @NonNull
2914     @Override
createWindowContext(@onNull Display display, @WindowType int type, @Nullable Bundle options)2915     public WindowContext createWindowContext(@NonNull Display display, @WindowType int type,
2916             @Nullable Bundle options) {
2917         if (display == null) {
2918             throw new IllegalArgumentException("Display must not be null");
2919         }
2920         return createWindowContextInternal(display, type, options);
2921     }
2922 
2923     /**
2924      * The internal implementation of {@link Context#createWindowContext(int, Bundle)} and
2925      * {@link Context#createWindowContext(Display, int, Bundle)}.
2926      *
2927      * @param display The {@link Display} instance to be associated with.
2928      *
2929      * @see Context#createWindowContext(Display, int, Bundle)
2930      * @see Context#createWindowContext(int, Bundle)
2931      */
createWindowContextInternal(@onNull Display display, @WindowType int type, @Nullable Bundle options)2932     private WindowContext createWindowContextInternal(@NonNull Display display,
2933             @WindowType int type, @Nullable Bundle options) {
2934         // Step 1. Create a WindowTokenClient to associate with the WindowContext's Resources
2935         //         instance and it will be later used to receive configuration updates from the
2936         //         server side.
2937         final WindowTokenClient windowTokenClient = new WindowTokenClient();
2938 
2939         // Step 2. Create the base context of the window context, it will also create a Resources
2940         //         associated with the WindowTokenClient and set the token to the base context.
2941         final ContextImpl windowContextBase = createWindowContextBase(windowTokenClient,
2942                 display.getDisplayId());
2943 
2944         // Step 3. Create a WindowContext instance and set it as the outer context of the base
2945         //         context to make the service obtained by #getSystemService(String) able to query
2946         //         the WindowContext's WindowManager instead of the default one.
2947         final WindowContext windowContext = new WindowContext(windowContextBase, type, options);
2948         windowContextBase.setOuterContext(windowContext);
2949 
2950         // Step 4. Attach the WindowContext to the WindowTokenClient. In this way, when there's a
2951         //         configuration update from the server side, the update will then apply to
2952         //         WindowContext's resources.
2953         windowTokenClient.attachContext(windowContext);
2954 
2955         // Step 5. Associate the WindowContext's token to a DisplayArea.
2956         windowContext.attachToDisplayArea();
2957 
2958         return windowContext;
2959     }
2960 
2961     @NonNull
2962     @Override
createTokenContext(@onNull IBinder token, @NonNull Display display)2963     public Context createTokenContext(@NonNull IBinder token, @NonNull Display display) {
2964         if (display == null) {
2965             throw new IllegalArgumentException("Display must not be null");
2966         }
2967         return createWindowContextBase(token, display.getDisplayId());
2968     }
2969 
2970     /**
2971      * Creates the base {@link Context} for UI context to associate with a non-{@link Activity}
2972      * window.
2973      *
2974      * @param token The token to associate with {@link Resources}
2975      * @param displayId The ID of {@link Display} to associate with.
2976      *
2977      * @see #createWindowContext(Display, int, Bundle)
2978      * @see #createTokenContext(IBinder, Display)
2979      */
2980     @UiContext
createWindowContextBase(@onNull IBinder token, int displayId)2981     ContextImpl createWindowContextBase(@NonNull IBinder token, int displayId) {
2982         ContextImpl baseContext = new ContextImpl(this, mMainThread, mPackageInfo, mParams,
2983                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
2984                 token, mUser, mFlags, mClassLoader, null, mDeviceId, mIsExplicitDeviceId);
2985         // Window contexts receive configurations directly from the server and as such do not
2986         // need to override their display in ResourcesManager.
2987         baseContext.mForceDisplayOverrideInResources = false;
2988         baseContext.mContextType = CONTEXT_TYPE_WINDOW_CONTEXT;
2989 
2990         final Resources windowContextResources = createWindowContextResources(baseContext);
2991         baseContext.setResources(windowContextResources);
2992         // Associate the display with window context resources so that configuration update from
2993         // the server side will also apply to the display's metrics.
2994         baseContext.setDisplay(ResourcesManager.getInstance().getAdjustedDisplay(
2995                 displayId, windowContextResources));
2996 
2997         return baseContext;
2998     }
2999 
3000     /**
3001      * Creates the {@link Resources} to associate with the {@link WindowContext}'s token.
3002      *
3003      * When there's a {@link Configuration} update, this Resources instance will be updated to match
3004      * the new configuration.
3005      *
3006      * @see WindowTokenClient
3007      * @see #getWindowContextToken()
3008      */
createWindowContextResources(@onNull ContextImpl windowContextBase)3009     private static Resources createWindowContextResources(@NonNull ContextImpl windowContextBase) {
3010         final LoadedApk packageInfo = windowContextBase.mPackageInfo;
3011         final ClassLoader classLoader = windowContextBase.getClassLoader();
3012         final IBinder token = windowContextBase.getWindowContextToken();
3013 
3014         final String resDir = packageInfo.getResDir();
3015         final String[] splitResDirs = packageInfo.getSplitResDirs();
3016         final String[] legacyOverlayDirs = packageInfo.getOverlayDirs();
3017         final String[] overlayPaths = packageInfo.getOverlayPaths();
3018         final String[] libDirs = packageInfo.getApplicationInfo().sharedLibraryFiles;
3019         final int displayId = windowContextBase.getDisplayId();
3020         final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY)
3021                 ? packageInfo.getCompatibilityInfo()
3022                 : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
3023         final List<ResourcesLoader> loaders = windowContextBase.mResources.getLoaders();
3024 
3025         return windowContextBase.mResourcesManager.createBaseTokenResources(token, resDir,
3026                 splitResDirs, legacyOverlayDirs, overlayPaths, libDirs, displayId,
3027                 null /* overrideConfig */, compatInfo, classLoader, loaders);
3028     }
3029 
3030     @NonNull
3031     @Override
createContext(@onNull ContextParams contextParams)3032     public Context createContext(@NonNull ContextParams contextParams) {
3033         return new ContextImpl(this, mMainThread, mPackageInfo, contextParams,
3034                 contextParams.getAttributionTag(), contextParams.getNextAttributionSource(),
3035                 mSplitName, mToken, mUser, mFlags, mClassLoader, null, mDeviceId,
3036                 mIsExplicitDeviceId);
3037     }
3038 
3039     @Override
createAttributionContext(@ullable String attributionTag)3040     public @NonNull Context createAttributionContext(@Nullable String attributionTag) {
3041         return createContext(
3042                 new ContextParams.Builder(mParams).setAttributionTag(attributionTag).build());
3043     }
3044 
3045     @Override
createDeviceProtectedStorageContext()3046     public Context createDeviceProtectedStorageContext() {
3047         final int flags = (mFlags & ~Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE)
3048                 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
3049         return new ContextImpl(this, mMainThread, mPackageInfo, mParams,
3050                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
3051                 mToken, mUser, flags, mClassLoader, null, mDeviceId, mIsExplicitDeviceId);
3052     }
3053 
3054     @Override
createCredentialProtectedStorageContext()3055     public Context createCredentialProtectedStorageContext() {
3056         final int flags = (mFlags & ~Context.CONTEXT_DEVICE_PROTECTED_STORAGE)
3057                 | Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
3058         return new ContextImpl(this, mMainThread, mPackageInfo, mParams,
3059                 mAttributionSource.getAttributionTag(), mAttributionSource.getNext(), mSplitName,
3060                 mToken, mUser, flags, mClassLoader, null, mDeviceId, mIsExplicitDeviceId);
3061     }
3062 
3063     @Override
isRestricted()3064     public boolean isRestricted() {
3065         return (mFlags & Context.CONTEXT_RESTRICTED) != 0;
3066     }
3067 
3068     @Override
isDeviceProtectedStorage()3069     public boolean isDeviceProtectedStorage() {
3070         return (mFlags & Context.CONTEXT_DEVICE_PROTECTED_STORAGE) != 0;
3071     }
3072 
3073     @Override
isCredentialProtectedStorage()3074     public boolean isCredentialProtectedStorage() {
3075         return (mFlags & Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE) != 0;
3076     }
3077 
3078     @Override
canLoadUnsafeResources()3079     public boolean canLoadUnsafeResources() {
3080         if (getPackageName().equals(getOpPackageName())) {
3081             return true;
3082         }
3083         return (mFlags & Context.CONTEXT_IGNORE_SECURITY) != 0;
3084     }
3085 
3086     @Override
getDisplay()3087     public Display getDisplay() {
3088         if (!isAssociatedWithDisplay()) {
3089             throw new UnsupportedOperationException("Tried to obtain display from a Context not "
3090                     + "associated with one. Only visual Contexts (such as Activity or one created "
3091                     + "with Context#createWindowContext) or ones created with "
3092                     + "Context#createDisplayContext are associated with displays. Other types of "
3093                     + "Contexts are typically related to background entities and may return an "
3094                     + "arbitrary display.");
3095         }
3096         return getDisplayNoVerify();
3097     }
3098 
isAssociatedWithDisplay()3099     private boolean isAssociatedWithDisplay() {
3100         switch (mContextType) {
3101             case CONTEXT_TYPE_DISPLAY_CONTEXT:
3102             case CONTEXT_TYPE_ACTIVITY:
3103             case CONTEXT_TYPE_WINDOW_CONTEXT:
3104             // TODO(b/170369943): Remove after WindowContext migration
3105             case CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI:
3106                 return true;
3107             default:
3108                 return false;
3109         }
3110     }
3111 
3112     /**
3113      * @hide
3114      */
3115     @Override
getAssociatedDisplayId()3116     public int getAssociatedDisplayId()  {
3117         return isAssociatedWithDisplay() ? getDisplayId() : Display.INVALID_DISPLAY;
3118     }
3119 
3120     @Override
getDisplayNoVerify()3121     public Display getDisplayNoVerify() {
3122         if (mDisplay == null) {
3123             return mResourcesManager.getAdjustedDisplay(Display.DEFAULT_DISPLAY,
3124                     mResources);
3125         }
3126 
3127         return mDisplay;
3128     }
3129 
3130     @Override
getDisplayId()3131     public int getDisplayId() {
3132         final Display display = getDisplayNoVerify();
3133         return display != null ? display.getDisplayId() : Display.DEFAULT_DISPLAY;
3134     }
3135 
3136     @Override
updateDisplay(int displayId)3137     public void updateDisplay(int displayId) {
3138         setDisplay(mResourcesManager.getAdjustedDisplay(displayId, mResources));
3139         if (mContextType == CONTEXT_TYPE_NON_UI) {
3140             mContextType = CONTEXT_TYPE_DISPLAY_CONTEXT;
3141         }
3142     }
3143 
updateDeviceIdIfChanged(int displayId)3144     private void updateDeviceIdIfChanged(int displayId) {
3145         if (mIsExplicitDeviceId) {
3146             return;
3147         }
3148 
3149         if ((displayId == Display.DEFAULT_DISPLAY || displayId == Display.INVALID_DISPLAY)
3150                 && mDeviceId == DEVICE_ID_DEFAULT) {
3151             // DEFAULT_DISPLAY & INVALID_DISPLAY are associated with default device.
3152             // Return early avoiding instantiating VDM when it's not needed.
3153             return;
3154         }
3155 
3156         VirtualDeviceManager vdm = getSystemService(VirtualDeviceManager.class);
3157         if (vdm != null) {
3158             int deviceId = vdm.getDeviceIdForDisplayId(displayId);
3159             if (deviceId != mDeviceId) {
3160                 mDeviceId = deviceId;
3161                 mAttributionSource =
3162                         createAttributionSourceWithDeviceId(mAttributionSource, mDeviceId);
3163                 notifyOnDeviceChangedListeners(mDeviceId);
3164             }
3165         }
3166     }
3167 
3168     @Override
updateDeviceId(int updatedDeviceId)3169     public void updateDeviceId(int updatedDeviceId) {
3170         if (updatedDeviceId != Context.DEVICE_ID_DEFAULT) {
3171             VirtualDeviceManager vdm = getSystemService(VirtualDeviceManager.class);
3172             if (!vdm.isValidVirtualDeviceId(updatedDeviceId)) {
3173                 throw new IllegalArgumentException(
3174                         "Not a valid ID of the default device or any virtual device: "
3175                                 + updatedDeviceId);
3176             }
3177         }
3178         if (mIsExplicitDeviceId) {
3179             throw new UnsupportedOperationException(
3180                     "Cannot update device ID on a Context created with createDeviceContext()");
3181         }
3182 
3183         if (mDeviceId != updatedDeviceId) {
3184             mDeviceId = updatedDeviceId;
3185             mAttributionSource = createAttributionSourceWithDeviceId(mAttributionSource, mDeviceId);
3186             notifyOnDeviceChangedListeners(updatedDeviceId);
3187         }
3188     }
3189 
3190     @Override
getDeviceId()3191     public int getDeviceId() {
3192         return mDeviceId;
3193     }
3194 
3195     @Override
registerDeviceIdChangeListener(@onNull @allbackExecutor Executor executor, @NonNull IntConsumer listener)3196     public void registerDeviceIdChangeListener(@NonNull @CallbackExecutor Executor executor,
3197             @NonNull IntConsumer listener) {
3198         Objects.requireNonNull(executor, "executor cannot be null");
3199         Objects.requireNonNull(listener, "listener cannot be null");
3200 
3201         synchronized (mDeviceIdListenerLock) {
3202             if (getDeviceIdListener(listener) != null) {
3203                 throw new IllegalArgumentException(
3204                         "attempt to call registerDeviceIdChangeListener() "
3205                                 + "on a previously registered listener");
3206             }
3207             // lazy initialization
3208             if (mDeviceIdChangeListeners == null) {
3209                 mDeviceIdChangeListeners = new ArrayList<>();
3210             }
3211             mDeviceIdChangeListeners.add(new DeviceIdChangeListenerDelegate(listener, executor));
3212         }
3213     }
3214 
3215     @Override
unregisterDeviceIdChangeListener(@onNull IntConsumer listener)3216     public void unregisterDeviceIdChangeListener(@NonNull IntConsumer listener) {
3217         Objects.requireNonNull(listener, "listener cannot be null");
3218         synchronized (mDeviceIdListenerLock) {
3219             DeviceIdChangeListenerDelegate listenerToRemove = getDeviceIdListener(listener);
3220             if (listenerToRemove != null) {
3221                 mDeviceIdChangeListeners.remove(listenerToRemove);
3222             }
3223         }
3224     }
3225 
3226     @GuardedBy("mDeviceIdListenerLock")
3227     @Nullable
getDeviceIdListener( @ullable IntConsumer listener)3228     private DeviceIdChangeListenerDelegate getDeviceIdListener(
3229             @Nullable IntConsumer listener) {
3230         if (mDeviceIdChangeListeners == null) {
3231             return null;
3232         }
3233         for (int i = 0; i < mDeviceIdChangeListeners.size(); i++) {
3234             DeviceIdChangeListenerDelegate delegate = mDeviceIdChangeListeners.get(i);
3235             if (delegate.mListener == listener) {
3236                 return delegate;
3237             }
3238         }
3239         return null;
3240     }
3241 
notifyOnDeviceChangedListeners(int deviceId)3242     private void notifyOnDeviceChangedListeners(int deviceId) {
3243         synchronized (mDeviceIdListenerLock) {
3244             if (mDeviceIdChangeListeners != null) {
3245                 for (DeviceIdChangeListenerDelegate delegate : mDeviceIdChangeListeners) {
3246                     delegate.mExecutor.execute(() ->
3247                             delegate.mListener.accept(deviceId));
3248                 }
3249             }
3250         }
3251     }
3252 
3253     @Override
getDisplayAdjustments(int displayId)3254     public DisplayAdjustments getDisplayAdjustments(int displayId) {
3255         return mResources.getDisplayAdjustments();
3256     }
3257 
3258     @Override
getDataDir()3259     public File getDataDir() {
3260         if (mPackageInfo != null) {
3261             File res = null;
3262             if (isCredentialProtectedStorage()) {
3263                 res = mPackageInfo.getCredentialProtectedDataDirFile();
3264             } else if (isDeviceProtectedStorage()) {
3265                 res = mPackageInfo.getDeviceProtectedDataDirFile();
3266             } else {
3267                 res = mPackageInfo.getDataDirFile();
3268             }
3269 
3270             if (res != null) {
3271                 if (!res.exists() && android.os.Process.myUid() == android.os.Process.SYSTEM_UID) {
3272                     Log.wtf(TAG, "Data directory doesn't exist for package " + getPackageName(),
3273                             new Throwable());
3274                 }
3275                 return res;
3276             } else {
3277                 throw new RuntimeException(
3278                         "No data directory found for package " + getPackageName());
3279             }
3280         } else {
3281             throw new RuntimeException(
3282                     "No package details found for package " + getPackageName());
3283         }
3284     }
3285 
3286     @Override
getDir(String name, int mode)3287     public File getDir(String name, int mode) {
3288         checkMode(mode);
3289         name = "app_" + name;
3290         File file = makeFilename(getDataDir(), name);
3291         if (!file.exists()) {
3292             file.mkdir();
3293             setFilePermissionsFromMode(file.getPath(), mode,
3294                     FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
3295         }
3296         return file;
3297     }
3298 
3299     /** {@hide} */
3300     @Override
getUser()3301     public UserHandle getUser() {
3302         return mUser;
3303     }
3304 
3305     /** {@hide} */
3306     @Override
getUserId()3307     public int getUserId() {
3308         return mUser.getIdentifier();
3309     }
3310 
3311     /** @hide */
3312     @Override
getAutofillClient()3313     public AutofillClient getAutofillClient() {
3314         return mAutofillClient;
3315     }
3316 
3317     /** @hide */
3318     @Override
setAutofillClient(AutofillClient client)3319     public void setAutofillClient(AutofillClient client) {
3320         mAutofillClient = client;
3321     }
3322 
3323     /** @hide */
3324     @Override
getAutofillOptions()3325     public AutofillOptions getAutofillOptions() {
3326         return mAutofillOptions;
3327     }
3328 
3329     /** @hide */
3330     @Override
setAutofillOptions(AutofillOptions options)3331     public void setAutofillOptions(AutofillOptions options) {
3332         mAutofillOptions = options;
3333     }
3334 
3335     /** @hide */
3336     @Override
getContentCaptureOptions()3337     public ContentCaptureOptions getContentCaptureOptions() {
3338         return mContentCaptureOptions;
3339     }
3340 
3341     /** @hide */
3342     @Override
setContentCaptureOptions(ContentCaptureOptions options)3343     public void setContentCaptureOptions(ContentCaptureOptions options) {
3344         mContentCaptureOptions = options;
3345     }
3346 
3347     @Override
finalize()3348     protected void finalize() throws Throwable {
3349         // If mToken is a WindowTokenClient, the Context is usually associated with a
3350         // WindowContainer. We should detach from WindowContainer when the Context is finalized
3351         // if this Context is not a WindowContext. WindowContext finalization is handled in
3352         // WindowContext class.
3353         if (mToken instanceof WindowTokenClient && mOwnsToken) {
3354             WindowTokenClientController.getInstance().detachIfNeeded(
3355                     (WindowTokenClient) mToken);
3356         }
3357         super.finalize();
3358     }
3359 
3360     @UnsupportedAppUsage
createSystemContext(ActivityThread mainThread)3361     static ContextImpl createSystemContext(ActivityThread mainThread) {
3362         LoadedApk packageInfo = new LoadedApk(mainThread);
3363         ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
3364                 ContextParams.EMPTY, null, null, null, null, null, 0, null, null,
3365                 DEVICE_ID_DEFAULT, false);
3366         context.setResources(packageInfo.getResources());
3367         context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
3368                 context.mResourcesManager.getDisplayMetrics());
3369         context.mContextType = CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI;
3370         return context;
3371     }
3372 
3373     /**
3374      * System Context to be used for UI. This Context has resources that can be themed.
3375      * Make sure that the created system UI context shares the same LoadedApk as the system context.
3376      * @param systemContext The system context which created by
3377      *                      {@link #createSystemContext(ActivityThread)}.
3378      * @param displayId The ID of the display where the UI is shown.
3379      */
createSystemUiContext(ContextImpl systemContext, int displayId)3380     static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) {
3381         final WindowTokenClient token = new WindowTokenClient();
3382         final ContextImpl context = systemContext.createWindowContextBase(token, displayId);
3383         token.attachContext(context);
3384         WindowTokenClientController.getInstance().attachToDisplayContent(token, displayId);
3385         context.mContextType = CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI;
3386         context.mOwnsToken = true;
3387 
3388         return context;
3389     }
3390 
3391     @UnsupportedAppUsage
createAppContext(ActivityThread mainThread, LoadedApk packageInfo)3392     static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
3393         return createAppContext(mainThread, packageInfo, null);
3394     }
3395 
createAppContext(ActivityThread mainThread, LoadedApk packageInfo, String opPackageName)3396     static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo,
3397             String opPackageName) {
3398         if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
3399         ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
3400                 ContextParams.EMPTY, null, null, null, null, null, 0, null, opPackageName,
3401                 DEVICE_ID_DEFAULT, false);
3402         context.setResources(packageInfo.getResources());
3403         context.mContextType = isSystemOrSystemUI(context) ? CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI
3404                 : CONTEXT_TYPE_NON_UI;
3405         return context;
3406     }
3407 
3408     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
createActivityContext(ActivityThread mainThread, LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId, Configuration overrideConfiguration)3409     static ContextImpl createActivityContext(ActivityThread mainThread,
3410             LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
3411             Configuration overrideConfiguration) {
3412         if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
3413 
3414         String[] splitDirs = packageInfo.getSplitResDirs();
3415         ClassLoader classLoader = packageInfo.getClassLoader();
3416 
3417         if (packageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) {
3418             Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "SplitDependencies");
3419             try {
3420                 classLoader = packageInfo.getSplitClassLoader(activityInfo.splitName);
3421                 splitDirs = packageInfo.getSplitPaths(activityInfo.splitName);
3422             } catch (NameNotFoundException e) {
3423                 // Nothing above us can handle a NameNotFoundException, better crash.
3424                 throw new RuntimeException(e);
3425             } finally {
3426                 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
3427             }
3428         }
3429 
3430         final String attributionTag;
3431         if (activityInfo.attributionTags != null && activityInfo.attributionTags.length > 0) {
3432             attributionTag = activityInfo.attributionTags[0];
3433         } else {
3434             attributionTag = null;
3435         }
3436 
3437         ContextImpl context = new ContextImpl(null, mainThread, packageInfo, ContextParams.EMPTY,
3438                 attributionTag, null, activityInfo.splitName, activityToken, null, 0, classLoader,
3439                 null, DEVICE_ID_DEFAULT, false);
3440         context.mContextType = CONTEXT_TYPE_ACTIVITY;
3441         context.mIsConfigurationBasedContext = true;
3442 
3443         // Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY.
3444         displayId = (displayId != Display.INVALID_DISPLAY) ? displayId : Display.DEFAULT_DISPLAY;
3445 
3446         final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY)
3447                 ? packageInfo.getCompatibilityInfo()
3448                 : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
3449 
3450         final ResourcesManager resourcesManager = ResourcesManager.getInstance();
3451 
3452         // Create the base resources for which all configuration contexts for this Activity
3453         // will be rebased upon.
3454         context.setResources(resourcesManager.createBaseTokenResources(activityToken,
3455                 packageInfo.getResDir(),
3456                 splitDirs,
3457                 packageInfo.getOverlayDirs(),
3458                 packageInfo.getOverlayPaths(),
3459                 packageInfo.getApplicationInfo().sharedLibraryFiles,
3460                 displayId,
3461                 overrideConfiguration,
3462                 compatInfo,
3463                 classLoader,
3464                 packageInfo.getApplication() == null ? null
3465                         : packageInfo.getApplication().getResources().getLoaders()));
3466         context.setDisplay(resourcesManager.getAdjustedDisplay(
3467                 displayId, context.getResources()));
3468         return context;
3469     }
3470 
ContextImpl(@ullable ContextImpl container, @NonNull ActivityThread mainThread, @NonNull LoadedApk packageInfo, @NonNull ContextParams params, @Nullable String attributionTag, @Nullable AttributionSource nextAttributionSource, @Nullable String splitName, @Nullable IBinder token, @Nullable UserHandle user, int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName, int deviceId, boolean isExplicitDeviceId)3471     private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread,
3472             @NonNull LoadedApk packageInfo, @NonNull ContextParams params,
3473             @Nullable String attributionTag, @Nullable AttributionSource nextAttributionSource,
3474             @Nullable String splitName, @Nullable IBinder token, @Nullable UserHandle user,
3475             int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName,
3476             int deviceId, boolean isExplicitDeviceId) {
3477         mOuterContext = this;
3478         // If creator didn't specify which storage to use, use the default
3479         // location for application.
3480         if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE
3481                 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) {
3482             final File dataDir = packageInfo.getDataDirFile();
3483             if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) {
3484                 flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE;
3485             } else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) {
3486                 flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE;
3487             }
3488         }
3489 
3490         mMainThread = mainThread;
3491         mToken = token;
3492         mFlags = flags;
3493 
3494         if (user == null) {
3495             user = Process.myUserHandle();
3496         }
3497         mUser = user;
3498 
3499         mPackageInfo = packageInfo;
3500         mSplitName = splitName;
3501         mClassLoader = classLoader;
3502         mResourcesManager = ResourcesManager.getInstance();
3503 
3504         String opPackageName;
3505 
3506         mDeviceId = deviceId;
3507         mIsExplicitDeviceId = isExplicitDeviceId;
3508 
3509         if (container != null) {
3510             mBasePackageName = container.mBasePackageName;
3511             opPackageName = container.mOpPackageName;
3512             setResources(container.mResources);
3513             mDisplay = container.mDisplay;
3514             if (!isExplicitDeviceId) {
3515                 mIsExplicitDeviceId = container.mIsExplicitDeviceId;
3516                 mDeviceId = container.mDeviceId;
3517             }
3518             mForceDisplayOverrideInResources = container.mForceDisplayOverrideInResources;
3519             mIsConfigurationBasedContext = container.mIsConfigurationBasedContext;
3520             mContextType = container.mContextType;
3521             mContentCaptureOptions = container.mContentCaptureOptions;
3522             mAutofillOptions = container.mAutofillOptions;
3523         } else {
3524             mBasePackageName = packageInfo.mPackageName;
3525             ApplicationInfo ainfo = packageInfo.getApplicationInfo();
3526             if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
3527                 // Special case: system components allow themselves to be loaded in to other
3528                 // processes.  For purposes of app ops, we must then consider the context as
3529                 // belonging to the package of this process, not the system itself, otherwise
3530                 // the package+uid verifications in app ops will fail.
3531                 opPackageName = ActivityThread.currentPackageName();
3532             } else {
3533                 opPackageName = mBasePackageName;
3534             }
3535         }
3536 
3537         mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName;
3538         mParams = Objects.requireNonNull(params);
3539         mAttributionSource = createAttributionSource(attributionTag, nextAttributionSource,
3540                 params.getRenouncedPermissions(), params.shouldRegisterAttributionSource(), mDeviceId);
3541         mContentResolver = new ApplicationContentResolver(this, mainThread);
3542     }
3543 
createAttributionSource(@ullable String attributionTag, @Nullable AttributionSource nextAttributionSource, @Nullable Set<String> renouncedPermissions, boolean shouldRegister, int deviceId)3544     private @NonNull AttributionSource createAttributionSource(@Nullable String attributionTag,
3545             @Nullable AttributionSource nextAttributionSource,
3546             @Nullable Set<String> renouncedPermissions, boolean shouldRegister,
3547             int deviceId) {
3548         AttributionSource attributionSource = new AttributionSource(Process.myUid(),
3549                 Process.myPid(), mOpPackageName, attributionTag,
3550                 (renouncedPermissions != null) ? renouncedPermissions.toArray(new String[0]) : null,
3551                 deviceId, nextAttributionSource);
3552         // If we want to access protected data on behalf of another app we need to
3553         // tell the OS that we opt in to participate in the attribution chain.
3554         return registerAttributionSourceIfNeeded(attributionSource, shouldRegister);
3555     }
3556 
createAttributionSourceWithDeviceId( @onNull AttributionSource oldSource, int deviceId)3557     private @NonNull AttributionSource createAttributionSourceWithDeviceId(
3558             @NonNull AttributionSource oldSource, int deviceId) {
3559         boolean shouldRegister = false;
3560         if (shouldRegisterAttributionSource()) {
3561             shouldRegister = mParams.shouldRegisterAttributionSource();
3562         }
3563         return registerAttributionSourceIfNeeded(oldSource.withDeviceId(deviceId), shouldRegister);
3564     }
3565 
registerAttributionSourceIfNeeded( @onNull AttributionSource attributionSource, boolean shouldRegister)3566     private @NonNull AttributionSource registerAttributionSourceIfNeeded(
3567             @NonNull AttributionSource attributionSource, boolean shouldRegister) {
3568         if (shouldRegister || attributionSource.getNext() != null) {
3569             return getSystemService(PermissionManager.class)
3570                     .registerAttributionSource(attributionSource);
3571         }
3572         return attributionSource;
3573     }
3574 
setResources(Resources r)3575     void setResources(Resources r) {
3576         if (r instanceof CompatResources) {
3577             ((CompatResources) r).setContext(this);
3578         }
3579         mResources = r;
3580 
3581         if (r != null) {
3582             // only do this if the user already has more than one preferred locale
3583             if (android.content.res.Flags.defaultLocale()
3584                     && r.getConfiguration().getLocales().size() > 1) {
3585                 LocaleConfig lc = LocaleConfig.fromContextIgnoringOverride(this);
3586                 mResourcesManager.setLocaleConfig(lc);
3587             }
3588         }
3589     }
3590 
installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader)3591     void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
3592         mPackageInfo.installSystemApplicationInfo(info, classLoader);
3593     }
3594 
3595     @UnsupportedAppUsage
scheduleFinalCleanup(String who, String what)3596     final void scheduleFinalCleanup(String who, String what) {
3597         mMainThread.scheduleContextCleanup(this, who, what);
3598     }
3599 
performFinalCleanup(String who, String what)3600     final void performFinalCleanup(String who, String what) {
3601         //Log.i(TAG, "Cleanup up context: " + this);
3602         mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
3603         if (mContextType == CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI
3604                 && mToken instanceof WindowTokenClient) {
3605             mMainThread.onSystemUiContextCleanup(this);
3606         }
3607     }
3608 
3609     @UnsupportedAppUsage
getReceiverRestrictedContext()3610     final Context getReceiverRestrictedContext() {
3611         if (mReceiverRestrictedContext != null) {
3612             return mReceiverRestrictedContext;
3613         }
3614         return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
3615     }
3616 
3617     @UnsupportedAppUsage
setOuterContext(@onNull Context context)3618     final void setOuterContext(@NonNull Context context) {
3619         mOuterContext = context;
3620     }
3621 
3622     @UnsupportedAppUsage
getOuterContext()3623     final Context getOuterContext() {
3624         return mOuterContext;
3625     }
3626 
3627     @Override
3628     @UnsupportedAppUsage
getActivityToken()3629     public IBinder getActivityToken() {
3630         return mContextType == CONTEXT_TYPE_ACTIVITY ? mToken : null;
3631     }
3632 
3633     @Override
getWindowContextToken()3634     public IBinder getWindowContextToken() {
3635         switch (mContextType) {
3636             case CONTEXT_TYPE_WINDOW_CONTEXT:
3637             case CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI:
3638                 return mToken;
3639             default:
3640                 return null;
3641         }
3642     }
3643 
checkMode(int mode)3644     private void checkMode(int mode) {
3645         if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
3646             if ((mode & MODE_WORLD_READABLE) != 0) {
3647                 throw new SecurityException("MODE_WORLD_READABLE no longer supported");
3648             }
3649             if ((mode & MODE_WORLD_WRITEABLE) != 0) {
3650                 throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported");
3651             }
3652         }
3653     }
3654 
3655     @SuppressWarnings("deprecation")
setFilePermissionsFromMode(String name, int mode, int extraPermissions)3656     static void setFilePermissionsFromMode(String name, int mode,
3657             int extraPermissions) {
3658         int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
3659             |FileUtils.S_IRGRP|FileUtils.S_IWGRP
3660             |extraPermissions;
3661         if ((mode&MODE_WORLD_READABLE) != 0) {
3662             perms |= FileUtils.S_IROTH;
3663         }
3664         if ((mode&MODE_WORLD_WRITEABLE) != 0) {
3665             perms |= FileUtils.S_IWOTH;
3666         }
3667         if (DEBUG) {
3668             Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
3669                   + ", perms=0x" + Integer.toHexString(perms));
3670         }
3671         FileUtils.setPermissions(name, perms, -1, -1);
3672     }
3673 
makeFilename(File base, String name)3674     private File makeFilename(File base, String name) {
3675         if (name.indexOf(File.separatorChar) < 0) {
3676             final File res = new File(base, name);
3677             // We report as filesystem access here to give us the best shot at
3678             // detecting apps that will pass the path down to native code.
3679             BlockGuard.getVmPolicy().onPathAccess(res.getPath());
3680             return res;
3681         }
3682         throw new IllegalArgumentException(
3683                 "File " + name + " contains a path separator");
3684     }
3685 
3686     /**
3687      * Ensure that given directories exist, trying to create them if missing. If
3688      * unable to create, they are filtered by replacing with {@code null}.
3689      */
ensureExternalDirsExistOrFilter(File[] dirs, boolean tryCreateInProcess)3690     private File[] ensureExternalDirsExistOrFilter(File[] dirs, boolean tryCreateInProcess) {
3691         final StorageManager sm = getSystemService(StorageManager.class);
3692         final File[] result = new File[dirs.length];
3693         for (int i = 0; i < dirs.length; i++) {
3694             File dir = dirs[i];
3695             if (!dir.exists()) {
3696                 try {
3697                     if (!tryCreateInProcess || !dir.mkdirs()) {
3698                         // recheck existence in case of cross-process race
3699                         if (!dir.exists()) {
3700                             // Failing to mkdir() may be okay, since we might not have
3701                             // enough permissions; ask vold to create on our behalf.
3702                             sm.mkdirs(dir);
3703                         }
3704                     }
3705                 } catch (Exception e) {
3706                     Log.w(TAG, "Failed to ensure " + dir + ": " + e);
3707                     dir = null;
3708                 }
3709             }
3710             if (dir != null && !dir.canWrite()) {
3711                 // Older versions of the MediaProvider mainline module had a rare early boot race
3712                 // condition where app-private dirs could be created with the wrong permissions;
3713                 // fix this up here. This check should be very fast, because dir.exists() above
3714                 // will already have loaded the dentry in the cache.
3715                 sm.fixupAppDir(dir);
3716             }
3717             result[i] = dir;
3718         }
3719         return result;
3720     }
3721 
3722     @Override
destroy()3723     public void destroy() {
3724         // The final clean-up is to release BroadcastReceiver registrations. It is called in
3725         // ActivityThread for Activity and Service. For the context, such as WindowContext,
3726         // without lifecycle concept, it should be called once the context is released.
3727         scheduleFinalCleanup(getClass().getName(), getOuterContext().getClass().getSimpleName());
3728     }
3729 
3730     @Override
closeSystemDialogs()3731     public void closeSystemDialogs() {
3732         final Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
3733                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
3734         final Bundle options = BroadcastOptions.makeBasic()
3735                 .setDeliveryGroupPolicy(BroadcastOptions.DELIVERY_GROUP_POLICY_MOST_RECENT)
3736                 .setDeferralPolicy(BroadcastOptions.DEFERRAL_POLICY_UNTIL_ACTIVE)
3737                 .toBundle();
3738         sendBroadcast(intent, null /* receiverPermission */, options);
3739     }
3740 
3741     // ----------------------------------------------------------------------
3742     // ----------------------------------------------------------------------
3743     // ----------------------------------------------------------------------
3744 
3745     private static final class ApplicationContentResolver extends ContentResolver {
3746         @UnsupportedAppUsage
3747         private final ActivityThread mMainThread;
3748 
ApplicationContentResolver(Context context, ActivityThread mainThread)3749         public ApplicationContentResolver(Context context, ActivityThread mainThread) {
3750             super(context);
3751             mMainThread = Objects.requireNonNull(mainThread);
3752         }
3753 
3754         @Override
3755         @UnsupportedAppUsage
acquireProvider(Context context, String auth)3756         protected IContentProvider acquireProvider(Context context, String auth) {
3757             return mMainThread.acquireProvider(context,
3758                     ContentProvider.getAuthorityWithoutUserId(auth),
3759                     resolveUserIdFromAuthority(auth), true);
3760         }
3761 
3762         @Override
acquireExistingProvider(Context context, String auth)3763         protected IContentProvider acquireExistingProvider(Context context, String auth) {
3764             return mMainThread.acquireExistingProvider(context,
3765                     ContentProvider.getAuthorityWithoutUserId(auth),
3766                     resolveUserIdFromAuthority(auth), true);
3767         }
3768 
3769         @Override
releaseProvider(IContentProvider provider)3770         public boolean releaseProvider(IContentProvider provider) {
3771             return mMainThread.releaseProvider(provider, true);
3772         }
3773 
3774         @Override
acquireUnstableProvider(Context c, String auth)3775         protected IContentProvider acquireUnstableProvider(Context c, String auth) {
3776             return mMainThread.acquireProvider(c,
3777                     ContentProvider.getAuthorityWithoutUserId(auth),
3778                     resolveUserIdFromAuthority(auth), false);
3779         }
3780 
3781         @Override
releaseUnstableProvider(IContentProvider icp)3782         public boolean releaseUnstableProvider(IContentProvider icp) {
3783             return mMainThread.releaseProvider(icp, false);
3784         }
3785 
3786         @Override
unstableProviderDied(IContentProvider icp)3787         public void unstableProviderDied(IContentProvider icp) {
3788             mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
3789         }
3790 
3791         @Override
appNotRespondingViaProvider(IContentProvider icp)3792         public void appNotRespondingViaProvider(IContentProvider icp) {
3793             mMainThread.appNotRespondingViaProvider(icp.asBinder());
3794         }
3795 
3796         /** @hide */
resolveUserIdFromAuthority(String auth)3797         protected int resolveUserIdFromAuthority(String auth) {
3798             return ContentProvider.getUserIdFromAuthority(auth, getUserId());
3799         }
3800     }
3801 }
3802