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