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 android.annotation.IntDef; 20 import android.annotation.NonNull; 21 import android.annotation.Nullable; 22 import android.annotation.TestApi; 23 import android.compat.annotation.UnsupportedAppUsage; 24 import android.content.AutofillOptions; 25 import android.content.BroadcastReceiver; 26 import android.content.ComponentName; 27 import android.content.ContentCaptureOptions; 28 import android.content.ContentProvider; 29 import android.content.ContentResolver; 30 import android.content.Context; 31 import android.content.ContextWrapper; 32 import android.content.IContentProvider; 33 import android.content.IIntentReceiver; 34 import android.content.Intent; 35 import android.content.IntentFilter; 36 import android.content.IntentSender; 37 import android.content.ReceiverCallNotAllowedException; 38 import android.content.ServiceConnection; 39 import android.content.SharedPreferences; 40 import android.content.pm.ActivityInfo; 41 import android.content.pm.ApplicationInfo; 42 import android.content.pm.IPackageManager; 43 import android.content.pm.PackageManager; 44 import android.content.pm.PackageManager.NameNotFoundException; 45 import android.content.res.AssetManager; 46 import android.content.res.CompatResources; 47 import android.content.res.CompatibilityInfo; 48 import android.content.res.Configuration; 49 import android.content.res.Resources; 50 import android.database.DatabaseErrorHandler; 51 import android.database.sqlite.SQLiteDatabase; 52 import android.database.sqlite.SQLiteDatabase.CursorFactory; 53 import android.graphics.Bitmap; 54 import android.graphics.drawable.Drawable; 55 import android.net.Uri; 56 import android.os.Binder; 57 import android.os.Build; 58 import android.os.Bundle; 59 import android.os.Debug; 60 import android.os.Environment; 61 import android.os.FileUtils; 62 import android.os.Handler; 63 import android.os.IBinder; 64 import android.os.Looper; 65 import android.os.Process; 66 import android.os.RemoteException; 67 import android.os.Trace; 68 import android.os.UserHandle; 69 import android.os.UserManager; 70 import android.os.storage.StorageManager; 71 import android.system.ErrnoException; 72 import android.system.Os; 73 import android.system.OsConstants; 74 import android.system.StructStat; 75 import android.text.TextUtils; 76 import android.util.AndroidRuntimeException; 77 import android.util.ArrayMap; 78 import android.util.Log; 79 import android.util.Slog; 80 import android.view.Display; 81 import android.view.DisplayAdjustments; 82 import android.view.autofill.AutofillManager.AutofillClient; 83 84 import com.android.internal.annotations.GuardedBy; 85 import com.android.internal.util.Preconditions; 86 87 import dalvik.system.BlockGuard; 88 89 import libcore.io.Memory; 90 91 import java.io.File; 92 import java.io.FileInputStream; 93 import java.io.FileNotFoundException; 94 import java.io.FileOutputStream; 95 import java.io.FilenameFilter; 96 import java.io.IOException; 97 import java.io.InputStream; 98 import java.lang.annotation.Retention; 99 import java.lang.annotation.RetentionPolicy; 100 import java.nio.ByteOrder; 101 import java.util.ArrayList; 102 import java.util.Objects; 103 import java.util.concurrent.Executor; 104 105 class ReceiverRestrictedContext extends ContextWrapper { 106 @UnsupportedAppUsage ReceiverRestrictedContext(Context base)107 ReceiverRestrictedContext(Context base) { 108 super(base); 109 } 110 111 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter)112 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 113 return registerReceiver(receiver, filter, null, null); 114 } 115 116 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)117 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 118 String broadcastPermission, Handler scheduler) { 119 if (receiver == null) { 120 // Allow retrieving current sticky broadcast; this is safe since we 121 // aren't actually registering a receiver. 122 return super.registerReceiver(null, filter, broadcastPermission, scheduler); 123 } else { 124 throw new ReceiverCallNotAllowedException( 125 "BroadcastReceiver components are not allowed to register to receive intents"); 126 } 127 } 128 129 @Override registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)130 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, 131 String broadcastPermission, Handler scheduler) { 132 return registerReceiverAsUser( 133 receiver, UserHandle.ALL, filter, broadcastPermission, scheduler); 134 } 135 136 @Override registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)137 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, 138 IntentFilter filter, String broadcastPermission, Handler scheduler) { 139 if (receiver == null) { 140 // Allow retrieving current sticky broadcast; this is safe since we 141 // aren't actually registering a receiver. 142 return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler); 143 } else { 144 throw new ReceiverCallNotAllowedException( 145 "BroadcastReceiver components are not allowed to register to receive intents"); 146 } 147 } 148 149 @Override bindService(Intent service, ServiceConnection conn, int flags)150 public boolean bindService(Intent service, ServiceConnection conn, int flags) { 151 throw new ReceiverCallNotAllowedException( 152 "BroadcastReceiver components are not allowed to bind to services"); 153 } 154 155 @Override bindService( Intent service, int flags, Executor executor, ServiceConnection conn)156 public boolean bindService( 157 Intent service, int flags, Executor executor, ServiceConnection conn) { 158 throw new ReceiverCallNotAllowedException( 159 "BroadcastReceiver components are not allowed to bind to services"); 160 } 161 162 @Override bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)163 public boolean bindIsolatedService(Intent service, int flags, String instanceName, 164 Executor executor, ServiceConnection conn) { 165 throw new ReceiverCallNotAllowedException( 166 "BroadcastReceiver components are not allowed to bind to services"); 167 } 168 } 169 170 /** 171 * Common implementation of Context API, which provides the base 172 * context object for Activity and other application components. 173 */ 174 class ContextImpl extends Context { 175 private final static String TAG = "ContextImpl"; 176 private final static boolean DEBUG = false; 177 178 private static final String XATTR_INODE_CACHE = "user.inode_cache"; 179 private static final String XATTR_INODE_CODE_CACHE = "user.inode_code_cache"; 180 181 /** 182 * Map from package name, to preference name, to cached preferences. 183 */ 184 @GuardedBy("ContextImpl.class") 185 @UnsupportedAppUsage 186 private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache; 187 188 /** 189 * Map from preference name to generated path. 190 */ 191 @GuardedBy("ContextImpl.class") 192 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 193 private ArrayMap<String, File> mSharedPrefsPaths; 194 195 @UnsupportedAppUsage 196 final @NonNull ActivityThread mMainThread; 197 @UnsupportedAppUsage 198 final @NonNull LoadedApk mPackageInfo; 199 @UnsupportedAppUsage 200 private @Nullable ClassLoader mClassLoader; 201 202 private final @Nullable IBinder mActivityToken; 203 204 private final @NonNull UserHandle mUser; 205 206 @UnsupportedAppUsage 207 private final ApplicationContentResolver mContentResolver; 208 209 @UnsupportedAppUsage 210 private final String mBasePackageName; 211 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 212 private final String mOpPackageName; 213 214 private final @NonNull ResourcesManager mResourcesManager; 215 @UnsupportedAppUsage 216 private @NonNull Resources mResources; 217 private @Nullable Display mDisplay; // may be null if default display 218 219 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 220 private final int mFlags; 221 222 @UnsupportedAppUsage 223 private Context mOuterContext; 224 @UnsupportedAppUsage 225 private int mThemeResource = 0; 226 @UnsupportedAppUsage 227 private Resources.Theme mTheme = null; 228 @UnsupportedAppUsage 229 private PackageManager mPackageManager; 230 private Context mReceiverRestrictedContext = null; 231 232 // The name of the split this Context is representing. May be null. 233 private @Nullable String mSplitName = null; 234 235 private @Nullable AutofillClient mAutofillClient = null; 236 private @Nullable AutofillOptions mAutofillOptions; 237 238 private ContentCaptureOptions mContentCaptureOptions = null; 239 240 private final Object mSync = new Object(); 241 242 @GuardedBy("mSync") 243 private File mDatabasesDir; 244 @GuardedBy("mSync") 245 @UnsupportedAppUsage 246 private File mPreferencesDir; 247 @GuardedBy("mSync") 248 private File mFilesDir; 249 @GuardedBy("mSync") 250 private File mNoBackupFilesDir; 251 @GuardedBy("mSync") 252 private File mCacheDir; 253 @GuardedBy("mSync") 254 private File mCodeCacheDir; 255 256 // The system service cache for the system services that are cached per-ContextImpl. 257 @UnsupportedAppUsage 258 final Object[] mServiceCache = SystemServiceRegistry.createServiceCache(); 259 260 static final int STATE_UNINITIALIZED = 0; 261 static final int STATE_INITIALIZING = 1; 262 static final int STATE_READY = 2; 263 static final int STATE_NOT_FOUND = 3; 264 265 /** @hide */ 266 @IntDef(prefix = { "STATE_" }, value = { 267 STATE_UNINITIALIZED, 268 STATE_INITIALIZING, 269 STATE_READY, 270 STATE_NOT_FOUND, 271 }) 272 @Retention(RetentionPolicy.SOURCE) 273 @interface ServiceInitializationState {} 274 275 /** 276 * Initialization state for each service. Any of {@link #STATE_UNINITIALIZED}, 277 * {@link #STATE_INITIALIZING} or {@link #STATE_READY}, 278 */ 279 @ServiceInitializationState 280 final int[] mServiceInitializationStateArray = new int[mServiceCache.length]; 281 282 @UnsupportedAppUsage getImpl(Context context)283 static ContextImpl getImpl(Context context) { 284 Context nextContext; 285 while ((context instanceof ContextWrapper) && 286 (nextContext=((ContextWrapper)context).getBaseContext()) != null) { 287 context = nextContext; 288 } 289 return (ContextImpl)context; 290 } 291 292 @Override getAssets()293 public AssetManager getAssets() { 294 return getResources().getAssets(); 295 } 296 297 @Override getResources()298 public Resources getResources() { 299 return mResources; 300 } 301 302 @Override getPackageManager()303 public PackageManager getPackageManager() { 304 if (mPackageManager != null) { 305 return mPackageManager; 306 } 307 308 IPackageManager pm = ActivityThread.getPackageManager(); 309 if (pm != null) { 310 // Doesn't matter if we make more than one instance. 311 return (mPackageManager = new ApplicationPackageManager(this, pm)); 312 } 313 314 return null; 315 } 316 317 @Override getContentResolver()318 public ContentResolver getContentResolver() { 319 return mContentResolver; 320 } 321 322 @Override getMainLooper()323 public Looper getMainLooper() { 324 return mMainThread.getLooper(); 325 } 326 327 @Override getMainExecutor()328 public Executor getMainExecutor() { 329 return mMainThread.getExecutor(); 330 } 331 332 @Override getApplicationContext()333 public Context getApplicationContext() { 334 return (mPackageInfo != null) ? 335 mPackageInfo.getApplication() : mMainThread.getApplication(); 336 } 337 338 @Override setTheme(int resId)339 public void setTheme(int resId) { 340 synchronized (mSync) { 341 if (mThemeResource != resId) { 342 mThemeResource = resId; 343 initializeTheme(); 344 } 345 } 346 } 347 348 @Override getThemeResId()349 public int getThemeResId() { 350 synchronized (mSync) { 351 return mThemeResource; 352 } 353 } 354 355 @Override getTheme()356 public Resources.Theme getTheme() { 357 synchronized (mSync) { 358 if (mTheme != null) { 359 return mTheme; 360 } 361 362 mThemeResource = Resources.selectDefaultTheme(mThemeResource, 363 getOuterContext().getApplicationInfo().targetSdkVersion); 364 initializeTheme(); 365 366 return mTheme; 367 } 368 } 369 initializeTheme()370 private void initializeTheme() { 371 if (mTheme == null) { 372 mTheme = mResources.newTheme(); 373 } 374 mTheme.applyStyle(mThemeResource, true); 375 } 376 377 @Override getClassLoader()378 public ClassLoader getClassLoader() { 379 return mClassLoader != null ? mClassLoader : (mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader()); 380 } 381 382 @Override getPackageName()383 public String getPackageName() { 384 if (mPackageInfo != null) { 385 return mPackageInfo.getPackageName(); 386 } 387 // No mPackageInfo means this is a Context for the system itself, 388 // and this here is its name. 389 return "android"; 390 } 391 392 /** @hide */ 393 @Override getBasePackageName()394 public String getBasePackageName() { 395 return mBasePackageName != null ? mBasePackageName : getPackageName(); 396 } 397 398 /** @hide */ 399 @Override getOpPackageName()400 public String getOpPackageName() { 401 return mOpPackageName != null ? mOpPackageName : getBasePackageName(); 402 } 403 404 @Override getApplicationInfo()405 public ApplicationInfo getApplicationInfo() { 406 if (mPackageInfo != null) { 407 return mPackageInfo.getApplicationInfo(); 408 } 409 throw new RuntimeException("Not supported in system context"); 410 } 411 412 @Override getPackageResourcePath()413 public String getPackageResourcePath() { 414 if (mPackageInfo != null) { 415 return mPackageInfo.getResDir(); 416 } 417 throw new RuntimeException("Not supported in system context"); 418 } 419 420 @Override getPackageCodePath()421 public String getPackageCodePath() { 422 if (mPackageInfo != null) { 423 return mPackageInfo.getAppDir(); 424 } 425 throw new RuntimeException("Not supported in system context"); 426 } 427 428 @Override getSharedPreferences(String name, int mode)429 public SharedPreferences getSharedPreferences(String name, int mode) { 430 // At least one application in the world actually passes in a null 431 // name. This happened to work because when we generated the file name 432 // we would stringify it to "null.xml". Nice. 433 if (mPackageInfo.getApplicationInfo().targetSdkVersion < 434 Build.VERSION_CODES.KITKAT) { 435 if (name == null) { 436 name = "null"; 437 } 438 } 439 440 File file; 441 synchronized (ContextImpl.class) { 442 if (mSharedPrefsPaths == null) { 443 mSharedPrefsPaths = new ArrayMap<>(); 444 } 445 file = mSharedPrefsPaths.get(name); 446 if (file == null) { 447 file = getSharedPreferencesPath(name); 448 mSharedPrefsPaths.put(name, file); 449 } 450 } 451 return getSharedPreferences(file, mode); 452 } 453 454 @Override getSharedPreferences(File file, int mode)455 public SharedPreferences getSharedPreferences(File file, int mode) { 456 SharedPreferencesImpl sp; 457 synchronized (ContextImpl.class) { 458 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked(); 459 sp = cache.get(file); 460 if (sp == null) { 461 checkMode(mode); 462 if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) { 463 if (isCredentialProtectedStorage() 464 && !getSystemService(UserManager.class) 465 .isUserUnlockingOrUnlocked(UserHandle.myUserId())) { 466 throw new IllegalStateException("SharedPreferences in credential encrypted " 467 + "storage are not available until after user is unlocked"); 468 } 469 } 470 sp = new SharedPreferencesImpl(file, mode); 471 cache.put(file, sp); 472 return sp; 473 } 474 } 475 if ((mode & Context.MODE_MULTI_PROCESS) != 0 || 476 getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { 477 // If somebody else (some other process) changed the prefs 478 // file behind our back, we reload it. This has been the 479 // historical (if undocumented) behavior. 480 sp.startReloadIfChangedUnexpectedly(); 481 } 482 return sp; 483 } 484 485 @GuardedBy("ContextImpl.class") getSharedPreferencesCacheLocked()486 private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() { 487 if (sSharedPrefsCache == null) { 488 sSharedPrefsCache = new ArrayMap<>(); 489 } 490 491 final String packageName = getPackageName(); 492 ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName); 493 if (packagePrefs == null) { 494 packagePrefs = new ArrayMap<>(); 495 sSharedPrefsCache.put(packageName, packagePrefs); 496 } 497 498 return packagePrefs; 499 } 500 501 @Override reloadSharedPreferences()502 public void reloadSharedPreferences() { 503 // Build the list of all per-context impls (i.e. caches) we know about 504 ArrayList<SharedPreferencesImpl> spImpls = new ArrayList<>(); 505 synchronized (ContextImpl.class) { 506 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked(); 507 for (int i = 0; i < cache.size(); i++) { 508 final SharedPreferencesImpl sp = cache.valueAt(i); 509 if (sp != null) { 510 spImpls.add(sp); 511 } 512 } 513 } 514 515 // Issue the reload outside the cache lock 516 for (int i = 0; i < spImpls.size(); i++) { 517 spImpls.get(i).startReloadIfChangedUnexpectedly(); 518 } 519 } 520 521 /** 522 * Try our best to migrate all files from source to target that match 523 * requested prefix. 524 * 525 * @return the number of files moved, or -1 if there was trouble. 526 */ moveFiles(File sourceDir, File targetDir, final String prefix)527 private static int moveFiles(File sourceDir, File targetDir, final String prefix) { 528 final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() { 529 @Override 530 public boolean accept(File dir, String name) { 531 return name.startsWith(prefix); 532 } 533 }); 534 535 int res = 0; 536 for (File sourceFile : sourceFiles) { 537 final File targetFile = new File(targetDir, sourceFile.getName()); 538 Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile); 539 try { 540 FileUtils.copyFileOrThrow(sourceFile, targetFile); 541 FileUtils.copyPermissions(sourceFile, targetFile); 542 if (!sourceFile.delete()) { 543 throw new IOException("Failed to clean up " + sourceFile); 544 } 545 if (res != -1) { 546 res++; 547 } 548 } catch (IOException e) { 549 Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e); 550 res = -1; 551 } 552 } 553 return res; 554 } 555 556 @Override moveSharedPreferencesFrom(Context sourceContext, String name)557 public boolean moveSharedPreferencesFrom(Context sourceContext, String name) { 558 synchronized (ContextImpl.class) { 559 final File source = sourceContext.getSharedPreferencesPath(name); 560 final File target = getSharedPreferencesPath(name); 561 562 final int res = moveFiles(source.getParentFile(), target.getParentFile(), 563 source.getName()); 564 if (res > 0) { 565 // We moved at least one file, so evict any in-memory caches for 566 // either location 567 final ArrayMap<File, SharedPreferencesImpl> cache = 568 getSharedPreferencesCacheLocked(); 569 cache.remove(source); 570 cache.remove(target); 571 } 572 return res != -1; 573 } 574 } 575 576 @Override deleteSharedPreferences(String name)577 public boolean deleteSharedPreferences(String name) { 578 synchronized (ContextImpl.class) { 579 final File prefs = getSharedPreferencesPath(name); 580 final File prefsBackup = SharedPreferencesImpl.makeBackupFile(prefs); 581 582 // Evict any in-memory caches 583 final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked(); 584 cache.remove(prefs); 585 586 prefs.delete(); 587 prefsBackup.delete(); 588 589 // We failed if files are still lingering 590 return !(prefs.exists() || prefsBackup.exists()); 591 } 592 } 593 594 @UnsupportedAppUsage getPreferencesDir()595 private File getPreferencesDir() { 596 synchronized (mSync) { 597 if (mPreferencesDir == null) { 598 mPreferencesDir = new File(getDataDir(), "shared_prefs"); 599 } 600 return ensurePrivateDirExists(mPreferencesDir); 601 } 602 } 603 604 @Override openFileInput(String name)605 public FileInputStream openFileInput(String name) 606 throws FileNotFoundException { 607 File f = makeFilename(getFilesDir(), name); 608 return new FileInputStream(f); 609 } 610 611 @Override openFileOutput(String name, int mode)612 public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { 613 checkMode(mode); 614 final boolean append = (mode&MODE_APPEND) != 0; 615 File f = makeFilename(getFilesDir(), name); 616 try { 617 FileOutputStream fos = new FileOutputStream(f, append); 618 setFilePermissionsFromMode(f.getPath(), mode, 0); 619 return fos; 620 } catch (FileNotFoundException e) { 621 } 622 623 File parent = f.getParentFile(); 624 parent.mkdir(); 625 FileUtils.setPermissions( 626 parent.getPath(), 627 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 628 -1, -1); 629 FileOutputStream fos = new FileOutputStream(f, append); 630 setFilePermissionsFromMode(f.getPath(), mode, 0); 631 return fos; 632 } 633 634 @Override deleteFile(String name)635 public boolean deleteFile(String name) { 636 File f = makeFilename(getFilesDir(), name); 637 return f.delete(); 638 } 639 640 /** 641 * Common-path handling of app data dir creation 642 */ ensurePrivateDirExists(File file)643 private static File ensurePrivateDirExists(File file) { 644 return ensurePrivateDirExists(file, 0771, -1, null); 645 } 646 ensurePrivateCacheDirExists(File file, String xattr)647 private static File ensurePrivateCacheDirExists(File file, String xattr) { 648 final int gid = UserHandle.getCacheAppGid(Process.myUid()); 649 return ensurePrivateDirExists(file, 02771, gid, xattr); 650 } 651 ensurePrivateDirExists(File file, int mode, int gid, String xattr)652 private static File ensurePrivateDirExists(File file, int mode, int gid, String xattr) { 653 if (!file.exists()) { 654 final String path = file.getAbsolutePath(); 655 try { 656 Os.mkdir(path, mode); 657 Os.chmod(path, mode); 658 if (gid != -1) { 659 Os.chown(path, -1, gid); 660 } 661 } catch (ErrnoException e) { 662 if (e.errno == OsConstants.EEXIST) { 663 // We must have raced with someone; that's okay 664 } else { 665 Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage()); 666 } 667 } 668 669 if (xattr != null) { 670 try { 671 final StructStat stat = Os.stat(file.getAbsolutePath()); 672 final byte[] value = new byte[8]; 673 Memory.pokeLong(value, 0, stat.st_ino, ByteOrder.nativeOrder()); 674 Os.setxattr(file.getParentFile().getAbsolutePath(), xattr, value, 0); 675 } catch (ErrnoException e) { 676 Log.w(TAG, "Failed to update " + xattr + ": " + e.getMessage()); 677 } 678 } 679 } 680 return file; 681 } 682 683 @Override getFilesDir()684 public File getFilesDir() { 685 synchronized (mSync) { 686 if (mFilesDir == null) { 687 mFilesDir = new File(getDataDir(), "files"); 688 } 689 return ensurePrivateDirExists(mFilesDir); 690 } 691 } 692 693 @Override getNoBackupFilesDir()694 public File getNoBackupFilesDir() { 695 synchronized (mSync) { 696 if (mNoBackupFilesDir == null) { 697 mNoBackupFilesDir = new File(getDataDir(), "no_backup"); 698 } 699 return ensurePrivateDirExists(mNoBackupFilesDir); 700 } 701 } 702 703 @Override getExternalFilesDir(String type)704 public File getExternalFilesDir(String type) { 705 // Operates on primary external storage 706 final File[] dirs = getExternalFilesDirs(type); 707 return (dirs != null && dirs.length > 0) ? dirs[0] : null; 708 } 709 710 @Override getExternalFilesDirs(String type)711 public File[] getExternalFilesDirs(String type) { 712 synchronized (mSync) { 713 File[] dirs = Environment.buildExternalStorageAppFilesDirs(getPackageName()); 714 if (type != null) { 715 dirs = Environment.buildPaths(dirs, type); 716 } 717 return ensureExternalDirsExistOrFilter(dirs); 718 } 719 } 720 721 @Override getObbDir()722 public File getObbDir() { 723 // Operates on primary external storage 724 final File[] dirs = getObbDirs(); 725 return (dirs != null && dirs.length > 0) ? dirs[0] : null; 726 } 727 728 @Override getObbDirs()729 public File[] getObbDirs() { 730 synchronized (mSync) { 731 File[] dirs = Environment.buildExternalStorageAppObbDirs(getPackageName()); 732 return ensureExternalDirsExistOrFilter(dirs); 733 } 734 } 735 736 @Override getCacheDir()737 public File getCacheDir() { 738 synchronized (mSync) { 739 if (mCacheDir == null) { 740 mCacheDir = new File(getDataDir(), "cache"); 741 } 742 return ensurePrivateCacheDirExists(mCacheDir, XATTR_INODE_CACHE); 743 } 744 } 745 746 @Override getCodeCacheDir()747 public File getCodeCacheDir() { 748 synchronized (mSync) { 749 if (mCodeCacheDir == null) { 750 mCodeCacheDir = getCodeCacheDirBeforeBind(getDataDir()); 751 } 752 return ensurePrivateCacheDirExists(mCodeCacheDir, XATTR_INODE_CODE_CACHE); 753 } 754 } 755 756 /** 757 * Helper for getting code-cache dir potentially before application bind. 758 * 759 * @hide 760 */ getCodeCacheDirBeforeBind(File dataDir)761 static File getCodeCacheDirBeforeBind(File dataDir) { 762 return new File(dataDir, "code_cache"); 763 } 764 765 @Override getExternalCacheDir()766 public File getExternalCacheDir() { 767 // Operates on primary external storage 768 final File[] dirs = getExternalCacheDirs(); 769 return (dirs != null && dirs.length > 0) ? dirs[0] : null; 770 } 771 772 @Override getExternalCacheDirs()773 public File[] getExternalCacheDirs() { 774 synchronized (mSync) { 775 File[] dirs = Environment.buildExternalStorageAppCacheDirs(getPackageName()); 776 return ensureExternalDirsExistOrFilter(dirs); 777 } 778 } 779 780 @Override getExternalMediaDirs()781 public File[] getExternalMediaDirs() { 782 synchronized (mSync) { 783 File[] dirs = Environment.buildExternalStorageAppMediaDirs(getPackageName()); 784 return ensureExternalDirsExistOrFilter(dirs); 785 } 786 } 787 788 /** 789 * @hide 790 */ 791 @Nullable 792 @Override getPreloadsFileCache()793 public File getPreloadsFileCache() { 794 return Environment.getDataPreloadsFileCacheDirectory(getPackageName()); 795 } 796 797 @Override getFileStreamPath(String name)798 public File getFileStreamPath(String name) { 799 return makeFilename(getFilesDir(), name); 800 } 801 802 @Override getSharedPreferencesPath(String name)803 public File getSharedPreferencesPath(String name) { 804 return makeFilename(getPreferencesDir(), name + ".xml"); 805 } 806 807 @Override fileList()808 public String[] fileList() { 809 return FileUtils.listOrEmpty(getFilesDir()); 810 } 811 812 @Override openOrCreateDatabase(String name, int mode, CursorFactory factory)813 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { 814 return openOrCreateDatabase(name, mode, factory, null); 815 } 816 817 @Override openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler)818 public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory, 819 DatabaseErrorHandler errorHandler) { 820 checkMode(mode); 821 File f = getDatabasePath(name); 822 int flags = SQLiteDatabase.CREATE_IF_NECESSARY; 823 if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) { 824 flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING; 825 } 826 if ((mode & MODE_NO_LOCALIZED_COLLATORS) != 0) { 827 flags |= SQLiteDatabase.NO_LOCALIZED_COLLATORS; 828 } 829 SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler); 830 setFilePermissionsFromMode(f.getPath(), mode, 0); 831 return db; 832 } 833 834 @Override moveDatabaseFrom(Context sourceContext, String name)835 public boolean moveDatabaseFrom(Context sourceContext, String name) { 836 synchronized (ContextImpl.class) { 837 final File source = sourceContext.getDatabasePath(name); 838 final File target = getDatabasePath(name); 839 return moveFiles(source.getParentFile(), target.getParentFile(), 840 source.getName()) != -1; 841 } 842 } 843 844 @Override deleteDatabase(String name)845 public boolean deleteDatabase(String name) { 846 try { 847 File f = getDatabasePath(name); 848 return SQLiteDatabase.deleteDatabase(f); 849 } catch (Exception e) { 850 } 851 return false; 852 } 853 854 @Override getDatabasePath(String name)855 public File getDatabasePath(String name) { 856 File dir; 857 File f; 858 859 if (name.charAt(0) == File.separatorChar) { 860 String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); 861 dir = new File(dirPath); 862 name = name.substring(name.lastIndexOf(File.separatorChar)); 863 f = new File(dir, name); 864 865 if (!dir.isDirectory() && dir.mkdir()) { 866 FileUtils.setPermissions(dir.getPath(), 867 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, 868 -1, -1); 869 } 870 } else { 871 dir = getDatabasesDir(); 872 f = makeFilename(dir, name); 873 } 874 875 return f; 876 } 877 878 @Override databaseList()879 public String[] databaseList() { 880 return FileUtils.listOrEmpty(getDatabasesDir()); 881 } 882 getDatabasesDir()883 private File getDatabasesDir() { 884 synchronized (mSync) { 885 if (mDatabasesDir == null) { 886 if ("android".equals(getPackageName())) { 887 mDatabasesDir = new File("/data/system"); 888 } else { 889 mDatabasesDir = new File(getDataDir(), "databases"); 890 } 891 } 892 return ensurePrivateDirExists(mDatabasesDir); 893 } 894 } 895 896 @Override 897 @Deprecated getWallpaper()898 public Drawable getWallpaper() { 899 return getWallpaperManager().getDrawable(); 900 } 901 902 @Override 903 @Deprecated peekWallpaper()904 public Drawable peekWallpaper() { 905 return getWallpaperManager().peekDrawable(); 906 } 907 908 @Override 909 @Deprecated getWallpaperDesiredMinimumWidth()910 public int getWallpaperDesiredMinimumWidth() { 911 return getWallpaperManager().getDesiredMinimumWidth(); 912 } 913 914 @Override 915 @Deprecated getWallpaperDesiredMinimumHeight()916 public int getWallpaperDesiredMinimumHeight() { 917 return getWallpaperManager().getDesiredMinimumHeight(); 918 } 919 920 @Override 921 @Deprecated setWallpaper(Bitmap bitmap)922 public void setWallpaper(Bitmap bitmap) throws IOException { 923 getWallpaperManager().setBitmap(bitmap); 924 } 925 926 @Override 927 @Deprecated setWallpaper(InputStream data)928 public void setWallpaper(InputStream data) throws IOException { 929 getWallpaperManager().setStream(data); 930 } 931 932 @Override 933 @Deprecated clearWallpaper()934 public void clearWallpaper() throws IOException { 935 getWallpaperManager().clear(); 936 } 937 getWallpaperManager()938 private WallpaperManager getWallpaperManager() { 939 return getSystemService(WallpaperManager.class); 940 } 941 942 @Override startActivity(Intent intent)943 public void startActivity(Intent intent) { 944 warnIfCallingFromSystemProcess(); 945 startActivity(intent, null); 946 } 947 948 /** @hide */ 949 @Override startActivityAsUser(Intent intent, UserHandle user)950 public void startActivityAsUser(Intent intent, UserHandle user) { 951 startActivityAsUser(intent, null, user); 952 } 953 954 @Override startActivity(Intent intent, Bundle options)955 public void startActivity(Intent intent, Bundle options) { 956 warnIfCallingFromSystemProcess(); 957 958 // Calling start activity from outside an activity without FLAG_ACTIVITY_NEW_TASK is 959 // generally not allowed, except if the caller specifies the task id the activity should 960 // be launched in. A bug was existed between N and O-MR1 which allowed this to work. We 961 // maintain this for backwards compatibility. 962 final int targetSdkVersion = getApplicationInfo().targetSdkVersion; 963 964 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 965 && (targetSdkVersion < Build.VERSION_CODES.N 966 || targetSdkVersion >= Build.VERSION_CODES.P) 967 && (options == null 968 || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) { 969 throw new AndroidRuntimeException( 970 "Calling startActivity() from outside of an Activity " 971 + " context requires the FLAG_ACTIVITY_NEW_TASK flag." 972 + " Is this really what you want?"); 973 } 974 mMainThread.getInstrumentation().execStartActivity( 975 getOuterContext(), mMainThread.getApplicationThread(), null, 976 (Activity) null, intent, -1, options); 977 } 978 979 /** @hide */ 980 @Override startActivityAsUser(Intent intent, Bundle options, UserHandle user)981 public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) { 982 try { 983 ActivityTaskManager.getService().startActivityAsUser( 984 mMainThread.getApplicationThread(), getBasePackageName(), intent, 985 intent.resolveTypeIfNeeded(getContentResolver()), 986 null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options, 987 user.getIdentifier()); 988 } catch (RemoteException e) { 989 throw e.rethrowFromSystemServer(); 990 } 991 } 992 993 @Override startActivities(Intent[] intents)994 public void startActivities(Intent[] intents) { 995 warnIfCallingFromSystemProcess(); 996 startActivities(intents, null); 997 } 998 999 /** @hide */ 1000 @Override startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle)1001 public int startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) { 1002 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 1003 throw new AndroidRuntimeException( 1004 "Calling startActivities() from outside of an Activity " 1005 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent." 1006 + " Is this really what you want?"); 1007 } 1008 return mMainThread.getInstrumentation().execStartActivitiesAsUser( 1009 getOuterContext(), mMainThread.getApplicationThread(), null, 1010 (Activity) null, intents, options, userHandle.getIdentifier()); 1011 } 1012 1013 @Override startActivities(Intent[] intents, Bundle options)1014 public void startActivities(Intent[] intents, Bundle options) { 1015 warnIfCallingFromSystemProcess(); 1016 if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { 1017 throw new AndroidRuntimeException( 1018 "Calling startActivities() from outside of an Activity " 1019 + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent." 1020 + " Is this really what you want?"); 1021 } 1022 mMainThread.getInstrumentation().execStartActivities( 1023 getOuterContext(), mMainThread.getApplicationThread(), null, 1024 (Activity) null, intents, options); 1025 } 1026 1027 @Override startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)1028 public void startIntentSender(IntentSender intent, 1029 Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) 1030 throws IntentSender.SendIntentException { 1031 startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null); 1032 } 1033 1034 @Override startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options)1035 public void startIntentSender(IntentSender intent, Intent fillInIntent, 1036 int flagsMask, int flagsValues, int extraFlags, Bundle options) 1037 throws IntentSender.SendIntentException { 1038 try { 1039 String resolvedType = null; 1040 if (fillInIntent != null) { 1041 fillInIntent.migrateExtraStreamToClipData(); 1042 fillInIntent.prepareToLeaveProcess(this); 1043 resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); 1044 } 1045 int result = ActivityTaskManager.getService() 1046 .startActivityIntentSender(mMainThread.getApplicationThread(), 1047 intent != null ? intent.getTarget() : null, 1048 intent != null ? intent.getWhitelistToken() : null, 1049 fillInIntent, resolvedType, null, null, 1050 0, flagsMask, flagsValues, options); 1051 if (result == ActivityManager.START_CANCELED) { 1052 throw new IntentSender.SendIntentException(); 1053 } 1054 Instrumentation.checkStartActivityResult(result, null); 1055 } catch (RemoteException e) { 1056 throw e.rethrowFromSystemServer(); 1057 } 1058 } 1059 1060 @Override sendBroadcast(Intent intent)1061 public void sendBroadcast(Intent intent) { 1062 warnIfCallingFromSystemProcess(); 1063 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1064 try { 1065 intent.prepareToLeaveProcess(this); 1066 ActivityManager.getService().broadcastIntent( 1067 mMainThread.getApplicationThread(), intent, resolvedType, null, 1068 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false, 1069 getUserId()); 1070 } catch (RemoteException e) { 1071 throw e.rethrowFromSystemServer(); 1072 } 1073 } 1074 1075 @Override sendBroadcast(Intent intent, String receiverPermission)1076 public void sendBroadcast(Intent intent, String receiverPermission) { 1077 warnIfCallingFromSystemProcess(); 1078 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1079 String[] receiverPermissions = receiverPermission == null ? null 1080 : new String[] {receiverPermission}; 1081 try { 1082 intent.prepareToLeaveProcess(this); 1083 ActivityManager.getService().broadcastIntent( 1084 mMainThread.getApplicationThread(), intent, resolvedType, null, 1085 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1086 null, false, false, getUserId()); 1087 } catch (RemoteException e) { 1088 throw e.rethrowFromSystemServer(); 1089 } 1090 } 1091 1092 @Override sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions)1093 public void sendBroadcastMultiplePermissions(Intent intent, String[] receiverPermissions) { 1094 warnIfCallingFromSystemProcess(); 1095 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1096 try { 1097 intent.prepareToLeaveProcess(this); 1098 ActivityManager.getService().broadcastIntent( 1099 mMainThread.getApplicationThread(), intent, resolvedType, null, 1100 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1101 null, false, false, getUserId()); 1102 } catch (RemoteException e) { 1103 throw e.rethrowFromSystemServer(); 1104 } 1105 } 1106 1107 @Override sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user, String[] receiverPermissions)1108 public void sendBroadcastAsUserMultiplePermissions(Intent intent, UserHandle user, 1109 String[] receiverPermissions) { 1110 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1111 try { 1112 intent.prepareToLeaveProcess(this); 1113 ActivityManager.getService().broadcastIntent( 1114 mMainThread.getApplicationThread(), intent, resolvedType, null, 1115 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1116 null, false, false, user.getIdentifier()); 1117 } catch (RemoteException e) { 1118 throw e.rethrowFromSystemServer(); 1119 } 1120 } 1121 1122 @Override sendBroadcast(Intent intent, String receiverPermission, Bundle options)1123 public void sendBroadcast(Intent intent, String receiverPermission, Bundle options) { 1124 warnIfCallingFromSystemProcess(); 1125 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1126 String[] receiverPermissions = receiverPermission == null ? null 1127 : new String[] {receiverPermission}; 1128 try { 1129 intent.prepareToLeaveProcess(this); 1130 ActivityManager.getService().broadcastIntent( 1131 mMainThread.getApplicationThread(), intent, resolvedType, null, 1132 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1133 options, false, false, getUserId()); 1134 } catch (RemoteException e) { 1135 throw e.rethrowFromSystemServer(); 1136 } 1137 } 1138 1139 @Override sendBroadcast(Intent intent, String receiverPermission, int appOp)1140 public void sendBroadcast(Intent intent, String receiverPermission, int appOp) { 1141 warnIfCallingFromSystemProcess(); 1142 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1143 String[] receiverPermissions = receiverPermission == null ? null 1144 : new String[] {receiverPermission}; 1145 try { 1146 intent.prepareToLeaveProcess(this); 1147 ActivityManager.getService().broadcastIntent( 1148 mMainThread.getApplicationThread(), intent, resolvedType, null, 1149 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false, 1150 getUserId()); 1151 } catch (RemoteException e) { 1152 throw e.rethrowFromSystemServer(); 1153 } 1154 } 1155 1156 @Override sendOrderedBroadcast(Intent intent, String receiverPermission)1157 public void sendOrderedBroadcast(Intent intent, String receiverPermission) { 1158 warnIfCallingFromSystemProcess(); 1159 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1160 String[] receiverPermissions = receiverPermission == null ? null 1161 : new String[] {receiverPermission}; 1162 try { 1163 intent.prepareToLeaveProcess(this); 1164 ActivityManager.getService().broadcastIntent( 1165 mMainThread.getApplicationThread(), intent, resolvedType, null, 1166 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1167 null, true, false, getUserId()); 1168 } catch (RemoteException e) { 1169 throw e.rethrowFromSystemServer(); 1170 } 1171 } 1172 1173 @Override sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1174 public void sendOrderedBroadcast(Intent intent, 1175 String receiverPermission, BroadcastReceiver resultReceiver, 1176 Handler scheduler, int initialCode, String initialData, 1177 Bundle initialExtras) { 1178 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE, 1179 resultReceiver, scheduler, initialCode, initialData, initialExtras, null); 1180 } 1181 1182 @Override sendOrderedBroadcast(Intent intent, String receiverPermission, Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1183 public void sendOrderedBroadcast(Intent intent, 1184 String receiverPermission, Bundle options, BroadcastReceiver resultReceiver, 1185 Handler scheduler, int initialCode, String initialData, 1186 Bundle initialExtras) { 1187 sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE, 1188 resultReceiver, scheduler, initialCode, initialData, initialExtras, options); 1189 } 1190 1191 @Override sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1192 public void sendOrderedBroadcast(Intent intent, 1193 String receiverPermission, int appOp, BroadcastReceiver resultReceiver, 1194 Handler scheduler, int initialCode, String initialData, 1195 Bundle initialExtras) { 1196 sendOrderedBroadcast(intent, receiverPermission, appOp, 1197 resultReceiver, scheduler, initialCode, initialData, initialExtras, null); 1198 } 1199 sendOrderedBroadcast(Intent intent, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras, Bundle options)1200 void sendOrderedBroadcast(Intent intent, 1201 String receiverPermission, int appOp, BroadcastReceiver resultReceiver, 1202 Handler scheduler, int initialCode, String initialData, 1203 Bundle initialExtras, Bundle options) { 1204 warnIfCallingFromSystemProcess(); 1205 IIntentReceiver rd = null; 1206 if (resultReceiver != null) { 1207 if (mPackageInfo != null) { 1208 if (scheduler == null) { 1209 scheduler = mMainThread.getHandler(); 1210 } 1211 rd = mPackageInfo.getReceiverDispatcher( 1212 resultReceiver, getOuterContext(), scheduler, 1213 mMainThread.getInstrumentation(), false); 1214 } else { 1215 if (scheduler == null) { 1216 scheduler = mMainThread.getHandler(); 1217 } 1218 rd = new LoadedApk.ReceiverDispatcher( 1219 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1220 } 1221 } 1222 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1223 String[] receiverPermissions = receiverPermission == null ? null 1224 : new String[] {receiverPermission}; 1225 try { 1226 intent.prepareToLeaveProcess(this); 1227 ActivityManager.getService().broadcastIntent( 1228 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1229 initialCode, initialData, initialExtras, receiverPermissions, appOp, 1230 options, true, false, getUserId()); 1231 } catch (RemoteException e) { 1232 throw e.rethrowFromSystemServer(); 1233 } 1234 } 1235 1236 @Override sendBroadcastAsUser(Intent intent, UserHandle user)1237 public void sendBroadcastAsUser(Intent intent, UserHandle user) { 1238 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1239 try { 1240 intent.prepareToLeaveProcess(this); 1241 ActivityManager.getService().broadcastIntent(mMainThread.getApplicationThread(), 1242 intent, resolvedType, null, Activity.RESULT_OK, null, null, null, 1243 AppOpsManager.OP_NONE, null, false, false, user.getIdentifier()); 1244 } catch (RemoteException e) { 1245 throw e.rethrowFromSystemServer(); 1246 } 1247 } 1248 1249 @Override sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission)1250 public void sendBroadcastAsUser(Intent intent, UserHandle user, 1251 String receiverPermission) { 1252 sendBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE); 1253 } 1254 1255 @Override sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, Bundle options)1256 public void sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, 1257 Bundle options) { 1258 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1259 String[] receiverPermissions = receiverPermission == null ? null 1260 : new String[] {receiverPermission}; 1261 try { 1262 intent.prepareToLeaveProcess(this); 1263 ActivityManager.getService().broadcastIntent( 1264 mMainThread.getApplicationThread(), intent, resolvedType, null, 1265 Activity.RESULT_OK, null, null, receiverPermissions, AppOpsManager.OP_NONE, 1266 options, false, false, user.getIdentifier()); 1267 } catch (RemoteException e) { 1268 throw e.rethrowFromSystemServer(); 1269 } 1270 } 1271 1272 @Override sendBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp)1273 public void sendBroadcastAsUser(Intent intent, UserHandle user, 1274 String receiverPermission, int appOp) { 1275 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1276 String[] receiverPermissions = receiverPermission == null ? null 1277 : new String[] {receiverPermission}; 1278 try { 1279 intent.prepareToLeaveProcess(this); 1280 ActivityManager.getService().broadcastIntent( 1281 mMainThread.getApplicationThread(), intent, resolvedType, null, 1282 Activity.RESULT_OK, null, null, receiverPermissions, appOp, null, false, false, 1283 user.getIdentifier()); 1284 } catch (RemoteException e) { 1285 throw e.rethrowFromSystemServer(); 1286 } 1287 } 1288 1289 @Override sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1290 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, 1291 String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, 1292 int initialCode, String initialData, Bundle initialExtras) { 1293 sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE, 1294 null, resultReceiver, scheduler, initialCode, initialData, initialExtras); 1295 } 1296 1297 @Override sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1298 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, 1299 String receiverPermission, int appOp, BroadcastReceiver resultReceiver, 1300 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { 1301 sendOrderedBroadcastAsUser(intent, user, receiverPermission, appOp, 1302 null, resultReceiver, scheduler, initialCode, initialData, initialExtras); 1303 } 1304 1305 @Override sendOrderedBroadcastAsUser(Intent intent, UserHandle user, String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1306 public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user, 1307 String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver, 1308 Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { 1309 IIntentReceiver rd = null; 1310 if (resultReceiver != null) { 1311 if (mPackageInfo != null) { 1312 if (scheduler == null) { 1313 scheduler = mMainThread.getHandler(); 1314 } 1315 rd = mPackageInfo.getReceiverDispatcher( 1316 resultReceiver, getOuterContext(), scheduler, 1317 mMainThread.getInstrumentation(), false); 1318 } else { 1319 if (scheduler == null) { 1320 scheduler = mMainThread.getHandler(); 1321 } 1322 rd = new LoadedApk.ReceiverDispatcher(resultReceiver, getOuterContext(), 1323 scheduler, null, false).getIIntentReceiver(); 1324 } 1325 } 1326 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1327 String[] receiverPermissions = receiverPermission == null ? null 1328 : new String[] {receiverPermission}; 1329 try { 1330 intent.prepareToLeaveProcess(this); 1331 ActivityManager.getService().broadcastIntent( 1332 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1333 initialCode, initialData, initialExtras, receiverPermissions, 1334 appOp, options, true, false, user.getIdentifier()); 1335 } catch (RemoteException e) { 1336 throw e.rethrowFromSystemServer(); 1337 } 1338 } 1339 1340 @Override sendOrderedBroadcast(Intent intent, String receiverPermission, String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, @Nullable Bundle initialExtras)1341 public void sendOrderedBroadcast(Intent intent, String receiverPermission, 1342 String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, 1343 int initialCode, String initialData, @Nullable Bundle initialExtras) { 1344 int intAppOp = AppOpsManager.OP_NONE; 1345 if (!TextUtils.isEmpty(receiverAppOp)) { 1346 intAppOp = AppOpsManager.strOpToOp(receiverAppOp); 1347 } 1348 sendOrderedBroadcastAsUser(intent, getUser(), 1349 receiverPermission, intAppOp, resultReceiver, scheduler, initialCode, initialData, 1350 initialExtras); 1351 } 1352 1353 @Override sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission, String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, String initialData, @Nullable Bundle initialExtras, Bundle options)1354 public void sendOrderedBroadcast(Intent intent, int initialCode, String receiverPermission, 1355 String receiverAppOp, BroadcastReceiver resultReceiver, Handler scheduler, 1356 String initialData, @Nullable Bundle initialExtras, Bundle options) { 1357 int intAppOp = AppOpsManager.OP_NONE; 1358 if (!TextUtils.isEmpty(receiverAppOp)) { 1359 intAppOp = AppOpsManager.strOpToOp(receiverAppOp); 1360 } 1361 sendOrderedBroadcastAsUser(intent, getUser(), receiverPermission, intAppOp, options, 1362 resultReceiver, scheduler, initialCode, initialData, initialExtras); 1363 } 1364 1365 @Override 1366 @Deprecated sendStickyBroadcast(Intent intent)1367 public void sendStickyBroadcast(Intent intent) { 1368 warnIfCallingFromSystemProcess(); 1369 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1370 try { 1371 intent.prepareToLeaveProcess(this); 1372 ActivityManager.getService().broadcastIntent( 1373 mMainThread.getApplicationThread(), intent, resolvedType, null, 1374 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true, 1375 getUserId()); 1376 } catch (RemoteException e) { 1377 throw e.rethrowFromSystemServer(); 1378 } 1379 } 1380 1381 @Override 1382 @Deprecated sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1383 public void sendStickyOrderedBroadcast(Intent intent, 1384 BroadcastReceiver resultReceiver, 1385 Handler scheduler, int initialCode, String initialData, 1386 Bundle initialExtras) { 1387 warnIfCallingFromSystemProcess(); 1388 IIntentReceiver rd = null; 1389 if (resultReceiver != null) { 1390 if (mPackageInfo != null) { 1391 if (scheduler == null) { 1392 scheduler = mMainThread.getHandler(); 1393 } 1394 rd = mPackageInfo.getReceiverDispatcher( 1395 resultReceiver, getOuterContext(), scheduler, 1396 mMainThread.getInstrumentation(), false); 1397 } else { 1398 if (scheduler == null) { 1399 scheduler = mMainThread.getHandler(); 1400 } 1401 rd = new LoadedApk.ReceiverDispatcher( 1402 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1403 } 1404 } 1405 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1406 try { 1407 intent.prepareToLeaveProcess(this); 1408 ActivityManager.getService().broadcastIntent( 1409 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1410 initialCode, initialData, initialExtras, null, 1411 AppOpsManager.OP_NONE, null, true, true, getUserId()); 1412 } catch (RemoteException e) { 1413 throw e.rethrowFromSystemServer(); 1414 } 1415 } 1416 1417 @Override 1418 @Deprecated removeStickyBroadcast(Intent intent)1419 public void removeStickyBroadcast(Intent intent) { 1420 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1421 if (resolvedType != null) { 1422 intent = new Intent(intent); 1423 intent.setDataAndType(intent.getData(), resolvedType); 1424 } 1425 try { 1426 intent.prepareToLeaveProcess(this); 1427 ActivityManager.getService().unbroadcastIntent( 1428 mMainThread.getApplicationThread(), intent, getUserId()); 1429 } catch (RemoteException e) { 1430 throw e.rethrowFromSystemServer(); 1431 } 1432 } 1433 1434 @Override 1435 @Deprecated sendStickyBroadcastAsUser(Intent intent, UserHandle user)1436 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) { 1437 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1438 try { 1439 intent.prepareToLeaveProcess(this); 1440 ActivityManager.getService().broadcastIntent( 1441 mMainThread.getApplicationThread(), intent, resolvedType, null, 1442 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, true, 1443 user.getIdentifier()); 1444 } catch (RemoteException e) { 1445 throw e.rethrowFromSystemServer(); 1446 } 1447 } 1448 1449 @Override 1450 @Deprecated sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options)1451 public void sendStickyBroadcastAsUser(Intent intent, UserHandle user, Bundle options) { 1452 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1453 try { 1454 intent.prepareToLeaveProcess(this); 1455 ActivityManager.getService().broadcastIntent( 1456 mMainThread.getApplicationThread(), intent, resolvedType, null, 1457 Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, options, false, true, 1458 user.getIdentifier()); 1459 } catch (RemoteException e) { 1460 throw e.rethrowFromSystemServer(); 1461 } 1462 } 1463 1464 @Override 1465 @Deprecated sendStickyOrderedBroadcastAsUser(Intent intent, UserHandle user, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)1466 public void sendStickyOrderedBroadcastAsUser(Intent intent, 1467 UserHandle user, BroadcastReceiver resultReceiver, 1468 Handler scheduler, int initialCode, String initialData, 1469 Bundle initialExtras) { 1470 IIntentReceiver rd = null; 1471 if (resultReceiver != null) { 1472 if (mPackageInfo != null) { 1473 if (scheduler == null) { 1474 scheduler = mMainThread.getHandler(); 1475 } 1476 rd = mPackageInfo.getReceiverDispatcher( 1477 resultReceiver, getOuterContext(), scheduler, 1478 mMainThread.getInstrumentation(), false); 1479 } else { 1480 if (scheduler == null) { 1481 scheduler = mMainThread.getHandler(); 1482 } 1483 rd = new LoadedApk.ReceiverDispatcher( 1484 resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); 1485 } 1486 } 1487 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1488 try { 1489 intent.prepareToLeaveProcess(this); 1490 ActivityManager.getService().broadcastIntent( 1491 mMainThread.getApplicationThread(), intent, resolvedType, rd, 1492 initialCode, initialData, initialExtras, null, 1493 AppOpsManager.OP_NONE, null, true, true, user.getIdentifier()); 1494 } catch (RemoteException e) { 1495 throw e.rethrowFromSystemServer(); 1496 } 1497 } 1498 1499 @Override 1500 @Deprecated removeStickyBroadcastAsUser(Intent intent, UserHandle user)1501 public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) { 1502 String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); 1503 if (resolvedType != null) { 1504 intent = new Intent(intent); 1505 intent.setDataAndType(intent.getData(), resolvedType); 1506 } 1507 try { 1508 intent.prepareToLeaveProcess(this); 1509 ActivityManager.getService().unbroadcastIntent( 1510 mMainThread.getApplicationThread(), intent, user.getIdentifier()); 1511 } catch (RemoteException e) { 1512 throw e.rethrowFromSystemServer(); 1513 } 1514 } 1515 1516 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter)1517 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { 1518 return registerReceiver(receiver, filter, null, null); 1519 } 1520 1521 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags)1522 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 1523 int flags) { 1524 return registerReceiver(receiver, filter, null, null, flags); 1525 } 1526 1527 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)1528 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 1529 String broadcastPermission, Handler scheduler) { 1530 return registerReceiverInternal(receiver, getUserId(), 1531 filter, broadcastPermission, scheduler, getOuterContext(), 0); 1532 } 1533 1534 @Override registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, int flags)1535 public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, 1536 String broadcastPermission, Handler scheduler, int flags) { 1537 return registerReceiverInternal(receiver, getUserId(), 1538 filter, broadcastPermission, scheduler, getOuterContext(), flags); 1539 } 1540 1541 @Override registerReceiverForAllUsers(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)1542 public Intent registerReceiverForAllUsers(BroadcastReceiver receiver, 1543 IntentFilter filter, String broadcastPermission, Handler scheduler) { 1544 return registerReceiverAsUser(receiver, UserHandle.ALL, 1545 filter, broadcastPermission, scheduler); 1546 } 1547 1548 @Override registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)1549 public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, 1550 IntentFilter filter, String broadcastPermission, Handler scheduler) { 1551 return registerReceiverInternal(receiver, user.getIdentifier(), 1552 filter, broadcastPermission, scheduler, getOuterContext(), 0); 1553 } 1554 registerReceiverInternal(BroadcastReceiver receiver, int userId, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context, int flags)1555 private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId, 1556 IntentFilter filter, String broadcastPermission, 1557 Handler scheduler, Context context, int flags) { 1558 IIntentReceiver rd = null; 1559 if (receiver != null) { 1560 if (mPackageInfo != null && context != null) { 1561 if (scheduler == null) { 1562 scheduler = mMainThread.getHandler(); 1563 } 1564 rd = mPackageInfo.getReceiverDispatcher( 1565 receiver, context, scheduler, 1566 mMainThread.getInstrumentation(), true); 1567 } else { 1568 if (scheduler == null) { 1569 scheduler = mMainThread.getHandler(); 1570 } 1571 rd = new LoadedApk.ReceiverDispatcher( 1572 receiver, context, scheduler, null, true).getIIntentReceiver(); 1573 } 1574 } 1575 try { 1576 final Intent intent = ActivityManager.getService().registerReceiver( 1577 mMainThread.getApplicationThread(), mBasePackageName, rd, filter, 1578 broadcastPermission, userId, flags); 1579 if (intent != null) { 1580 intent.setExtrasClassLoader(getClassLoader()); 1581 intent.prepareToEnterProcess(); 1582 } 1583 return intent; 1584 } catch (RemoteException e) { 1585 throw e.rethrowFromSystemServer(); 1586 } 1587 } 1588 1589 @Override unregisterReceiver(BroadcastReceiver receiver)1590 public void unregisterReceiver(BroadcastReceiver receiver) { 1591 if (mPackageInfo != null) { 1592 IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( 1593 getOuterContext(), receiver); 1594 try { 1595 ActivityManager.getService().unregisterReceiver(rd); 1596 } catch (RemoteException e) { 1597 throw e.rethrowFromSystemServer(); 1598 } 1599 } else { 1600 throw new RuntimeException("Not supported in system context"); 1601 } 1602 } 1603 validateServiceIntent(Intent service)1604 private void validateServiceIntent(Intent service) { 1605 if (service.getComponent() == null && service.getPackage() == null) { 1606 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) { 1607 IllegalArgumentException ex = new IllegalArgumentException( 1608 "Service Intent must be explicit: " + service); 1609 throw ex; 1610 } else { 1611 Log.w(TAG, "Implicit intents with startService are not safe: " + service 1612 + " " + Debug.getCallers(2, 3)); 1613 } 1614 } 1615 } 1616 1617 @Override startService(Intent service)1618 public ComponentName startService(Intent service) { 1619 warnIfCallingFromSystemProcess(); 1620 return startServiceCommon(service, false, mUser); 1621 } 1622 1623 @Override startForegroundService(Intent service)1624 public ComponentName startForegroundService(Intent service) { 1625 warnIfCallingFromSystemProcess(); 1626 return startServiceCommon(service, true, mUser); 1627 } 1628 1629 @Override stopService(Intent service)1630 public boolean stopService(Intent service) { 1631 warnIfCallingFromSystemProcess(); 1632 return stopServiceCommon(service, mUser); 1633 } 1634 1635 @Override startServiceAsUser(Intent service, UserHandle user)1636 public ComponentName startServiceAsUser(Intent service, UserHandle user) { 1637 return startServiceCommon(service, false, user); 1638 } 1639 1640 @Override startForegroundServiceAsUser(Intent service, UserHandle user)1641 public ComponentName startForegroundServiceAsUser(Intent service, UserHandle user) { 1642 return startServiceCommon(service, true, user); 1643 } 1644 startServiceCommon(Intent service, boolean requireForeground, UserHandle user)1645 private ComponentName startServiceCommon(Intent service, boolean requireForeground, 1646 UserHandle user) { 1647 try { 1648 validateServiceIntent(service); 1649 service.prepareToLeaveProcess(this); 1650 ComponentName cn = ActivityManager.getService().startService( 1651 mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded( 1652 getContentResolver()), requireForeground, 1653 getOpPackageName(), user.getIdentifier()); 1654 if (cn != null) { 1655 if (cn.getPackageName().equals("!")) { 1656 throw new SecurityException( 1657 "Not allowed to start service " + service 1658 + " without permission " + cn.getClassName()); 1659 } else if (cn.getPackageName().equals("!!")) { 1660 throw new SecurityException( 1661 "Unable to start service " + service 1662 + ": " + cn.getClassName()); 1663 } else if (cn.getPackageName().equals("?")) { 1664 throw new IllegalStateException( 1665 "Not allowed to start service " + service + ": " + cn.getClassName()); 1666 } 1667 } 1668 return cn; 1669 } catch (RemoteException e) { 1670 throw e.rethrowFromSystemServer(); 1671 } 1672 } 1673 1674 @Override stopServiceAsUser(Intent service, UserHandle user)1675 public boolean stopServiceAsUser(Intent service, UserHandle user) { 1676 return stopServiceCommon(service, user); 1677 } 1678 stopServiceCommon(Intent service, UserHandle user)1679 private boolean stopServiceCommon(Intent service, UserHandle user) { 1680 try { 1681 validateServiceIntent(service); 1682 service.prepareToLeaveProcess(this); 1683 int res = ActivityManager.getService().stopService( 1684 mMainThread.getApplicationThread(), service, 1685 service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier()); 1686 if (res < 0) { 1687 throw new SecurityException( 1688 "Not allowed to stop service " + service); 1689 } 1690 return res != 0; 1691 } catch (RemoteException e) { 1692 throw e.rethrowFromSystemServer(); 1693 } 1694 } 1695 1696 @Override bindService(Intent service, ServiceConnection conn, int flags)1697 public boolean bindService(Intent service, ServiceConnection conn, int flags) { 1698 warnIfCallingFromSystemProcess(); 1699 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null, 1700 getUser()); 1701 } 1702 1703 @Override bindService( Intent service, int flags, Executor executor, ServiceConnection conn)1704 public boolean bindService( 1705 Intent service, int flags, Executor executor, ServiceConnection conn) { 1706 warnIfCallingFromSystemProcess(); 1707 return bindServiceCommon(service, conn, flags, null, null, executor, getUser()); 1708 } 1709 1710 @Override bindIsolatedService(Intent service, int flags, String instanceName, Executor executor, ServiceConnection conn)1711 public boolean bindIsolatedService(Intent service, int flags, String instanceName, 1712 Executor executor, ServiceConnection conn) { 1713 warnIfCallingFromSystemProcess(); 1714 if (instanceName == null) { 1715 throw new NullPointerException("null instanceName"); 1716 } 1717 return bindServiceCommon(service, conn, flags, instanceName, null, executor, getUser()); 1718 } 1719 1720 /** @hide */ 1721 @Override bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user)1722 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, 1723 UserHandle user) { 1724 return bindServiceCommon(service, conn, flags, null, mMainThread.getHandler(), null, user); 1725 } 1726 1727 /** @hide */ 1728 @Override bindServiceAsUser(Intent service, ServiceConnection conn, int flags, Handler handler, UserHandle user)1729 public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags, 1730 Handler handler, UserHandle user) { 1731 if (handler == null) { 1732 throw new IllegalArgumentException("handler must not be null."); 1733 } 1734 return bindServiceCommon(service, conn, flags, null, handler, null, user); 1735 } 1736 1737 /** @hide */ 1738 @Override getServiceDispatcher(ServiceConnection conn, Handler handler, int flags)1739 public IServiceConnection getServiceDispatcher(ServiceConnection conn, Handler handler, 1740 int flags) { 1741 return mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags); 1742 } 1743 1744 /** @hide */ 1745 @Override getIApplicationThread()1746 public IApplicationThread getIApplicationThread() { 1747 return mMainThread.getApplicationThread(); 1748 } 1749 1750 /** @hide */ 1751 @Override getMainThreadHandler()1752 public Handler getMainThreadHandler() { 1753 return mMainThread.getHandler(); 1754 } 1755 bindServiceCommon(Intent service, ServiceConnection conn, int flags, String instanceName, Handler handler, Executor executor, UserHandle user)1756 private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, 1757 String instanceName, Handler handler, Executor executor, UserHandle user) { 1758 // Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser. 1759 IServiceConnection sd; 1760 if (conn == null) { 1761 throw new IllegalArgumentException("connection is null"); 1762 } 1763 if (handler != null && executor != null) { 1764 throw new IllegalArgumentException("Handler and Executor both supplied"); 1765 } 1766 if (mPackageInfo != null) { 1767 if (executor != null) { 1768 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags); 1769 } else { 1770 sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags); 1771 } 1772 } else { 1773 throw new RuntimeException("Not supported in system context"); 1774 } 1775 validateServiceIntent(service); 1776 try { 1777 IBinder token = getActivityToken(); 1778 if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null 1779 && mPackageInfo.getApplicationInfo().targetSdkVersion 1780 < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 1781 flags |= BIND_WAIVE_PRIORITY; 1782 } 1783 service.prepareToLeaveProcess(this); 1784 int res = ActivityManager.getService().bindIsolatedService( 1785 mMainThread.getApplicationThread(), getActivityToken(), service, 1786 service.resolveTypeIfNeeded(getContentResolver()), 1787 sd, flags, instanceName, getOpPackageName(), user.getIdentifier()); 1788 if (res < 0) { 1789 throw new SecurityException( 1790 "Not allowed to bind to service " + service); 1791 } 1792 return res != 0; 1793 } catch (RemoteException e) { 1794 throw e.rethrowFromSystemServer(); 1795 } 1796 } 1797 1798 @Override updateServiceGroup(@onNull ServiceConnection conn, int group, int importance)1799 public void updateServiceGroup(@NonNull ServiceConnection conn, int group, int importance) { 1800 if (conn == null) { 1801 throw new IllegalArgumentException("connection is null"); 1802 } 1803 if (mPackageInfo != null) { 1804 IServiceConnection sd = mPackageInfo.lookupServiceDispatcher(conn, getOuterContext()); 1805 if (sd == null) { 1806 throw new IllegalArgumentException("ServiceConnection not currently bound: " 1807 + conn); 1808 } 1809 try { 1810 ActivityManager.getService().updateServiceGroup(sd, group, importance); 1811 } catch (RemoteException e) { 1812 throw e.rethrowFromSystemServer(); 1813 } 1814 } else { 1815 throw new RuntimeException("Not supported in system context"); 1816 } 1817 } 1818 1819 @Override unbindService(ServiceConnection conn)1820 public void unbindService(ServiceConnection conn) { 1821 if (conn == null) { 1822 throw new IllegalArgumentException("connection is null"); 1823 } 1824 if (mPackageInfo != null) { 1825 IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( 1826 getOuterContext(), conn); 1827 try { 1828 ActivityManager.getService().unbindService(sd); 1829 } catch (RemoteException e) { 1830 throw e.rethrowFromSystemServer(); 1831 } 1832 } else { 1833 throw new RuntimeException("Not supported in system context"); 1834 } 1835 } 1836 1837 @Override startInstrumentation(ComponentName className, String profileFile, Bundle arguments)1838 public boolean startInstrumentation(ComponentName className, 1839 String profileFile, Bundle arguments) { 1840 try { 1841 if (arguments != null) { 1842 arguments.setAllowFds(false); 1843 } 1844 return ActivityManager.getService().startInstrumentation( 1845 className, profileFile, 0, arguments, null, null, getUserId(), 1846 null /* ABI override */); 1847 } catch (RemoteException e) { 1848 throw e.rethrowFromSystemServer(); 1849 } 1850 } 1851 1852 @Override getSystemService(String name)1853 public Object getSystemService(String name) { 1854 return SystemServiceRegistry.getSystemService(this, name); 1855 } 1856 1857 @Override getSystemServiceName(Class<?> serviceClass)1858 public String getSystemServiceName(Class<?> serviceClass) { 1859 return SystemServiceRegistry.getSystemServiceName(serviceClass); 1860 } 1861 1862 @Override checkPermission(String permission, int pid, int uid)1863 public int checkPermission(String permission, int pid, int uid) { 1864 if (permission == null) { 1865 throw new IllegalArgumentException("permission is null"); 1866 } 1867 1868 final IActivityManager am = ActivityManager.getService(); 1869 if (am == null) { 1870 // Well this is super awkward; we somehow don't have an active 1871 // ActivityManager instance. If we're testing a root or system 1872 // UID, then they totally have whatever permission this is. 1873 final int appId = UserHandle.getAppId(uid); 1874 if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) { 1875 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission); 1876 return PackageManager.PERMISSION_GRANTED; 1877 } 1878 Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold " 1879 + permission); 1880 return PackageManager.PERMISSION_DENIED; 1881 } 1882 1883 try { 1884 return am.checkPermission(permission, pid, uid); 1885 } catch (RemoteException e) { 1886 throw e.rethrowFromSystemServer(); 1887 } 1888 } 1889 1890 /** @hide */ 1891 @Override checkPermission(String permission, int pid, int uid, IBinder callerToken)1892 public int checkPermission(String permission, int pid, int uid, IBinder callerToken) { 1893 if (permission == null) { 1894 throw new IllegalArgumentException("permission is null"); 1895 } 1896 1897 try { 1898 return ActivityManager.getService().checkPermissionWithToken( 1899 permission, pid, uid, callerToken); 1900 } catch (RemoteException e) { 1901 throw e.rethrowFromSystemServer(); 1902 } 1903 } 1904 1905 @Override checkCallingPermission(String permission)1906 public int checkCallingPermission(String permission) { 1907 if (permission == null) { 1908 throw new IllegalArgumentException("permission is null"); 1909 } 1910 1911 int pid = Binder.getCallingPid(); 1912 if (pid != Process.myPid()) { 1913 return checkPermission(permission, pid, Binder.getCallingUid()); 1914 } 1915 return PackageManager.PERMISSION_DENIED; 1916 } 1917 1918 @Override checkCallingOrSelfPermission(String permission)1919 public int checkCallingOrSelfPermission(String permission) { 1920 if (permission == null) { 1921 throw new IllegalArgumentException("permission is null"); 1922 } 1923 1924 return checkPermission(permission, Binder.getCallingPid(), 1925 Binder.getCallingUid()); 1926 } 1927 1928 @Override checkSelfPermission(String permission)1929 public int checkSelfPermission(String permission) { 1930 if (permission == null) { 1931 throw new IllegalArgumentException("permission is null"); 1932 } 1933 1934 return checkPermission(permission, Process.myPid(), Process.myUid()); 1935 } 1936 enforce( String permission, int resultOfCheck, boolean selfToo, int uid, String message)1937 private void enforce( 1938 String permission, int resultOfCheck, 1939 boolean selfToo, int uid, String message) { 1940 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 1941 throw new SecurityException( 1942 (message != null ? (message + ": ") : "") + 1943 (selfToo 1944 ? "Neither user " + uid + " nor current process has " 1945 : "uid " + uid + " does not have ") + 1946 permission + 1947 "."); 1948 } 1949 } 1950 1951 @Override enforcePermission( String permission, int pid, int uid, String message)1952 public void enforcePermission( 1953 String permission, int pid, int uid, String message) { 1954 enforce(permission, 1955 checkPermission(permission, pid, uid), 1956 false, 1957 uid, 1958 message); 1959 } 1960 1961 @Override enforceCallingPermission(String permission, String message)1962 public void enforceCallingPermission(String permission, String message) { 1963 enforce(permission, 1964 checkCallingPermission(permission), 1965 false, 1966 Binder.getCallingUid(), 1967 message); 1968 } 1969 1970 @Override enforceCallingOrSelfPermission( String permission, String message)1971 public void enforceCallingOrSelfPermission( 1972 String permission, String message) { 1973 enforce(permission, 1974 checkCallingOrSelfPermission(permission), 1975 true, 1976 Binder.getCallingUid(), 1977 message); 1978 } 1979 1980 @Override grantUriPermission(String toPackage, Uri uri, int modeFlags)1981 public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { 1982 try { 1983 ActivityManager.getService().grantUriPermission( 1984 mMainThread.getApplicationThread(), toPackage, 1985 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri)); 1986 } catch (RemoteException e) { 1987 throw e.rethrowFromSystemServer(); 1988 } 1989 } 1990 1991 @Override revokeUriPermission(Uri uri, int modeFlags)1992 public void revokeUriPermission(Uri uri, int modeFlags) { 1993 try { 1994 ActivityManager.getService().revokeUriPermission( 1995 mMainThread.getApplicationThread(), null, 1996 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri)); 1997 } catch (RemoteException e) { 1998 throw e.rethrowFromSystemServer(); 1999 } 2000 } 2001 2002 @Override revokeUriPermission(String targetPackage, Uri uri, int modeFlags)2003 public void revokeUriPermission(String targetPackage, Uri uri, int modeFlags) { 2004 try { 2005 ActivityManager.getService().revokeUriPermission( 2006 mMainThread.getApplicationThread(), targetPackage, 2007 ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri)); 2008 } catch (RemoteException e) { 2009 throw e.rethrowFromSystemServer(); 2010 } 2011 } 2012 2013 @Override checkUriPermission(Uri uri, int pid, int uid, int modeFlags)2014 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 2015 try { 2016 return ActivityManager.getService().checkUriPermission( 2017 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags, 2018 resolveUserId(uri), null); 2019 } catch (RemoteException e) { 2020 throw e.rethrowFromSystemServer(); 2021 } 2022 } 2023 2024 /** @hide */ 2025 @Override checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken)2026 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) { 2027 try { 2028 return ActivityManager.getService().checkUriPermission( 2029 ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags, 2030 resolveUserId(uri), callerToken); 2031 } catch (RemoteException e) { 2032 throw e.rethrowFromSystemServer(); 2033 } 2034 } 2035 resolveUserId(Uri uri)2036 private int resolveUserId(Uri uri) { 2037 return ContentProvider.getUserIdFromUri(uri, getUserId()); 2038 } 2039 2040 @Override checkCallingUriPermission(Uri uri, int modeFlags)2041 public int checkCallingUriPermission(Uri uri, int modeFlags) { 2042 int pid = Binder.getCallingPid(); 2043 if (pid != Process.myPid()) { 2044 return checkUriPermission(uri, pid, 2045 Binder.getCallingUid(), modeFlags); 2046 } 2047 return PackageManager.PERMISSION_DENIED; 2048 } 2049 2050 @Override checkCallingOrSelfUriPermission(Uri uri, int modeFlags)2051 public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { 2052 return checkUriPermission(uri, Binder.getCallingPid(), 2053 Binder.getCallingUid(), modeFlags); 2054 } 2055 2056 @Override checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags)2057 public int checkUriPermission(Uri uri, String readPermission, 2058 String writePermission, int pid, int uid, int modeFlags) { 2059 if (DEBUG) { 2060 Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" 2061 + readPermission + " writePermission=" + writePermission 2062 + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); 2063 } 2064 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 2065 if (readPermission == null 2066 || checkPermission(readPermission, pid, uid) 2067 == PackageManager.PERMISSION_GRANTED) { 2068 return PackageManager.PERMISSION_GRANTED; 2069 } 2070 } 2071 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 2072 if (writePermission == null 2073 || checkPermission(writePermission, pid, uid) 2074 == PackageManager.PERMISSION_GRANTED) { 2075 return PackageManager.PERMISSION_GRANTED; 2076 } 2077 } 2078 return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) 2079 : PackageManager.PERMISSION_DENIED; 2080 } 2081 uriModeFlagToString(int uriModeFlags)2082 private String uriModeFlagToString(int uriModeFlags) { 2083 StringBuilder builder = new StringBuilder(); 2084 if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 2085 builder.append("read and "); 2086 } 2087 if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 2088 builder.append("write and "); 2089 } 2090 if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) { 2091 builder.append("persistable and "); 2092 } 2093 if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) { 2094 builder.append("prefix and "); 2095 } 2096 2097 if (builder.length() > 5) { 2098 builder.setLength(builder.length() - 5); 2099 return builder.toString(); 2100 } else { 2101 throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags); 2102 } 2103 } 2104 enforceForUri( int modeFlags, int resultOfCheck, boolean selfToo, int uid, Uri uri, String message)2105 private void enforceForUri( 2106 int modeFlags, int resultOfCheck, boolean selfToo, 2107 int uid, Uri uri, String message) { 2108 if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { 2109 throw new SecurityException( 2110 (message != null ? (message + ": ") : "") + 2111 (selfToo 2112 ? "Neither user " + uid + " nor current process has " 2113 : "User " + uid + " does not have ") + 2114 uriModeFlagToString(modeFlags) + 2115 " permission on " + 2116 uri + 2117 "."); 2118 } 2119 } 2120 2121 @Override enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message)2122 public void enforceUriPermission( 2123 Uri uri, int pid, int uid, int modeFlags, String message) { 2124 enforceForUri( 2125 modeFlags, checkUriPermission(uri, pid, uid, modeFlags), 2126 false, uid, uri, message); 2127 } 2128 2129 @Override enforceCallingUriPermission( Uri uri, int modeFlags, String message)2130 public void enforceCallingUriPermission( 2131 Uri uri, int modeFlags, String message) { 2132 enforceForUri( 2133 modeFlags, checkCallingUriPermission(uri, modeFlags), 2134 false, 2135 Binder.getCallingUid(), uri, message); 2136 } 2137 2138 @Override enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message)2139 public void enforceCallingOrSelfUriPermission( 2140 Uri uri, int modeFlags, String message) { 2141 enforceForUri( 2142 modeFlags, 2143 checkCallingOrSelfUriPermission(uri, modeFlags), true, 2144 Binder.getCallingUid(), uri, message); 2145 } 2146 2147 @Override enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message)2148 public void enforceUriPermission( 2149 Uri uri, String readPermission, String writePermission, 2150 int pid, int uid, int modeFlags, String message) { 2151 enforceForUri(modeFlags, 2152 checkUriPermission( 2153 uri, readPermission, writePermission, pid, uid, 2154 modeFlags), 2155 false, 2156 uid, 2157 uri, 2158 message); 2159 } 2160 2161 /** 2162 * Logs a warning if the system process directly called a method such as 2163 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}. 2164 * The "AsUser" variants allow us to properly enforce the user's restrictions. 2165 */ warnIfCallingFromSystemProcess()2166 private void warnIfCallingFromSystemProcess() { 2167 if (Process.myUid() == Process.SYSTEM_UID) { 2168 Slog.w(TAG, "Calling a method in the system process without a qualified user: " 2169 + Debug.getCallers(5)); 2170 } 2171 } 2172 createResources(IBinder activityToken, LoadedApk pi, String splitName, int displayId, Configuration overrideConfig, CompatibilityInfo compatInfo)2173 private static Resources createResources(IBinder activityToken, LoadedApk pi, String splitName, 2174 int displayId, Configuration overrideConfig, CompatibilityInfo compatInfo) { 2175 final String[] splitResDirs; 2176 final ClassLoader classLoader; 2177 try { 2178 splitResDirs = pi.getSplitPaths(splitName); 2179 classLoader = pi.getSplitClassLoader(splitName); 2180 } catch (NameNotFoundException e) { 2181 throw new RuntimeException(e); 2182 } 2183 return ResourcesManager.getInstance().getResources(activityToken, 2184 pi.getResDir(), 2185 splitResDirs, 2186 pi.getOverlayDirs(), 2187 pi.getApplicationInfo().sharedLibraryFiles, 2188 displayId, 2189 overrideConfig, 2190 compatInfo, 2191 classLoader); 2192 } 2193 2194 @Override createApplicationContext(ApplicationInfo application, int flags)2195 public Context createApplicationContext(ApplicationInfo application, int flags) 2196 throws NameNotFoundException { 2197 LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(), 2198 flags | CONTEXT_REGISTER_PACKAGE); 2199 if (pi != null) { 2200 ContextImpl c = new ContextImpl(this, mMainThread, pi, null, mActivityToken, 2201 new UserHandle(UserHandle.getUserId(application.uid)), flags, null, null); 2202 2203 final int displayId = getDisplayId(); 2204 2205 c.setResources(createResources(mActivityToken, pi, null, displayId, null, 2206 getDisplayAdjustments(displayId).getCompatibilityInfo())); 2207 if (c.mResources != null) { 2208 return c; 2209 } 2210 } 2211 2212 throw new PackageManager.NameNotFoundException( 2213 "Application package " + application.packageName + " not found"); 2214 } 2215 2216 @Override createPackageContext(String packageName, int flags)2217 public Context createPackageContext(String packageName, int flags) 2218 throws NameNotFoundException { 2219 return createPackageContextAsUser(packageName, flags, mUser); 2220 } 2221 2222 @Override createPackageContextAsUser(String packageName, int flags, UserHandle user)2223 public Context createPackageContextAsUser(String packageName, int flags, UserHandle user) 2224 throws NameNotFoundException { 2225 if (packageName.equals("system") || packageName.equals("android")) { 2226 // The system resources are loaded in every application, so we can safely copy 2227 // the context without reloading Resources. 2228 return new ContextImpl(this, mMainThread, mPackageInfo, null, mActivityToken, user, 2229 flags, null, null); 2230 } 2231 2232 LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(), 2233 flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier()); 2234 if (pi != null) { 2235 ContextImpl c = new ContextImpl(this, mMainThread, pi, null, mActivityToken, user, 2236 flags, null, null); 2237 2238 final int displayId = getDisplayId(); 2239 2240 c.setResources(createResources(mActivityToken, pi, null, displayId, null, 2241 getDisplayAdjustments(displayId).getCompatibilityInfo())); 2242 if (c.mResources != null) { 2243 return c; 2244 } 2245 } 2246 2247 // Should be a better exception. 2248 throw new PackageManager.NameNotFoundException( 2249 "Application package " + packageName + " not found"); 2250 } 2251 2252 @Override createContextAsUser(UserHandle user, @CreatePackageOptions int flags)2253 public Context createContextAsUser(UserHandle user, @CreatePackageOptions int flags) { 2254 try { 2255 return createPackageContextAsUser(getPackageName(), flags, user); 2256 } catch (NameNotFoundException e) { 2257 throw new IllegalStateException("Own package not found: package=" + getPackageName()); 2258 } 2259 } 2260 2261 @Override createContextForSplit(String splitName)2262 public Context createContextForSplit(String splitName) throws NameNotFoundException { 2263 if (!mPackageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) { 2264 // All Splits are always loaded. 2265 return this; 2266 } 2267 2268 final ClassLoader classLoader = mPackageInfo.getSplitClassLoader(splitName); 2269 final String[] paths = mPackageInfo.getSplitPaths(splitName); 2270 2271 final ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, splitName, 2272 mActivityToken, mUser, mFlags, classLoader, null); 2273 2274 final int displayId = getDisplayId(); 2275 2276 context.setResources(ResourcesManager.getInstance().getResources( 2277 mActivityToken, 2278 mPackageInfo.getResDir(), 2279 paths, 2280 mPackageInfo.getOverlayDirs(), 2281 mPackageInfo.getApplicationInfo().sharedLibraryFiles, 2282 displayId, 2283 null, 2284 mPackageInfo.getCompatibilityInfo(), 2285 classLoader)); 2286 return context; 2287 } 2288 2289 @Override createConfigurationContext(Configuration overrideConfiguration)2290 public Context createConfigurationContext(Configuration overrideConfiguration) { 2291 if (overrideConfiguration == null) { 2292 throw new IllegalArgumentException("overrideConfiguration must not be null"); 2293 } 2294 2295 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mSplitName, 2296 mActivityToken, mUser, mFlags, mClassLoader, null); 2297 2298 final int displayId = getDisplayId(); 2299 context.setResources(createResources(mActivityToken, mPackageInfo, mSplitName, displayId, 2300 overrideConfiguration, getDisplayAdjustments(displayId).getCompatibilityInfo())); 2301 return context; 2302 } 2303 2304 @Override createDisplayContext(Display display)2305 public Context createDisplayContext(Display display) { 2306 if (display == null) { 2307 throw new IllegalArgumentException("display must not be null"); 2308 } 2309 2310 ContextImpl context = new ContextImpl(this, mMainThread, mPackageInfo, mSplitName, 2311 mActivityToken, mUser, mFlags, mClassLoader, null); 2312 2313 final int displayId = display.getDisplayId(); 2314 context.setResources(createResources(mActivityToken, mPackageInfo, mSplitName, displayId, 2315 null, getDisplayAdjustments(displayId).getCompatibilityInfo())); 2316 context.mDisplay = display; 2317 return context; 2318 } 2319 2320 @Override createDeviceProtectedStorageContext()2321 public Context createDeviceProtectedStorageContext() { 2322 final int flags = (mFlags & ~Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE) 2323 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE; 2324 return new ContextImpl(this, mMainThread, mPackageInfo, mSplitName, mActivityToken, mUser, 2325 flags, mClassLoader, null); 2326 } 2327 2328 @Override createCredentialProtectedStorageContext()2329 public Context createCredentialProtectedStorageContext() { 2330 final int flags = (mFlags & ~Context.CONTEXT_DEVICE_PROTECTED_STORAGE) 2331 | Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE; 2332 return new ContextImpl(this, mMainThread, mPackageInfo, mSplitName, mActivityToken, mUser, 2333 flags, mClassLoader, null); 2334 } 2335 2336 @Override isRestricted()2337 public boolean isRestricted() { 2338 return (mFlags & Context.CONTEXT_RESTRICTED) != 0; 2339 } 2340 2341 @Override isDeviceProtectedStorage()2342 public boolean isDeviceProtectedStorage() { 2343 return (mFlags & Context.CONTEXT_DEVICE_PROTECTED_STORAGE) != 0; 2344 } 2345 2346 @Override isCredentialProtectedStorage()2347 public boolean isCredentialProtectedStorage() { 2348 return (mFlags & Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE) != 0; 2349 } 2350 2351 @Override canLoadUnsafeResources()2352 public boolean canLoadUnsafeResources() { 2353 if (getPackageName().equals(getOpPackageName())) { 2354 return true; 2355 } 2356 return (mFlags & Context.CONTEXT_IGNORE_SECURITY) != 0; 2357 } 2358 2359 @UnsupportedAppUsage 2360 @TestApi 2361 @Override getDisplay()2362 public Display getDisplay() { 2363 if (mDisplay == null) { 2364 return mResourcesManager.getAdjustedDisplay(Display.DEFAULT_DISPLAY, 2365 mResources); 2366 } 2367 2368 return mDisplay; 2369 } 2370 2371 @Override getDisplayId()2372 public int getDisplayId() { 2373 return mDisplay != null ? mDisplay.getDisplayId() : Display.DEFAULT_DISPLAY; 2374 } 2375 2376 @Override updateDisplay(int displayId)2377 public void updateDisplay(int displayId) { 2378 mDisplay = mResourcesManager.getAdjustedDisplay(displayId, mResources); 2379 } 2380 2381 @Override getDisplayAdjustments(int displayId)2382 public DisplayAdjustments getDisplayAdjustments(int displayId) { 2383 return mResources.getDisplayAdjustments(); 2384 } 2385 2386 @Override getDataDir()2387 public File getDataDir() { 2388 if (mPackageInfo != null) { 2389 File res = null; 2390 if (isCredentialProtectedStorage()) { 2391 res = mPackageInfo.getCredentialProtectedDataDirFile(); 2392 } else if (isDeviceProtectedStorage()) { 2393 res = mPackageInfo.getDeviceProtectedDataDirFile(); 2394 } else { 2395 res = mPackageInfo.getDataDirFile(); 2396 } 2397 2398 if (res != null) { 2399 if (!res.exists() && android.os.Process.myUid() == android.os.Process.SYSTEM_UID) { 2400 Log.wtf(TAG, "Data directory doesn't exist for package " + getPackageName(), 2401 new Throwable()); 2402 } 2403 return res; 2404 } else { 2405 throw new RuntimeException( 2406 "No data directory found for package " + getPackageName()); 2407 } 2408 } else { 2409 throw new RuntimeException( 2410 "No package details found for package " + getPackageName()); 2411 } 2412 } 2413 2414 @Override getDir(String name, int mode)2415 public File getDir(String name, int mode) { 2416 checkMode(mode); 2417 name = "app_" + name; 2418 File file = makeFilename(getDataDir(), name); 2419 if (!file.exists()) { 2420 file.mkdir(); 2421 setFilePermissionsFromMode(file.getPath(), mode, 2422 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); 2423 } 2424 return file; 2425 } 2426 2427 /** {@hide} */ 2428 @Override getUser()2429 public UserHandle getUser() { 2430 return mUser; 2431 } 2432 2433 /** {@hide} */ 2434 @Override getUserId()2435 public int getUserId() { 2436 return mUser.getIdentifier(); 2437 } 2438 2439 /** @hide */ 2440 @Override getAutofillClient()2441 public AutofillClient getAutofillClient() { 2442 return mAutofillClient; 2443 } 2444 2445 /** @hide */ 2446 @Override setAutofillClient(AutofillClient client)2447 public void setAutofillClient(AutofillClient client) { 2448 mAutofillClient = client; 2449 } 2450 2451 /** @hide */ 2452 @Override getAutofillOptions()2453 public AutofillOptions getAutofillOptions() { 2454 return mAutofillOptions; 2455 } 2456 2457 /** @hide */ 2458 @Override setAutofillOptions(AutofillOptions options)2459 public void setAutofillOptions(AutofillOptions options) { 2460 mAutofillOptions = options; 2461 } 2462 2463 /** @hide */ 2464 @Override getContentCaptureOptions()2465 public ContentCaptureOptions getContentCaptureOptions() { 2466 return mContentCaptureOptions; 2467 } 2468 2469 /** @hide */ 2470 @Override setContentCaptureOptions(ContentCaptureOptions options)2471 public void setContentCaptureOptions(ContentCaptureOptions options) { 2472 mContentCaptureOptions = options; 2473 } 2474 2475 @UnsupportedAppUsage createSystemContext(ActivityThread mainThread)2476 static ContextImpl createSystemContext(ActivityThread mainThread) { 2477 LoadedApk packageInfo = new LoadedApk(mainThread); 2478 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0, 2479 null, null); 2480 context.setResources(packageInfo.getResources()); 2481 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(), 2482 context.mResourcesManager.getDisplayMetrics()); 2483 return context; 2484 } 2485 2486 /** 2487 * System Context to be used for UI. This Context has resources that can be themed. 2488 * Make sure that the created system UI context shares the same LoadedApk as the system context. 2489 * @param systemContext The system context which created by 2490 * {@link #createSystemContext(ActivityThread)}. 2491 * @param displayId The ID of the display where the UI is shown. 2492 */ createSystemUiContext(ContextImpl systemContext, int displayId)2493 static ContextImpl createSystemUiContext(ContextImpl systemContext, int displayId) { 2494 final LoadedApk packageInfo = systemContext.mPackageInfo; 2495 ContextImpl context = new ContextImpl(null, systemContext.mMainThread, packageInfo, null, 2496 null, null, 0, null, null); 2497 context.setResources(createResources(null, packageInfo, null, displayId, null, 2498 packageInfo.getCompatibilityInfo())); 2499 context.updateDisplay(displayId); 2500 return context; 2501 } 2502 2503 /** 2504 * The overloaded method of {@link #createSystemUiContext(ContextImpl, int)}. 2505 * Uses {@Code Display.DEFAULT_DISPLAY} as the target display. 2506 */ createSystemUiContext(ContextImpl systemContext)2507 static ContextImpl createSystemUiContext(ContextImpl systemContext) { 2508 return createSystemUiContext(systemContext, Display.DEFAULT_DISPLAY); 2509 } 2510 2511 @UnsupportedAppUsage createAppContext(ActivityThread mainThread, LoadedApk packageInfo)2512 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) { 2513 return createAppContext(mainThread, packageInfo, null); 2514 } 2515 createAppContext(ActivityThread mainThread, LoadedApk packageInfo, String opPackageName)2516 static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo, 2517 String opPackageName) { 2518 if (packageInfo == null) throw new IllegalArgumentException("packageInfo"); 2519 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0, 2520 null, opPackageName); 2521 context.setResources(packageInfo.getResources()); 2522 return context; 2523 } 2524 2525 @UnsupportedAppUsage createActivityContext(ActivityThread mainThread, LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId, Configuration overrideConfiguration)2526 static ContextImpl createActivityContext(ActivityThread mainThread, 2527 LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId, 2528 Configuration overrideConfiguration) { 2529 if (packageInfo == null) throw new IllegalArgumentException("packageInfo"); 2530 2531 String[] splitDirs = packageInfo.getSplitResDirs(); 2532 ClassLoader classLoader = packageInfo.getClassLoader(); 2533 2534 if (packageInfo.getApplicationInfo().requestsIsolatedSplitLoading()) { 2535 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, "SplitDependencies"); 2536 try { 2537 classLoader = packageInfo.getSplitClassLoader(activityInfo.splitName); 2538 splitDirs = packageInfo.getSplitPaths(activityInfo.splitName); 2539 } catch (NameNotFoundException e) { 2540 // Nothing above us can handle a NameNotFoundException, better crash. 2541 throw new RuntimeException(e); 2542 } finally { 2543 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2544 } 2545 } 2546 2547 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, activityInfo.splitName, 2548 activityToken, null, 0, classLoader, null); 2549 2550 // Clamp display ID to DEFAULT_DISPLAY if it is INVALID_DISPLAY. 2551 displayId = (displayId != Display.INVALID_DISPLAY) ? displayId : Display.DEFAULT_DISPLAY; 2552 2553 final CompatibilityInfo compatInfo = (displayId == Display.DEFAULT_DISPLAY) 2554 ? packageInfo.getCompatibilityInfo() 2555 : CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO; 2556 2557 final ResourcesManager resourcesManager = ResourcesManager.getInstance(); 2558 2559 // Create the base resources for which all configuration contexts for this Activity 2560 // will be rebased upon. 2561 context.setResources(resourcesManager.createBaseActivityResources(activityToken, 2562 packageInfo.getResDir(), 2563 splitDirs, 2564 packageInfo.getOverlayDirs(), 2565 packageInfo.getApplicationInfo().sharedLibraryFiles, 2566 displayId, 2567 overrideConfiguration, 2568 compatInfo, 2569 classLoader)); 2570 context.mDisplay = resourcesManager.getAdjustedDisplay(displayId, 2571 context.getResources()); 2572 return context; 2573 } 2574 ContextImpl(@ullable ContextImpl container, @NonNull ActivityThread mainThread, @NonNull LoadedApk packageInfo, @Nullable String splitName, @Nullable IBinder activityToken, @Nullable UserHandle user, int flags, @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName)2575 private ContextImpl(@Nullable ContextImpl container, @NonNull ActivityThread mainThread, 2576 @NonNull LoadedApk packageInfo, @Nullable String splitName, 2577 @Nullable IBinder activityToken, @Nullable UserHandle user, int flags, 2578 @Nullable ClassLoader classLoader, @Nullable String overrideOpPackageName) { 2579 mOuterContext = this; 2580 2581 // If creator didn't specify which storage to use, use the default 2582 // location for application. 2583 if ((flags & (Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE 2584 | Context.CONTEXT_DEVICE_PROTECTED_STORAGE)) == 0) { 2585 final File dataDir = packageInfo.getDataDirFile(); 2586 if (Objects.equals(dataDir, packageInfo.getCredentialProtectedDataDirFile())) { 2587 flags |= Context.CONTEXT_CREDENTIAL_PROTECTED_STORAGE; 2588 } else if (Objects.equals(dataDir, packageInfo.getDeviceProtectedDataDirFile())) { 2589 flags |= Context.CONTEXT_DEVICE_PROTECTED_STORAGE; 2590 } 2591 } 2592 2593 mMainThread = mainThread; 2594 mActivityToken = activityToken; 2595 mFlags = flags; 2596 2597 if (user == null) { 2598 user = Process.myUserHandle(); 2599 } 2600 mUser = user; 2601 2602 mPackageInfo = packageInfo; 2603 mSplitName = splitName; 2604 mClassLoader = classLoader; 2605 mResourcesManager = ResourcesManager.getInstance(); 2606 2607 String opPackageName; 2608 2609 if (container != null) { 2610 mBasePackageName = container.mBasePackageName; 2611 opPackageName = container.mOpPackageName; 2612 setResources(container.mResources); 2613 mDisplay = container.mDisplay; 2614 } else { 2615 mBasePackageName = packageInfo.mPackageName; 2616 ApplicationInfo ainfo = packageInfo.getApplicationInfo(); 2617 if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) { 2618 // Special case: system components allow themselves to be loaded in to other 2619 // processes. For purposes of app ops, we must then consider the context as 2620 // belonging to the package of this process, not the system itself, otherwise 2621 // the package+uid verifications in app ops will fail. 2622 opPackageName = ActivityThread.currentPackageName(); 2623 } else { 2624 opPackageName = mBasePackageName; 2625 } 2626 } 2627 2628 mOpPackageName = overrideOpPackageName != null ? overrideOpPackageName : opPackageName; 2629 2630 mContentResolver = new ApplicationContentResolver(this, mainThread); 2631 } 2632 setResources(Resources r)2633 void setResources(Resources r) { 2634 if (r instanceof CompatResources) { 2635 ((CompatResources) r).setContext(this); 2636 } 2637 mResources = r; 2638 } 2639 installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader)2640 void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) { 2641 mPackageInfo.installSystemApplicationInfo(info, classLoader); 2642 } 2643 2644 @UnsupportedAppUsage scheduleFinalCleanup(String who, String what)2645 final void scheduleFinalCleanup(String who, String what) { 2646 mMainThread.scheduleContextCleanup(this, who, what); 2647 } 2648 performFinalCleanup(String who, String what)2649 final void performFinalCleanup(String who, String what) { 2650 //Log.i(TAG, "Cleanup up context: " + this); 2651 mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); 2652 } 2653 2654 @UnsupportedAppUsage getReceiverRestrictedContext()2655 final Context getReceiverRestrictedContext() { 2656 if (mReceiverRestrictedContext != null) { 2657 return mReceiverRestrictedContext; 2658 } 2659 return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); 2660 } 2661 2662 @UnsupportedAppUsage setOuterContext(Context context)2663 final void setOuterContext(Context context) { 2664 mOuterContext = context; 2665 } 2666 2667 @UnsupportedAppUsage getOuterContext()2668 final Context getOuterContext() { 2669 return mOuterContext; 2670 } 2671 2672 @Override 2673 @UnsupportedAppUsage getActivityToken()2674 public IBinder getActivityToken() { 2675 return mActivityToken; 2676 } 2677 checkMode(int mode)2678 private void checkMode(int mode) { 2679 if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) { 2680 if ((mode & MODE_WORLD_READABLE) != 0) { 2681 throw new SecurityException("MODE_WORLD_READABLE no longer supported"); 2682 } 2683 if ((mode & MODE_WORLD_WRITEABLE) != 0) { 2684 throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported"); 2685 } 2686 } 2687 } 2688 2689 @SuppressWarnings("deprecation") setFilePermissionsFromMode(String name, int mode, int extraPermissions)2690 static void setFilePermissionsFromMode(String name, int mode, 2691 int extraPermissions) { 2692 int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR 2693 |FileUtils.S_IRGRP|FileUtils.S_IWGRP 2694 |extraPermissions; 2695 if ((mode&MODE_WORLD_READABLE) != 0) { 2696 perms |= FileUtils.S_IROTH; 2697 } 2698 if ((mode&MODE_WORLD_WRITEABLE) != 0) { 2699 perms |= FileUtils.S_IWOTH; 2700 } 2701 if (DEBUG) { 2702 Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) 2703 + ", perms=0x" + Integer.toHexString(perms)); 2704 } 2705 FileUtils.setPermissions(name, perms, -1, -1); 2706 } 2707 makeFilename(File base, String name)2708 private File makeFilename(File base, String name) { 2709 if (name.indexOf(File.separatorChar) < 0) { 2710 final File res = new File(base, name); 2711 // We report as filesystem access here to give us the best shot at 2712 // detecting apps that will pass the path down to native code. 2713 BlockGuard.getVmPolicy().onPathAccess(res.getPath()); 2714 return res; 2715 } 2716 throw new IllegalArgumentException( 2717 "File " + name + " contains a path separator"); 2718 } 2719 2720 /** 2721 * Ensure that given directories exist, trying to create them if missing. If 2722 * unable to create, they are filtered by replacing with {@code null}. 2723 */ ensureExternalDirsExistOrFilter(File[] dirs)2724 private File[] ensureExternalDirsExistOrFilter(File[] dirs) { 2725 final StorageManager sm = getSystemService(StorageManager.class); 2726 final File[] result = new File[dirs.length]; 2727 for (int i = 0; i < dirs.length; i++) { 2728 File dir = dirs[i]; 2729 if (!dir.exists()) { 2730 if (!dir.mkdirs()) { 2731 // recheck existence in case of cross-process race 2732 if (!dir.exists()) { 2733 // Failing to mkdir() may be okay, since we might not have 2734 // enough permissions; ask vold to create on our behalf. 2735 try { 2736 sm.mkdirs(dir); 2737 } catch (Exception e) { 2738 Log.w(TAG, "Failed to ensure " + dir + ": " + e); 2739 dir = null; 2740 } 2741 } 2742 } 2743 } 2744 result[i] = dir; 2745 } 2746 return result; 2747 } 2748 2749 // ---------------------------------------------------------------------- 2750 // ---------------------------------------------------------------------- 2751 // ---------------------------------------------------------------------- 2752 2753 private static final class ApplicationContentResolver extends ContentResolver { 2754 @UnsupportedAppUsage 2755 private final ActivityThread mMainThread; 2756 ApplicationContentResolver(Context context, ActivityThread mainThread)2757 public ApplicationContentResolver(Context context, ActivityThread mainThread) { 2758 super(context); 2759 mMainThread = Preconditions.checkNotNull(mainThread); 2760 } 2761 2762 @Override 2763 @UnsupportedAppUsage acquireProvider(Context context, String auth)2764 protected IContentProvider acquireProvider(Context context, String auth) { 2765 return mMainThread.acquireProvider(context, 2766 ContentProvider.getAuthorityWithoutUserId(auth), 2767 resolveUserIdFromAuthority(auth), true); 2768 } 2769 2770 @Override acquireExistingProvider(Context context, String auth)2771 protected IContentProvider acquireExistingProvider(Context context, String auth) { 2772 return mMainThread.acquireExistingProvider(context, 2773 ContentProvider.getAuthorityWithoutUserId(auth), 2774 resolveUserIdFromAuthority(auth), true); 2775 } 2776 2777 @Override releaseProvider(IContentProvider provider)2778 public boolean releaseProvider(IContentProvider provider) { 2779 return mMainThread.releaseProvider(provider, true); 2780 } 2781 2782 @Override acquireUnstableProvider(Context c, String auth)2783 protected IContentProvider acquireUnstableProvider(Context c, String auth) { 2784 return mMainThread.acquireProvider(c, 2785 ContentProvider.getAuthorityWithoutUserId(auth), 2786 resolveUserIdFromAuthority(auth), false); 2787 } 2788 2789 @Override releaseUnstableProvider(IContentProvider icp)2790 public boolean releaseUnstableProvider(IContentProvider icp) { 2791 return mMainThread.releaseProvider(icp, false); 2792 } 2793 2794 @Override unstableProviderDied(IContentProvider icp)2795 public void unstableProviderDied(IContentProvider icp) { 2796 mMainThread.handleUnstableProviderDied(icp.asBinder(), true); 2797 } 2798 2799 @Override appNotRespondingViaProvider(IContentProvider icp)2800 public void appNotRespondingViaProvider(IContentProvider icp) { 2801 mMainThread.appNotRespondingViaProvider(icp.asBinder()); 2802 } 2803 2804 /** @hide */ resolveUserIdFromAuthority(String auth)2805 protected int resolveUserIdFromAuthority(String auth) { 2806 return ContentProvider.getUserIdFromAuthority(auth, getUserId()); 2807 } 2808 } 2809 } 2810