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